AnshulRaj commited on
Commit
549cfab
·
verified ·
1 Parent(s): 3a5aa2b

Sync storage.py from GitHub project

Browse files
Files changed (1) hide show
  1. storage.py +56 -0
storage.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """SQLite-backed persistence for saved games."""
2
+ from __future__ import annotations
3
+
4
+ import sqlite3
5
+ from pathlib import Path
6
+
7
+ from schema import CanvasGame
8
+
9
+ _DEFAULT_DB = Path(__file__).parent / "games.db"
10
+
11
+
12
+ class GameStore:
13
+ def __init__(self, db_path: Path = _DEFAULT_DB) -> None:
14
+ self.db_path = db_path
15
+ self._init_db()
16
+
17
+ def _init_db(self) -> None:
18
+ with sqlite3.connect(self.db_path) as conn:
19
+ conn.execute(
20
+ """
21
+ CREATE TABLE IF NOT EXISTS games (
22
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
23
+ name TEXT NOT NULL,
24
+ config_json TEXT NOT NULL,
25
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
26
+ )
27
+ """
28
+ )
29
+
30
+ def save_game(self, name: str, game: CanvasGame) -> int:
31
+ with sqlite3.connect(self.db_path) as conn:
32
+ cur = conn.execute(
33
+ "INSERT INTO games (name, config_json) VALUES (?, ?)",
34
+ (name, game.model_dump_json()),
35
+ )
36
+ return cur.lastrowid # type: ignore[return-value]
37
+
38
+ def load_game(self, game_id: int) -> CanvasGame:
39
+ with sqlite3.connect(self.db_path) as conn:
40
+ row = conn.execute(
41
+ "SELECT config_json FROM games WHERE id = ?", (game_id,)
42
+ ).fetchone()
43
+ if not row:
44
+ raise KeyError(f"Game {game_id} not found")
45
+ return CanvasGame.model_validate_json(row[0])
46
+
47
+ def list_games(self) -> list[dict]:
48
+ with sqlite3.connect(self.db_path) as conn:
49
+ rows = conn.execute(
50
+ "SELECT id, name, created_at FROM games ORDER BY created_at DESC"
51
+ ).fetchall()
52
+ return [{"id": r[0], "name": r[1], "created_at": r[2]} for r in rows]
53
+
54
+ def delete_game(self, game_id: int) -> None:
55
+ with sqlite3.connect(self.db_path) as conn:
56
+ conn.execute("DELETE FROM games WHERE id = ?", (game_id,))