Coverage for dao/league_dao.py: 45.90%
112 statements
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 20:17 +0000
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 20:17 +0000
1"""
2League Data Access Object.
4Handles all database operations related to leagues and divisions including:
5- League CRUD operations
6- Division CRUD operations
7- League-division associations
8"""
10import structlog
12from dao.base_dao import BaseDAO, dao_cache, invalidates_cache
14logger = structlog.get_logger()
16# Cache patterns for invalidation
17LEAGUES_CACHE_PATTERN = "mt:dao:leagues:*"
18DIVISIONS_CACHE_PATTERN = "mt:dao:divisions:*"
21class LeagueDAO(BaseDAO):
22 """Data access object for league and division operations."""
24 # === League Query Methods ===
26 @dao_cache("leagues:all:{include_test}")
27 def get_all_leagues(self, include_test: bool = False) -> list[dict]:
28 """Get all leagues ordered by name.
30 include_test gates the SB-85 test partition: real/anonymous viewers pass
31 False (test leagues hidden); admins + test users pass True. The cache key
32 varies by include_test so the two audiences never share a cached result.
33 """
34 try:
35 query = self.client.table("leagues").select("*")
36 if not include_test:
37 query = query.eq("is_test", False)
38 response = query.order("name").execute()
39 return response.data
40 except Exception:
41 logger.exception("Error querying leagues")
42 return []
44 @dao_cache("leagues:by_id:{league_id}")
45 def get_league_by_id(self, league_id: int) -> dict | None:
46 """Get league by ID, or None when there is no such league.
48 A database error is raised, not turned into None: "the lookup failed"
49 must not read as "not found".
50 """
51 response = self.client.table("leagues").select("*").eq("id", league_id).limit(1).execute()
52 return response.data[0] if response.data else None
54 # === League CRUD Methods ===
56 @invalidates_cache(LEAGUES_CACHE_PATTERN)
57 def create_league(self, league_data: dict) -> dict:
58 """Create new league."""
59 try:
60 response = self.client.table("leagues").insert(league_data).execute()
61 return response.data[0]
62 except Exception:
63 logger.exception("Error creating league")
64 raise
66 @invalidates_cache(LEAGUES_CACHE_PATTERN)
67 def update_league(self, league_id: int, league_data: dict) -> dict | None:
68 """Update league."""
69 try:
70 response = self.client.table("leagues").update(league_data).eq("id", league_id).execute()
71 return response.data[0] if response.data else None
72 except Exception:
73 logger.exception("Error updating league", league_id=league_id)
74 raise
76 @invalidates_cache(LEAGUES_CACHE_PATTERN)
77 def delete_league(self, league_id: int) -> bool:
78 """Delete league (will fail if divisions exist due to FK constraint)."""
79 try:
80 self.client.table("leagues").delete().eq("id", league_id).execute()
81 return True
82 except Exception:
83 logger.exception("Error deleting league", league_id=league_id)
84 raise
86 # === Division Query Methods ===
88 @dao_cache("divisions:all")
89 def get_all_divisions(self) -> list[dict]:
90 """Get all divisions with league info."""
91 try:
92 response = (
93 self.client.table("divisions")
94 .select("*, leagues!divisions_league_id_fkey(id, name, description, is_active)")
95 .order("name")
96 .execute()
97 )
98 return response.data
99 except Exception:
100 logger.exception("Error querying divisions")
101 return []
103 @dao_cache("divisions:by_league:{league_id}")
104 def get_divisions_by_league(self, league_id: int) -> list[dict]:
105 """Get divisions filtered by league."""
106 try:
107 response = (
108 self.client.table("divisions")
109 .select("*, leagues!divisions_league_id_fkey(id, name, description)")
110 .eq("league_id", league_id)
111 .order("name")
112 .execute()
113 )
114 return response.data
115 except Exception:
116 logger.exception("Error querying divisions for league", league_id=league_id)
117 return []
119 def get_league_by_name(self, name: str) -> dict | None:
120 """Get a league by name (case-insensitive exact match).
122 For match-scraper integration: the feed names its competition
123 ("Homegrown", "Academy", "Flex"), and that name has to become the
124 league_id that scopes the division lookup below. No caching - used
125 for scraper lookups.
126 """
127 try:
128 response = self.client.table("leagues").select("id, name").ilike("name", name).limit(1).execute()
129 if response.data and len(response.data) > 0:
130 return response.data[0]
131 return None
132 except Exception:
133 logger.exception("Error getting league by name", league_name=name)
134 return None
136 def get_division_by_name(self, name: str, league_id: int | None = None) -> dict | None:
137 """Get a division by name (case-insensitive exact match), scoped to a league.
139 Returns the division record (id, name, league_id).
140 For match-scraper integration, this helps look up divisions by name.
141 No caching - used for scraper lookups.
143 `league_id` is not optional in spirit, only in signature. Division
144 names are unique per league (divisions_name_league_id_key), NOT
145 globally: the 2026-2027 MLS Next feeds put "Florida", "Frontier",
146 "Northwest" and "Southeast" in both Homegrown and MLS NEXT Flex.
147 Without the scope this returns whichever row the database hands back
148 first, and a Flex match lands in a Homegrown table with nothing to
149 show that it went wrong. Callers that know their league must pass it.
151 When no league_id is given and the name is ambiguous, return None
152 rather than guessing - an unresolved division is reported and fixed,
153 a silently wrong one is not.
154 """
155 try:
156 query = self.client.table("divisions").select("id, name, league_id").ilike("name", name)
157 if league_id is not None:
158 query = query.eq("league_id", league_id)
159 response = query.limit(2).execute()
161 rows = response.data or []
162 if not rows:
163 return None
164 if len(rows) > 1:
165 logger.warning(
166 "Division name is ambiguous across leagues - refusing to guess",
167 division_name=name,
168 league_ids=sorted({r.get("league_id") for r in rows}),
169 )
170 return None
171 return rows[0]
173 except Exception:
174 logger.exception("Error getting division by name", division_name=name, league_id=league_id)
175 return None
177 # === Division CRUD Methods ===
179 @invalidates_cache(DIVISIONS_CACHE_PATTERN)
180 def create_division(self, division_data: dict) -> dict:
181 """Create a new division.
183 Args:
184 division_data: Dict with keys: name, description (optional), league_id (required)
185 """
186 try:
187 logger.debug("Creating division", division_data=division_data)
188 result = self.client.table("divisions").insert(division_data).execute()
189 logger.debug("Division created successfully", division=result.data[0])
190 return result.data[0]
191 except Exception as e:
192 logger.exception("Error creating division")
193 raise e
195 @invalidates_cache(DIVISIONS_CACHE_PATTERN)
196 def update_division(self, division_id: int, division_data: dict) -> dict | None:
197 """Update a division.
199 Args:
200 division_id: Division ID to update
201 division_data: Dict with any of: name, description, league_id
202 """
203 try:
204 result = self.client.table("divisions").update(division_data).eq("id", division_id).execute()
205 return result.data[0] if result.data else None
206 except Exception as e:
207 logger.exception("Error updating division")
208 raise e
210 @invalidates_cache(DIVISIONS_CACHE_PATTERN)
211 def delete_division(self, division_id: int) -> bool:
212 """Delete a division."""
213 try:
214 result = self.client.table("divisions").delete().eq("id", division_id).execute()
215 return len(result.data) > 0
216 except Exception as e:
217 logger.exception("Error deleting division")
218 raise e