-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb_functions.py
More file actions
47 lines (41 loc) · 1.49 KB
/
db_functions.py
File metadata and controls
47 lines (41 loc) · 1.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from db_setup import Base, RankingV1
import util
import uuid
from settings import Settings
from typing import Tuple, List, Dict
import exceptions
settings = Settings()
# Connects to the database
engine = create_engine(settings.database_address)
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
def add_ranking(event_code: str, team: str, ranking: int, won: bool):
session = DBSession()
if type(event_code) is not str or type(team) is not str or type(ranking) is not int or type(won) is not bool:
raise ValueError()
if session.query(RankingV1).filter(RankingV1.event_code == event_code).filter(RankingV1.team == team).first() is not None:
session.close()
raise exceptions.TeamAtEventAlreadyRecorded()
if session.query(RankingV1).filter(RankingV1.event_code == event_code).filter(RankingV1.ranking == ranking).first() is not None:
session.close()
raise exceptions.RankAtEventAlreadyRecorded()
session.add(RankingV1(
event_code=event_code,
team=team,
ranking=ranking,
won=won
))
session.commit()
session.close()
def get_rankings() -> Dict[int, Dict[str, int]]:
session = DBSession()
rankings = {}
for ranking in session.query(RankingV1).all(): # type: RankingV1
rank = rankings.get(ranking.ranking, {})
rank['instances'] = rank.get('instances', 0) + 1
win_delta = 1 if ranking.won else 0
rank['wins'] = rank.get('wins', 0) + win_delta
rankings[ranking.ranking] = rank
return rankings