97 lines
2.8 KiB
Python
97 lines
2.8 KiB
Python
from sqlite3 import Connection, Cursor
|
|
from database import SmartCursor
|
|
|
|
|
|
class KeyTable:
|
|
key: str
|
|
game_table_id: number
|
|
key_file: str
|
|
created: bool
|
|
updated: bool
|
|
|
|
def __init__(
|
|
self, key: str, game_table_id: int, key_file: str, created: bool = True, updated: bool = True
|
|
):
|
|
self.key = key
|
|
self.game_table_id = game_table_id
|
|
self.key_file = key_file
|
|
self.created = created
|
|
self.updated = updated
|
|
|
|
def toJson(self):
|
|
return {"key": self.key, "table_id": self.game_table_id, "key_file": self.key_file}
|
|
|
|
def reserve(self, game_table_id):
|
|
self.game_table_id = game_table_id
|
|
self.updated = False
|
|
|
|
def release(self):
|
|
self.game_table_id = None
|
|
self.updated = False
|
|
|
|
def commit(self, cursor):
|
|
if not self.created:
|
|
cursor.execute(
|
|
"""INSERT INTO game_keys
|
|
(key, game_table_id)
|
|
VALUES (?, ?)
|
|
""",
|
|
(
|
|
self.key,
|
|
self.game_table_id,
|
|
),
|
|
)
|
|
self.created = True
|
|
self.updated = True
|
|
if not self.updated:
|
|
cursor.execute(
|
|
"""UPDATE game_keys
|
|
SET game_table_id = ?
|
|
WHERE key = ?""",
|
|
(
|
|
self.game_table_id,
|
|
self.key,
|
|
),
|
|
)
|
|
self.updated = True
|
|
|
|
|
|
class KeyService:
|
|
|
|
connection: Connection
|
|
|
|
def __init__(self, connection: Connection):
|
|
self.connection = connection
|
|
|
|
def get_key_for_table(self, game_table_id, cursor=None) -> KeyTable:
|
|
with SmartCursor(cursor, self.connection) as smartCursor:
|
|
smartCursor.execute(
|
|
"""SELECT key, game_table_id, key_file
|
|
FROM game_keys
|
|
WHERE game_table_id = ?""",
|
|
(game_table_id,),
|
|
)
|
|
row = smartCursor.fetchone()
|
|
|
|
if row == None:
|
|
return None
|
|
|
|
return KeyTable(row[0], row[1], row[2])
|
|
|
|
def get_reserved_keys(self, cursor=None) -> KeyTable:
|
|
with SmartCursor(cursor, self.connection) as smartCursor:
|
|
smartCurosr.execute("""SELECT key, game_table_id, key_file
|
|
FROM game_keys
|
|
WHERE game_table_id IS NOT NULL""")
|
|
rows = smartCursor.fetchall()
|
|
|
|
return [KeyTable(row[0], row[1, row[2]]) for row in rows]
|
|
|
|
def get_free_keys(self, cursor=None) -> KeyTable:
|
|
with SmartCursor(cursor, self.connection) as smartCursor:
|
|
smartCursor.execute("""SELECT key, game_table_id, key_file
|
|
FROM game_keys
|
|
WHERE game_table_id IS NULL""")
|
|
rows = smartCursor.fetchall()
|
|
return [KeyTable(row[0], row[1], row[2]) for row in rows]
|