Skip to content

Commit

Permalink
fixup! Add newtypes for primary keys
Browse files Browse the repository at this point in the history
  • Loading branch information
evroon committed Feb 23, 2024
1 parent 3b4ffda commit 726b6e2
Show file tree
Hide file tree
Showing 20 changed files with 198 additions and 131 deletions.
4 changes: 2 additions & 2 deletions backend/bracket/logic/planning/matches.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
)
from bracket.sql.stages import get_full_tournament_details
from bracket.sql.tournaments import sql_get_tournament
from bracket.utils.id_types import MatchId, TournamentId
from bracket.utils.id_types import CourtId, MatchId, TournamentId
from bracket.utils.types import assert_some


Expand Down Expand Up @@ -82,7 +82,7 @@ class MatchPosition(NamedTuple):
async def reorder_matches_for_court(
tournament: Tournament,
scheduled_matches: list[MatchPosition],
court_id: int,
court_id: CourtId,
) -> None:
matches_this_court = sorted(
(match_pos for match_pos in scheduled_matches if match_pos.match.court_id == court_id),
Expand Down
18 changes: 11 additions & 7 deletions backend/bracket/logic/ranking/elo.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import math
from collections import defaultdict
from decimal import Decimal
from typing import TypeVar

from bracket.database import database
from bracket.models.db.match import MatchWithDetailsDefinitive
Expand All @@ -10,18 +11,21 @@
from bracket.sql.players import get_all_players_in_tournament, update_player_stats
from bracket.sql.stages import get_full_tournament_details
from bracket.sql.teams import update_team_stats
from bracket.utils.id_types import TournamentId
from bracket.utils.id_types import PlayerId, TeamId, TournamentId
from bracket.utils.types import assert_some

K = 32
D = 400


TeamIdOrPlayerId = TypeVar("TeamIdOrPlayerId", bound=PlayerId | TeamId)


def set_statistics_for_player_or_team(
team_index: int,
stats: defaultdict[int, PlayerStatistics],
stats: defaultdict[TeamIdOrPlayerId, PlayerStatistics],
match: MatchWithDetailsDefinitive,
team_or_player_id: int,
team_or_player_id: TeamIdOrPlayerId,
rating_team1_before: float,
rating_team2_before: float,
) -> None:
Expand Down Expand Up @@ -49,9 +53,9 @@ def set_statistics_for_player_or_team(

def determine_ranking_for_stage_items(
stage_items: list[StageItemWithRounds],
) -> tuple[defaultdict[int, PlayerStatistics], defaultdict[int, PlayerStatistics]]:
player_x_stats: defaultdict[int, PlayerStatistics] = defaultdict(PlayerStatistics)
team_x_stats: defaultdict[int, PlayerStatistics] = defaultdict(PlayerStatistics)
) -> tuple[defaultdict[PlayerId, PlayerStatistics], defaultdict[TeamId, PlayerStatistics]]:
player_x_stats: defaultdict[PlayerId, PlayerStatistics] = defaultdict(PlayerStatistics)
team_x_stats: defaultdict[TeamId, PlayerStatistics] = defaultdict(PlayerStatistics)
matches = [
match
for stage_item in stage_items
Expand Down Expand Up @@ -101,7 +105,7 @@ def determine_ranking_for_stage_items(

def determine_team_ranking_for_stage_item(
stage_item: StageItemWithRounds,
) -> list[tuple[int, PlayerStatistics]]:
) -> list[tuple[TeamId, PlayerStatistics]]:
_, team_ranking = determine_ranking_for_stage_items([stage_item])
return sorted(team_ranking.items(), key=lambda x: x[1].elo_score, reverse=True)

Expand Down
9 changes: 5 additions & 4 deletions backend/bracket/logic/scheduling/ladder_teams.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,16 @@
)
from bracket.models.db.team import FullTeamWithPlayers
from bracket.models.db.util import RoundWithMatches
from bracket.utils.id_types import TeamId
from bracket.utils.types import assert_some


def get_draft_round_team_ids(draft_round: RoundWithMatches) -> list[int]:
def get_draft_round_team_ids(draft_round: RoundWithMatches) -> list[TeamId]:
return [
team
team_id
for match in draft_round.matches
if isinstance(match, MatchWithDetailsDefinitive)
for team in match.team_ids
for team_id in match.team_ids
]


Expand All @@ -37,7 +38,7 @@ def get_previous_matches_hashes(rounds: list[RoundWithMatches]) -> frozenset[str


def get_number_of_teams_played_per_team(
rounds: list[RoundWithMatches], excluded_team_ids: frozenset[int]
rounds: list[RoundWithMatches], excluded_team_ids: frozenset[TeamId]
) -> dict[int, int]:
result: dict[int, int] = defaultdict(int)

Expand Down
6 changes: 3 additions & 3 deletions backend/bracket/models/db/match.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from bracket.models.db.court import Court
from bracket.models.db.shared import BaseModelORM
from bracket.models.db.team import FullTeamWithPlayers, TeamWithPlayers
from bracket.utils.id_types import CourtId, MatchId, RoundId, StageItemId, TeamId
from bracket.utils.id_types import CourtId, MatchId, PlayerId, RoundId, StageItemId, TeamId
from bracket.utils.types import assert_some


Expand Down Expand Up @@ -67,7 +67,7 @@ def teams(self) -> list[FullTeamWithPlayers]:
return [self.team1, self.team2]

@property
def team_ids(self) -> list[int]:
def team_ids(self) -> list[TeamId]:
return [assert_some(self.team1.id), assert_some(self.team2.id)]

def get_team_ids_hashes(self) -> list[str]:
Expand All @@ -77,7 +77,7 @@ def get_team_ids_hashes(self) -> list[str]:
]

@property
def player_ids(self) -> list[int]:
def player_ids(self) -> list[PlayerId]:
return self.team1.player_ids + self.team2.player_ids


Expand Down
4 changes: 2 additions & 2 deletions backend/bracket/models/db/player_x_team.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
from bracket.models.db.shared import BaseModelORM
from bracket.utils.id_types import PlayerId, TeamId
from bracket.utils.id_types import PlayerId, PlayerXTeamId, TeamId


class PlayerXTeam(BaseModelORM):
id: int | None = None
id: PlayerXTeamId | None = None
player_id: PlayerId
team_id: TeamId
2 changes: 1 addition & 1 deletion backend/bracket/models/db/team.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ class TeamWithPlayers(BaseModel):
name: str

@property
def player_ids(self) -> list[int]:
def player_ids(self) -> list[PlayerId]:
return [assert_some(player.id) for player in self.players]

@field_validator("players", mode="before")
Expand Down
4 changes: 2 additions & 2 deletions backend/bracket/models/db/user_x_club.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from enum import auto

from bracket.models.db.shared import BaseModelORM
from bracket.utils.id_types import ClubId, UserId
from bracket.utils.id_types import ClubId, UserId, UserXClubId
from bracket.utils.types import EnumAutoStr


Expand All @@ -11,7 +11,7 @@ class UserXClubRelation(EnumAutoStr):


class UserXClub(BaseModelORM):
id: int | None = None
id: UserXClubId | None = None
user_id: UserId
club_id: ClubId
relation: UserXClubRelation
3 changes: 2 additions & 1 deletion backend/bracket/models/db/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from bracket.models.db.stage import Stage
from bracket.models.db.stage_item import StageItem, StageType
from bracket.models.db.stage_item_inputs import StageItemInput
from bracket.utils.id_types import TeamId
from bracket.utils.types import assert_some


Expand All @@ -23,7 +24,7 @@ def handle_matches(values: list[Match]) -> list[Match]: # type: ignore[misc]
return []
return values

def get_team_ids(self) -> set[int]:
def get_team_ids(self) -> set[TeamId]:
return {
assert_some(team.id)
for match in self.matches
Expand Down
4 changes: 2 additions & 2 deletions backend/bracket/routes/teams.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,15 @@
sql_delete_team,
)
from bracket.utils.db import fetch_one_parsed
from bracket.utils.id_types import TeamId, TournamentId
from bracket.utils.id_types import PlayerId, TeamId, TournamentId
from bracket.utils.pagination import PaginationTeams
from bracket.utils.types import assert_some

router = APIRouter()


async def update_team_members(
team_id: TeamId, tournament_id: TournamentId, player_ids: set[int]
team_id: TeamId, tournament_id: TournamentId, player_ids: set[PlayerId]
) -> None:
[team] = await get_teams_with_members(tournament_id, team_id=team_id)

Expand Down
6 changes: 3 additions & 3 deletions backend/bracket/sql/courts.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from bracket.database import database
from bracket.models.db.court import Court, CourtBody
from bracket.utils.id_types import TournamentId
from bracket.utils.id_types import CourtId, TournamentId


async def get_all_courts_in_tournament(tournament_id: TournamentId) -> list[Court]:
Expand All @@ -15,7 +15,7 @@ async def get_all_courts_in_tournament(tournament_id: TournamentId) -> list[Cour


async def update_court(
tournament_id: TournamentId, court_id: int, court_body: CourtBody
tournament_id: TournamentId, court_id: CourtId, court_body: CourtBody
) -> list[Court]:
query = """
UPDATE courts
Expand All @@ -30,7 +30,7 @@ async def update_court(
return [Court.model_validate(dict(x._mapping)) for x in result]


async def sql_delete_court(tournament_id: TournamentId, court_id: int) -> None:
async def sql_delete_court(tournament_id: TournamentId, court_id: CourtId) -> None:
query = "DELETE FROM courts WHERE id = :court_id AND tournament_id = :tournament_id"
await database.fetch_one(
query=query, values={"court_id": court_id, "tournament_id": tournament_id}
Expand Down
8 changes: 4 additions & 4 deletions backend/bracket/sql/matches.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from bracket.database import database
from bracket.models.db.match import Match, MatchBody, MatchCreateBody
from bracket.models.db.tournament import Tournament
from bracket.utils.id_types import MatchId, StageItemId
from bracket.utils.id_types import CourtId, MatchId, StageItemId, TeamId


async def sql_delete_match(match_id: MatchId) -> None:
Expand Down Expand Up @@ -116,7 +116,7 @@ async def sql_update_match(match_id: MatchId, match: MatchBody, tournament: Tour


async def sql_update_team_ids_for_match(
match_id: MatchId, team1_id: int | None, team2_id: int | None = None
match_id: MatchId, team1_id: TeamId | None, team2_id: TeamId | None = None
) -> None:
query = """
UPDATE matches
Expand All @@ -131,7 +131,7 @@ async def sql_update_team_ids_for_match(

async def sql_reschedule_match(
match_id: MatchId,
court_id: int | None,
court_id: CourtId | None,
start_time: datetime_utc,
position_in_schedule: int | None,
duration_minutes: int,
Expand Down Expand Up @@ -167,7 +167,7 @@ async def sql_reschedule_match(

async def sql_reschedule_match_and_determine_duration_and_margin(
match_id: MatchId,
court_id: int | None,
court_id: CourtId | None,
start_time: datetime_utc,
position_in_schedule: int | None,
match: Match,
Expand Down
2 changes: 1 addition & 1 deletion backend/bracket/sql/rounds.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ async def sql_create_round(round_: RoundToInsert) -> RoundId:
VALUES (NOW(), :is_draft, :is_active, :name, :stage_item_id)
RETURNING id
"""
result: int = await database.fetch_val(
result: RoundId = await database.fetch_val(
query=query,
values={
"name": round_.name,
Expand Down
2 changes: 1 addition & 1 deletion backend/bracket/sql/stage_items.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ async def get_stage_item(


async def get_stage_items(
tournament_id: TournamentId, stage_item_ids: set[int]
tournament_id: TournamentId, stage_item_ids: set[StageItemId]
) -> list[StageItemWithRounds]:
stages = await get_full_tournament_details(tournament_id, stage_item_ids=stage_item_ids)
if len(stages) < 1:
Expand Down
12 changes: 7 additions & 5 deletions backend/bracket/sql/stages.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@
from bracket.database import database
from bracket.models.db.stage import Stage
from bracket.models.db.util import StageWithStageItems
from bracket.utils.id_types import RoundId, StageId, TournamentId
from bracket.utils.id_types import RoundId, StageId, StageItemId, TournamentId
from bracket.utils.types import dict_without_none


async def get_full_tournament_details(
tournament_id: TournamentId,
round_id: RoundId | None = None,
stage_id: StageId | None = None,
stage_item_ids: set[int] | None = None,
stage_item_ids: set[StageItemId] | None = None,
*,
no_draft_rounds: bool = False,
) -> list[StageWithStageItems]:
Expand Down Expand Up @@ -149,7 +149,7 @@ async def sql_create_stage(tournament_id: TournamentId) -> Stage:

async def get_next_stage_in_tournament(
tournament_id: TournamentId, direction: Literal["next", "previous"]
) -> int | None:
) -> StageId | None:
select_query = """
SELECT id
FROM stages
Expand Down Expand Up @@ -184,15 +184,17 @@ async def get_next_stage_in_tournament(
AND is_active IS FALSE
"""
return cast(
int | None,
StageId | None,
await database.execute(
query=select_query,
values={"tournament_id": tournament_id, "direction": direction},
),
)


async def sql_activate_next_stage(new_active_stage_id: int, tournament_id: TournamentId) -> None:
async def sql_activate_next_stage(
new_active_stage_id: StageId, tournament_id: TournamentId
) -> None:
update_query = """
UPDATE stages
SET is_active = (stages.id = :new_active_stage_id)
Expand Down
2 changes: 1 addition & 1 deletion backend/bracket/sql/teams.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from bracket.utils.types import dict_without_none


async def get_teams_by_id(team_ids: set[int], tournament_id: TournamentId) -> list[Team]:
async def get_teams_by_id(team_ids: set[TeamId], tournament_id: TournamentId) -> list[Team]:
if len(team_ids) < 1:
return []

Check warning on line 13 in backend/bracket/sql/teams.py

View check run for this annotation

Codecov / codecov/patch

backend/bracket/sql/teams.py#L13

Added line #L13 was not covered by tests

Expand Down
2 changes: 1 addition & 1 deletion backend/bracket/sql/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ async def get_user_access_to_tournament(tournament_id: TournamentId, user_id: Us
return tournament_id in {tournament.id for tournament in result} # type: ignore[attr-defined]


async def get_which_clubs_has_user_access_to(user_id: UserId) -> set[int]:
async def get_which_clubs_has_user_access_to(user_id: UserId) -> set[ClubId]:
query = """
SELECT club_id
FROM users_x_clubs
Expand Down
Loading

0 comments on commit 726b6e2

Please sign in to comment.