This repository was archived by the owner on May 5, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
493 lines (413 loc) · 16 KB
/
database.py
File metadata and controls
493 lines (413 loc) · 16 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
from typing import Optional, Tuple
import sqlite3
from pathlib import Path
from exceptions import DatabaseError
Position = Tuple[int, int]
GAME_DB = Path(__file__).parent / "databases" / "game.db"
def get_connection(path: Optional[Path] = None):
"""Luo SQLite-yhteys WAL-tilassa.
Args:
path: Tietokantatiedoston polku (oletus: databases/game.db)
Returns:
sqlite3.Connection row_factory=Row ja WAL-tilassa
Huom:
Luo databases/-hakemiston jos ei ole olemassa.
Timeout 10 sekuntia rinnakkaiskäyttöä varten.
"""
p = path or GAME_DB
# Varmista että databases-hakemisto on olemassa
p.parent.mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(str(p), timeout=10.0)
conn.row_factory = sqlite3.Row
# Käytä WAL-tilaa paremman rinnakkaisuuden vuoksi
conn.execute("PRAGMA journal_mode=WAL")
return conn
def init_game_db(conn: sqlite3.Connection):
"""Alusta tietokannan rakenne (idempotentin - turvallinen kutsua useasti).
Luo taulut:
- game_objects: Fyysiset objektit UNIQUE(x,y) rajoitteella
- game_settings: Avain-arvo -varasto pelitilalle
- game_events: Tapahtumaloki
Args:
conn: Tietokantayhteys
Huom:
Käyttää CREATE TABLE IF NOT EXISTS - turvallinen olemassa oleville tietokannoille.
"""
conn.execute(
"""
CREATE TABLE IF NOT EXISTS game_objects (
id INTEGER PRIMARY KEY AUTOINCREMENT,
type TEXT NOT NULL,
name TEXT,
x INTEGER NOT NULL,
y INTEGER NOT NULL,
material_stored INTEGER,
material_capacity INTEGER,
inventory INTEGER,
robobasic_code TEXT,
UNIQUE(x,y)
)
"""
)
# Metataulukko pienille avain-arvo -pareille (kello, asetukset)
conn.execute(
"""
CREATE TABLE IF NOT EXISTS game_settings (
key TEXT PRIMARY KEY,
value TEXT
)
"""
)
# Tapahtumataulukko pelin tapahtumille aikaleimoineen
conn.execute(
"""
CREATE TABLE IF NOT EXISTS game_events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
event_type TEXT NOT NULL,
message TEXT NOT NULL,
timestamp TEXT DEFAULT (datetime('now'))
)
"""
)
# Varmista että vanhoissa tietokannoissa on timestamp-sarake
columns = {row[1] for row in conn.execute("PRAGMA table_info('game_events')")}
if "timestamp" not in columns:
# Lisää sarake ilman oletusarvoa (ALTER TABLE SQLitessä sallii vain literaaliset oletukset)
conn.execute("ALTER TABLE game_events ADD COLUMN timestamp TEXT")
# Täytä olemassa olevat rivit nykyisellä aikaleimoilla
conn.execute(
"UPDATE game_events SET timestamp = COALESCE(timestamp, datetime('now'))"
)
# Indeksi nopeampiin aikaleima-hakuihin
# conn.execute(
# """
# CREATE INDEX IF NOT EXISTS idx_events_timestamp
# ON game_events(timestamp DESC)
# """
# )
conn.commit()
def persist_object(conn: sqlite3.Connection, obj, commit: bool = True):
"""Tallenna tai päivitä peliobjekti tietokantaan (UPSERT-operaatio).
Käyttää ON CONFLICT(x,y) DO UPDATE käsittelemään sijainnin yksikäsitteisyysrajoite.
Varautuu DELETE+INSERT vanhoille tietokannoille ilman UNIQUE-rajoitetta.
Args:
conn: Tietokantayhteys
obj: Peliobjekti (Robot, Mine, Storage, Base, Rock)
Huom:
Tekee automaattisen commitin ellei commit=False (massatallenuksille).
Sijainti (x,y) on luonnollinen avain - vain yksi objekti per solu.
Esimerkki:
>>> robot = Robot(id=1, name='Bot1', pos=(5,7), inventory=3)
>>> persist_object(conn, robot)
"""
obj_type = type(obj).__name__.lower()
obj_id = getattr(obj, "id", None)
vals = {
"type": obj_type,
"name": getattr(obj, "name", None),
"x": getattr(obj, "pos")[0] if hasattr(obj, "pos") else None,
"y": getattr(obj, "pos")[1] if hasattr(obj, "pos") else None,
"material_stored": getattr(obj, "material_stored", None),
"material_capacity": getattr(obj, "material_capacity", None),
"robobasic_code": None,
}
# Serialisoi robotin ohjelmakoodi tallennusta varten
if obj_type == "robot":
# Robot-luokka käyttää program_text-attribuuttia
program = getattr(obj, "program_text", None)
if isinstance(program, list):
vals["robobasic_code"] = "\n".join(program)
elif isinstance(program, str):
vals["robobasic_code"] = program
# Käytä UPSERT koordinaattien mukaan jotta koordinaatit ovat auktoritatiiviset.
# Jos objektilla on ID, käytä sitä; muuten anna tietokannan generoida
try:
if obj_id is not None:
# Lisää eksplisiittisellä ID:llä
cur = conn.execute(
"""
INSERT INTO game_objects (id, type, name, x, y, material_stored, material_capacity, robobasic_code)
VALUES (:id, :type, :name, :x, :y, :material_stored, :material_capacity, :robobasic_code)
ON CONFLICT(x,y) DO UPDATE SET
id=excluded.id,
type=excluded.type,
name=excluded.name,
material_stored=excluded.material_stored,
material_capacity=excluded.material_capacity,
robobasic_code=excluded.robobasic_code
""",
{**vals, "id": obj_id},
)
else:
# Anna tietokannan generoida ID automaattisesti
cur = conn.execute(
"""
INSERT INTO game_objects (type, name, x, y, material_stored, material_capacity, robobasic_code)
VALUES (:type, :name, :x, :y, :material_stored, :material_capacity, :robobasic_code)
ON CONFLICT(x,y) DO UPDATE SET
type=excluded.type,
name=excluded.name,
material_stored=excluded.material_stored,
material_capacity=excluded.material_capacity,
robobasic_code=excluded.robobasic_code
""",
vals,
)
if commit:
conn.commit()
# Hae kanoninen ID tälle sijainnille ja aseta objektiin
if vals["x"] is not None and vals["y"] is not None:
cur2 = conn.execute(
"SELECT id FROM game_objects WHERE x = ? AND y = ?",
(vals["x"], vals["y"]),
)
row = cur2.fetchone()
if row:
try:
setattr(obj, "id", row["id"])
except (AttributeError, TypeError):
# Objekti ei tue attribuuttien asettamista (jäädytetty dataclass jne.)
pass
except sqlite3.OperationalError as e:
# Varautuminen vanhoille tietokannoille ilman UNIQUE(x,y): suorita delete+insert
msg = str(e)
if (
"ON CONFLICT" in msg
or "does not match any PRIMARY KEY or UNIQUE constraint" in msg
):
if vals["x"] is not None and vals["y"] is not None:
conn.execute(
"DELETE FROM game_objects WHERE x = ? AND y = ?",
(vals["x"], vals["y"]),
)
if obj_id is not None:
cur = conn.execute(
"INSERT INTO game_objects (id, type, name, x, y, material_capacity, material_stored, robobasic_code) VALUES (:id, :type, :name, :x, :y, :material_capacity, :material_stored, :robobasic_code)",
{**vals, "id": obj_id},
)
else:
cur = conn.execute(
"INSERT INTO game_objects (type, name, x, y, material_capacity, material_stored, robobasic_code) VALUES (:type, :name, :x, :y, :material_capacity, :material_stored, :robobasic_code)",
vals,
)
if commit:
conn.commit()
new_id = cur.lastrowid if obj_id is None else obj_id
try:
setattr(obj, "id", new_id)
except (AttributeError, TypeError):
# Object doesn't support attribute assignment
pass
else:
# Unexpected OperationalError, wrap and re-raise
raise DatabaseError(
f"Database operation failed: {e}",
details={"error": str(e), "object": vals},
) from e
def delete_object_db(conn: sqlite3.Connection, pos: Position):
"""Poista peliobjekti määritetystä sijainnista.
Args:
conn: Tietokantayhteys
pos: (x, y) koordinaatit poistettavalle objektille
Huom:
Tekee automaattisen commitin.
Onnistuu hiljaisesti vaikka objektia ei olisikaan sijainnissa.
"""
x, y = pos
conn.execute("DELETE FROM game_objects WHERE x = ? AND y = ?", (x, y))
conn.commit()
def delete_object_by_id(conn: sqlite3.Connection, oid: int):
"""Poista peliobjekti ID:n perusteella.
Args:
conn: Tietokantayhteys
oid: Poistettavan objektin ID
Huom:
Tekee automaattisen commitin.
Onnistuu hiljaisesti vaikka objekti-ID:tä ei olisikaan.
"""
conn.execute("DELETE FROM game_objects WHERE id = ?", (oid,))
conn.commit()
def load_objects_from_db(conn: sqlite3.Connection):
"""Lataa kaikki peliobjektit tietokannasta.
Args:
conn: Tietokantayhteys
Returns:
Lista sqlite3.Row-objekteja kaikilla objektien kentillä
Huom:
Palauttaa raa'at tietokantarivit - käytä create_object() luodaksesi malliobjektit.
Map-luokka käsittelee muunnoksen riveistä malliinstansseiksi.
Esimerkki:
>>> rows = load_objects_from_db(conn)
>>> for row in rows:
... obj = create_object(row['type'], id=row['id'], pos=(row['x'], row['y']))
"""
cur = conn.execute("SELECT * FROM game_objects")
return cur.fetchall()
def log_event(conn: sqlite3.Connection, event_type: str, message: str):
"""Kirjaa pelitapahtuma tietokantaan.
Args:
conn: Tietokantayhteys
event_type: Tapahtuman tyyppi (esim. 'robot_move', 'storage_full', 'mine_empty')
message: Ihmisluettava tapahtumakuvaus
obj: Valinnainen peliobjekti liittyen tapahtumaan
pos: Valinnainen sijaintitupla (x, y)"""
try:
conn.execute(
"""
INSERT INTO game_events (event_type, message, timestamp)
VALUES (?, ?, datetime('now'))
""",
(event_type, message),
)
except sqlite3.OperationalError:
# Varautuminen vanhoille tietokannoille ilman timestamp-saraketta
conn.execute(
"""
INSERT INTO game_events (event_type, message)
VALUES (?, ?)
""",
(event_type, message),
)
conn.commit()
def get_recent_events(conn: sqlite3.Connection, limit: int = 20):
"""Hae viimeisimmät pelitapahtumat, vanhimmat ensin (uusimmat alhaalla).
Args:
conn: Tietokantayhteys
limit: Palautettavien tapahtumien maksimimäärä
Returns:
Lista tapahtumariveistä (vanhimmat ensin, uusimmat viimeisenä)
"""
cursor = conn.execute(
"""
SELECT id, timestamp, event_type, message
FROM game_events
ORDER BY id DESC
LIMIT ?
""",
(limit,),
)
# Käännä lista niin että vanhimmat ovat ensin, uusimmat viimeisenä (näytön alareunassa)
return list(reversed(cursor.fetchall()))
def get_latest_event_id(conn: sqlite3.Connection) -> Optional[int]:
"""Palauta uusimman tapahtuman ID tai None jos ei tapahtumia."""
cur = conn.execute("SELECT id FROM game_events ORDER BY id DESC LIMIT 1")
row = cur.fetchone()
return int(row["id"]) if row else None
# ============================================================================
# Kartan asetustoiminnot
# ============================================================================
def get_map_settings(conn: sqlite3.Connection) -> dict:
"""Hae kartan leveys ja korkeus game_settings-taulusta.
Args:
conn: Tietokantayhteys
Returns:
Sanakirja 'width' ja 'height' avaimilla (None jos ei löydy)
"""
try:
cur = conn.execute(
"SELECT key, value FROM game_settings WHERE key IN ('map_width', 'map_height')"
)
rows = {row[0]: row[1] for row in cur.fetchall()}
width = None
height = None
if "map_width" in rows:
try:
width = int(rows["map_width"])
except (TypeError, ValueError):
pass
if "map_height" in rows:
try:
height = int(rows["map_height"])
except (TypeError, ValueError):
pass
return {"width": width, "height": height}
except Exception:
return {"width": None, "height": None}
def save_map_settings(
conn: sqlite3.Connection, width: int, height: int, commit: bool = True
) -> None:
"""Tallenna kartan mitat game_settings-tauluun.
Args:
conn: Tietokantayhteys
width: Kartan leveys
height: Kartan korkeus
commit: Tehdäänkö commit välittömästi (aseta False massatransaktioille)
"""
conn.execute(
"INSERT INTO game_settings(key, value) VALUES('map_width', ?) "
"ON CONFLICT(key) DO UPDATE SET value=excluded.value",
(str(width),),
)
conn.execute(
"INSERT INTO game_settings(key, value) VALUES('map_height', ?) "
"ON CONFLICT(key) DO UPDATE SET value=excluded.value",
(str(height),),
)
if commit:
conn.commit()
def get_all_settings(conn: sqlite3.Connection):
"""Palauta kaikki asetusrivit (avain, arvo) -pareina."""
try:
cur = conn.execute("SELECT key, value FROM game_settings ORDER BY key")
return cur.fetchall()
except Exception:
return []
def get_setting(conn: sqlite3.Connection, key: str) -> Optional[str]:
"""Hae yksittäinen asetusarvo.
Args:
conn: Tietokantayhteys
key: Asetusavain
Returns:
Asetusarvo tai None jos ei löydy
"""
try:
cur = conn.execute("SELECT value FROM game_settings WHERE key = ?", (key,))
row = cur.fetchone()
return row[0] if row else None
except Exception:
return None
def set_setting(conn: sqlite3.Connection, key: str, value: str) -> None:
"""Aseta yksittäinen asetusarvo.
Args:
conn: Tietokantayhteys
key: Asetusavain
value: Asetusarvo
"""
conn.execute(
"INSERT INTO game_settings(key, value) VALUES(?, ?) "
"ON CONFLICT(key) DO UPDATE SET value=excluded.value",
(key, value),
)
conn.commit()
def clear_all_objects(conn: sqlite3.Connection, commit: bool = True) -> None:
"""Delete all objects from game_objects table.
Args:
conn: Database connection
commit: Whether to commit immediately (set False for batch transactions)
"""
conn.execute("DELETE FROM game_objects")
if commit:
conn.commit()
def clear_all_settings(conn: sqlite3.Connection) -> None:
"""Delete all settings from game_settings table.
Args:
conn: Database connection
"""
conn.execute("DELETE FROM game_settings")
conn.commit()
def clear_map_settings(conn: sqlite3.Connection) -> None:
"""Poista vain kartalle spesifit asetukset (leveys/korkeus)."""
conn.execute("DELETE FROM game_settings WHERE key IN ('map_width', 'map_height')")
conn.commit()
def get_object_count(conn: sqlite3.Connection) -> int:
"""Get total number of objects in database.
Args:
conn: Database connection
Returns:
Count of objects
"""
try:
cur = conn.execute("SELECT COUNT(*) FROM game_objects")
return cur.fetchone()[0]
except Exception:
return 0