summaryrefslogtreecommitdiff
path: root/persistence.py
diff options
context:
space:
mode:
Diffstat (limited to 'persistence.py')
-rw-r--r--persistence.py53
1 files changed, 49 insertions, 4 deletions
diff --git a/persistence.py b/persistence.py
index 6070b69..92452ce 100644
--- a/persistence.py
+++ b/persistence.py
@@ -1,10 +1,9 @@
-import sqlite3
+import sqlite3, typing
+from Types import *
class UserRepository:
- conn = None
-
- def __init__(self, db_path):
+ def __init__(self):
self.__initialize()
def __initialize(self):
@@ -47,3 +46,49 @@ class UserRepository:
text = alias)
cur.execute(query)
connection.commit()
+
+class StatsRepository:
+
+ def __init__(self):
+ self.__initialize()
+
+ def __getConnection(self):
+ return sqlite3.connect('db.sqlite')
+
+ def __initialize(self):
+ cur = self.__getConnection().cursor()
+ cur.execute("CREATE TABLE IF NOT EXISTS stats(user_id TEXT, display_name TEXT, level INT, matches_played INT, kills INT, wins INT)")
+ cur.execute("CREATE UNIQUE INDEX IF NOT EXISTS user_id_idx ON stats(user_id)")
+
+ async def putStats(self, user: User):
+ stats: UserStats = await user.fetch_stats()
+
+ connection = self.__getConnection()
+ cur = connection.cursor()
+ query = "INSERT OR REPLACE INTO stats(user_id, display_name, level, matches_played, kills, wins) VALUES('{user_id}', '{display_name}', {level}, {matches_played}, {kills}, {wins})".format(
+ user_id = user.id,
+ display_name = user.display_name,
+ level = stats.level,
+ matches_played = stats.matches_played,
+ kills = stats.kills,
+ wins = stats.wins)
+ cur.execute(query)
+ connection.commit()
+
+ def getStats(self) -> typing.List[UserStats]:
+ connection = self.__getConnection()
+ cur = connection.cursor()
+ query = "SELECT * FROM stats"
+ cur.execute(query)
+ result = cur.fetchall()
+ return [self.__mapFromDb(stats) for stats in result]
+
+ def __mapFromDb(self, record):
+ userStats = UserStats()
+ userStats.user_id = str(record[0])
+ userStats.user_display_name = str(record[1])
+ userStats.level = int(record[2])
+ userStats.matches_played = int(record[3])
+ userStats.kills = int(record[4])
+ userStats.wins = int(record[5])
+ return userStats \ No newline at end of file