# -*- coding: utf-8 -*- # models/database.py from __future__ import annotations import os import sqlite3 import sys from pathlib import Path import resources.code_res.sql_queries as sql from models.db_locator import DbLocator from models.db_pouch_repo import DbPouchRepo from models.db_stats_repo import DbStatsRepo from resources.code_res.game_constants import INTERNAL_DB_REL_PATH, USER_DB_FILENAME def _resolve_bundle_root() -> Path: """Pfad zu den gebündelten Read-Only-Ressourcen (PyInstaller _MEIPASS oder Projekt-Root).""" if getattr(sys, "frozen", False) and hasattr(sys, "_MEIPASS"): return Path(sys._MEIPASS) return Path(__file__).resolve().parent.parent def _resolve_user_data_dir() -> Path: """Fallback-Speicherort neben der ausführbaren Datei (niemals /tmp!) bzw. im Benutzerverzeichnis.""" if getattr(sys, "frozen", False): raw_exe = os.environ.get("ARGV0") or (sys.argv[0] if sys.argv else sys.executable) exe_dir = Path(raw_exe).expanduser().resolve().parent exe_str = str(exe_dir).replace("\\", "/") if ( ".app/Contents/MacOS" not in exe_str and not exe_str.startswith("/tmp") and "/_MEI" not in exe_str and os.access(exe_dir, os.W_OK) ): return exe_dir return DbLocator._default_installed_data_dir() return Path(__file__).resolve().parent.parent BUNDLE_ROOT = _resolve_bundle_root() USER_DATA_DIR = _resolve_user_data_dir() INTERNAL_DB_PATH = BUNDLE_ROOT / INTERNAL_DB_REL_PATH USER_DB_PATH = DbLocator.resolve_initial_db_path(USER_DATA_DIR) class Database: """ Zentrale SQLite-Fassade für Verbindung, DB-Speicherort/Umzug, Einstellungen, Profile und Savegames; delegiert Goldbeutel und Statistiken an Sub-Repositories. """ _connection: sqlite3.Connection | None = None _active_user_db_path: Path = USER_DB_PATH @classmethod def get_user_db_path(cls) -> Path: return cls._active_user_db_path @classmethod def get_user_db_dir(cls) -> Path: return cls._active_user_db_path.parent @classmethod def _set_active_path_vars(cls, new_path: Path) -> None: global USER_DB_PATH, USER_DATA_DIR resolved = new_path.expanduser().resolve() cls._active_user_db_path = resolved USER_DB_PATH = resolved USER_DATA_DIR = resolved.parent @classmethod def conn(cls) -> sqlite3.Connection: if cls._connection is None: if not INTERNAL_DB_PATH.is_file(): raise FileNotFoundError( f"Interne Stammdaten-DB fehlt: {INTERNAL_DB_PATH}. " "Bitte zuerst das Seed-SQL mit deinem Query-Executor ausführen!" ) cls._active_user_db_path.parent.mkdir(parents=True, exist_ok=True) c = sqlite3.connect(str(cls._active_user_db_path)) c.row_factory = sqlite3.Row c.execute(sql.PRAGMA_FOREIGN_KEYS) internal_uri = f"{INTERNAL_DB_PATH.resolve().as_uri()}?mode=ro" try: c.execute(sql.ATTACH_INTERNAL_DB, (internal_uri,)) except sqlite3.OperationalError: c.execute(sql.ATTACH_INTERNAL_DB, (str(INTERNAL_DB_PATH),)) cls._connection = c return cls._connection @classmethod def close(cls): if cls._connection is not None: try: cls._connection.close() except Exception: pass cls._connection = None @classmethod def execute(cls, query: str, params: tuple = ()) -> sqlite3.Cursor: cur = cls.conn().execute(query, params) cls.conn().commit() return cur @classmethod def execute_many(cls, query: str, seq_of_params) -> sqlite3.Cursor: cur = cls.conn().executemany(query, seq_of_params) cls.conn().commit() return cur @classmethod def fetch_one(cls, query: str, params: tuple = ()) -> dict | None: row = cls.conn().execute(query, params).fetchone() return dict(row) if row else None @classmethod def fetch_all(cls, query: str, params: tuple = ()) -> list[dict]: return [dict(r) for r in cls.conn().execute(query, params).fetchall()] @classmethod def fetch_val(cls, query: str, params: tuple = (), default=None): row = cls.conn().execute(query, params).fetchone() return row[0] if row is not None else default @classmethod def _persist_self_location_in_db(cls, previous_path: Path | None = None) -> None: cur_p = cls._active_user_db_path.resolve() cls.save_setting("user_db_path", str(cur_p)) cls.save_setting("user_db_dir", str(cur_p.parent)) if previous_path is not None: cls.save_setting("user_db_previous_path", str(previous_path.resolve())) DbLocator.remember_db_path(cur_p) @classmethod def init_db(cls): cls.conn().executescript(sql.USER_SCHEMA_DDL) bj_cols = [r["name"] for r in cls.fetch_all(sql.PRAGMA_TABLE_INFO_BJ_ACCOUNTS)] if "devils_deal_active" not in bj_cols: cls.conn().execute(sql.MIGRATE_ADD_DEVILS_ACTIVE) prof_cols = [r["name"] for r in cls.fetch_all(sql.PRAGMA_TABLE_INFO_PROFILES)] if "avatar_ref" not in prof_cols: cls.conn().execute(sql.MIGRATE_ADD_PROFILE_AVATAR) cls.conn().commit() cls._persist_self_location_in_db() # --- DB-Speicherort, Live-Wechsel & Atomarer Umzug --- @staticmethod def validate_sqlite_file(candidate_file: Path) -> bool: if not candidate_file.is_file(): return False try: # Kein ?mode=ro erzwingen, da SQLite bei offenen -wal Dateien sonst unter Linux # mangels Schreibrecht fuer -shm mit OperationalError abbricht! with sqlite3.connect(str(candidate_file.resolve())) as test_c: res = test_c.execute("PRAGMA integrity_check;").fetchone() if not res or str(res[0]).lower() != "ok": return False tables = { r[0] for r in test_c.execute( "SELECT name FROM sqlite_master WHERE type='table';" ).fetchall() } return (not tables) or ("profiles" in tables and "settings" in tables) except Exception: return False @classmethod def relocate_for_first_user(cls, target_dir_or_file: Path) -> Path: target = target_dir_or_file.expanduser().resolve() if target.is_dir() or target.suffix.lower() != ".db": target = target / USER_DB_FILENAME old_path = cls._active_user_db_path.resolve() if target == old_path: cls._persist_self_location_in_db() return target target.parent.mkdir(parents=True, exist_ok=True) old_was_empty = (len(cls.get_profiles()) == 0) cls.close() cls._set_active_path_vars(target) cls.init_db() if old_was_empty and old_path.is_file() and old_path != target: for suffix in ("", "-wal", "-shm"): try: Path(f"{old_path}{suffix}").unlink(missing_ok=True) except Exception: pass return target @classmethod def switch_user_database(cls, existing_db_file: Path) -> tuple[bool, str]: cand = existing_db_file.expanduser().resolve() if not cls.validate_sqlite_file(cand): return False, "invalid_file" prev_path = cls._active_user_db_path.resolve() # Immer Verbindung sauber schließen & frisch öffnen (auch wenn cand == prev_path), # damit extern hineinkopierte Dateien garantiert neu eingelesen werden! cls.close() try: cls._set_active_path_vars(cand) cls.init_db() cls._persist_self_location_in_db( previous_path=prev_path if cand != prev_path else None ) return True, str(cand) except Exception as exc: cls.close() cls._set_active_path_vars(prev_path) cls.init_db() return False, str(exc) @classmethod def move_user_database(cls, destination_dir: Path) -> tuple[bool, str]: dst_dir = destination_dir.expanduser().resolve() dst_dir.mkdir(parents=True, exist_ok=True) dst_file = (dst_dir / cls._active_user_db_path.name).resolve() old_file = cls._active_user_db_path.resolve() if dst_file == old_file: cls._persist_self_location_in_db() return True, str(dst_file) tmp_file = dst_dir / f".{dst_file.name}.moving_tmp" try: tmp_file.unlink(missing_ok=True) src_conn = cls.conn() src_conn.commit() with sqlite3.connect(str(tmp_file)) as backup_conn: src_conn.backup(backup_conn, name="main") if not cls.validate_sqlite_file(tmp_file): tmp_file.unlink(missing_ok=True) return False, "Backup verification failed" cls.close() if dst_file.is_file(): dst_file.unlink() tmp_file.replace(dst_file) cls._set_active_path_vars(dst_file) cls.init_db() cls._persist_self_location_in_db(previous_path=old_file) for suffix in ("", "-wal", "-shm"): try: Path(f"{old_file}{suffix}").unlink(missing_ok=True) except Exception: pass return True, str(dst_file) except Exception as exc: try: tmp_file.unlink(missing_ok=True) except Exception: pass if cls._connection is None: cls._set_active_path_vars(old_file) cls.init_db() return False, str(exc) # --- Stammdaten, Settings, Profile & Savegames --- @classmethod def load_all_translations(cls) -> dict[str, dict[str, str]]: out: dict[str, dict[str, str]] = {"DE": {}, "EN": {}} for r in cls.fetch_all(sql.SELECT_ALL_I18N): out.setdefault(r["lang"], {})[r["key"]] = r["val"] return out @classmethod def load_prestige_ranks(cls) -> list[dict]: return cls.fetch_all(sql.SELECT_PRESTIGE_RANKS) @classmethod def load_setting(cls, key: str, default: str = "") -> str: return cls.fetch_val(sql.SELECT_SETTING, (key,), default=default) @classmethod def save_setting(cls, key: str, value: str): cls.execute(sql.UPSERT_SETTING, (key, str(value))) @classmethod def get_profiles(cls) -> list[str]: return [r["name"] for r in cls.fetch_all(sql.SELECT_ALL_PROFILES)] @classmethod def get_or_create_profile(cls, name: str) -> dict: cls.execute(sql.INSERT_PROFILE_IGNORE, (name,)) return cls.fetch_one(sql.SELECT_PROFILE_BY_NAME, (name,)) @classmethod def get_profile_by_id(cls, profile_id: int) -> dict | None: return cls.fetch_one(sql.SELECT_PROFILE_BY_ID, (profile_id,)) @classmethod def save_game_state(cls, profile_id: int, game_folder: str, variant_key: str, state_json: str): cls.execute(sql.UPSERT_SAVEGAME, (profile_id, game_folder, variant_key, state_json)) @classmethod def load_game_state(cls, profile_id: int, game_folder: str) -> dict | None: return cls.fetch_one(sql.SELECT_SAVEGAME, (profile_id, game_folder)) @classmethod def delete_game_state(cls, profile_id: int, game_folder: str): cls.execute(sql.DELETE_SAVEGAME, (profile_id, game_folder)) # --- Delegatoren an DbStatsRepo --- @classmethod def get_game_progress(cls, profile_id: int, game_folder: str) -> dict: return DbStatsRepo.get_game_progress(cls, profile_id, game_folder) @classmethod def get_recorded_game_level_avg_xp(cls, profile_id: int, game_folder: str, level_num: int) -> int: return DbStatsRepo.get_recorded_game_level_avg_xp(cls, profile_id, game_folder, level_num) @classmethod def add_game_points(cls, profile_id: int, game_folder: str, points: int): DbStatsRepo.add_game_points(cls, profile_id, game_folder, points) @classmethod def adjust_game_points(cls, profile_id: int, game_folder: str, delta_points: int, min_floor_xp: int = 0) -> dict: return DbStatsRepo.adjust_game_points(cls, profile_id, game_folder, delta_points, min_floor_xp) @classmethod def load_bot_configs(cls, profile_id: int, game_folder: str) -> dict[int, tuple[str, int]]: return DbStatsRepo.load_bot_configs(cls, profile_id, game_folder) @classmethod def save_bot_configs(cls, profile_id: int, game_folder: str, configs: dict[int, tuple[str, int]]): DbStatsRepo.save_bot_configs(cls, profile_id, game_folder, configs) @classmethod def record_game_result( cls, profile_id: int, variant_key: str, won: bool, duration_sec: float, points_gained: int = 0, bj_account_id: int | None = None, pk_account_id: int | None = None, ) -> tuple[int, int]: return DbStatsRepo.record_game_result( cls, profile_id, variant_key, won, duration_sec, points_gained, bj_account_id, pk_account_id ) @classmethod def get_variants_for_filter(cls, folder_path: str | None = None) -> list[dict]: return DbStatsRepo.get_variants_for_filter(cls, folder_path) @classmethod def get_stats_overview(cls, profile_id: int, variant_id: int | None = None, folder_path: str | None = None) -> dict: return DbStatsRepo.query_stats(cls, "profile", profile_id, variant_id=variant_id, folder_path=folder_path) @classmethod def get_bj_account_stats_overview(cls, bj_account_id: int, variant_id: int | None = None) -> dict: return DbStatsRepo.query_stats(cls, "bj_account", bj_account_id, variant_id=variant_id, folder_path="blackjack") @classmethod def get_pk_account_stats_overview(cls, pk_account_id: int, variant_id: int | None = None) -> dict: return DbStatsRepo.query_stats(cls, "pk_account", pk_account_id, variant_id=variant_id, folder_path="poker") format_seconds = staticmethod(DbStatsRepo.format_seconds) # --- Delegatoren an DbPouchRepo --- @classmethod def get_sacrificeable_profiles(cls, active_profile_id: int, game_folder: str) -> list[dict]: return DbPouchRepo.get_sacrificeable_profiles(cls, active_profile_id, game_folder) @classmethod def execute_devils_deal(cls, active_profile_id: int, game_folder: str, sacrifice_profile_id: int, account_id: int) -> tuple[bool, str]: return DbPouchRepo.execute_devils_deal(cls, active_profile_id, game_folder, sacrifice_profile_id, account_id) @classmethod def get_active_devils_bj_account(cls, profile_id: int) -> dict | None: return DbPouchRepo.get_active_devils_bj_account(cls, profile_id) @classmethod def set_bj_devils_deal_active(cls, bj_account_id: int, active: bool): DbPouchRepo.set_bj_devils_deal_active(cls, bj_account_id, active) @classmethod def get_active_devils_pk_account(cls, profile_id: int) -> dict | None: return DbPouchRepo.get_active_devils_pk_account(cls, profile_id) @classmethod def set_pk_devils_deal_active(cls, pk_account_id: int, active: bool): DbPouchRepo.set_pk_devils_deal_active(cls, pk_account_id, active) @classmethod def get_blackjack_accounts(cls, profile_id: int) -> list[dict]: return DbPouchRepo.get_blackjack_accounts(cls, profile_id) @classmethod def get_blackjack_account(cls, bj_account_id: int) -> dict | None: return DbPouchRepo.get_blackjack_account(cls, bj_account_id) @classmethod def create_blackjack_account(cls, profile_id: int, account_name: str) -> dict: return DbPouchRepo.create_blackjack_account(cls, profile_id, account_name) @classmethod def update_blackjack_gold(cls, bj_account_id: int, gold_delta: int, last_bet: int | None = None) -> dict: return DbPouchRepo.update_blackjack_gold(cls, bj_account_id, gold_delta, last_bet) @classmethod def save_blackjack_last_bet(cls, bj_account_id: int, bet: int): DbPouchRepo.save_blackjack_last_bet(cls, bj_account_id, bet) @classmethod def delete_blackjack_account(cls, bj_account_id: int): DbPouchRepo.delete_blackjack_account(cls, bj_account_id) @classmethod def exchange_xp_for_bj_gold(cls, profile_id: int, bj_account_id: int) -> tuple[bool, str]: return DbPouchRepo.exchange_game_xp_for_gold(cls, profile_id, "blackjack", bj_account_id) @classmethod def get_poker_accounts(cls, profile_id: int) -> list[dict]: return DbPouchRepo.get_poker_accounts(cls, profile_id) @classmethod def get_poker_account(cls, pk_account_id: int) -> dict | None: return DbPouchRepo.get_poker_account(cls, pk_account_id) @classmethod def create_poker_account(cls, profile_id: int, account_name: str) -> dict: return DbPouchRepo.create_poker_account(cls, profile_id, account_name) @classmethod def update_poker_gold(cls, pk_account_id: int, gold_delta: int) -> dict: return DbPouchRepo.update_poker_gold(cls, pk_account_id, gold_delta) @classmethod def delete_poker_account(cls, pk_account_id: int): DbPouchRepo.delete_poker_account(cls, pk_account_id) @classmethod def exchange_xp_for_pk_gold(cls, profile_id: int, pk_account_id: int) -> tuple[bool, str]: return DbPouchRepo.exchange_game_xp_for_gold(cls, profile_id, "poker", pk_account_id) @classmethod def rename_profile(cls, profile_id: int, new_name: str) -> tuple[bool, str]: clean = (new_name or "").strip() if not clean: return False, "profile_err_empty_name" if len(clean) > 24: return False, "profile_err_name_too_long" existing = cls.fetch_one(sql.SELECT_PROFILE_BY_NAME_NOCASE, (clean,)) if existing is not None and int(existing["id"]) != int(profile_id): return False, "profile_err_name_taken" old_row = cls.get_profile_by_id(profile_id) cls.execute(sql.UPDATE_PROFILE_NAME, (clean, int(profile_id))) if old_row and cls.load_setting("last_profile_name", "") == old_row["name"]: cls.save_setting("last_profile_name", clean) return True, clean @classmethod def update_profile_avatar(cls, profile_id: int, avatar_ref: str) -> None: cls.execute(sql.UPDATE_PROFILE_AVATAR, (str(avatar_ref), int(profile_id))) @classmethod def get_profile_overall_progress(cls, profile_id: int) -> dict: return DbStatsRepo.get_profile_overall_progress(cls, profile_id)