"""Strict, versioned migrations for the bot-owned SQLite database only. Never opens New API, changes journal mode, or changes billing/ATTACH semantics. """ from __future__ import annotations import logging import sqlite3 import time SCHEMA_VERSION = 2 TABLE_DDL = ('CREATE TABLE IF NOT EXISTS users(\n' ' tg_id INTEGER PRIMARY KEY, username TEXT, token_name TEXT, api_key TEXT,\n' ' created INTEGER, notified INTEGER DEFAULT 1,\n' ' points INTEGER DEFAULT 0, referred_by INTEGER, ref_time INTEGER, ref_awarded INTEGER ' 'DEFAULT 0,\n' ' lang TEXT, menu_style TEXT)', 'CREATE TABLE IF NOT EXISTS group_log(chat_id INTEGER, uid INTEGER, username TEXT, text TEXT, ts ' 'INTEGER)', 'CREATE TABLE IF NOT EXISTS sticker_cache(file_id TEXT PRIMARY KEY, emoji TEXT, set_name TEXT, ' 'added INTEGER)', 'CREATE TABLE IF NOT EXISTS video_tasks(tid TEXT PRIMARY KEY, uid INTEGER, chat_id INTEGER, ' 'message_id INTEGER, prompt TEXT, key TEXT, ts INTEGER)') USER_COLUMNS = (('points', 'INTEGER DEFAULT 0'), ('referred_by', 'INTEGER'), ('ref_time', 'INTEGER'), ('ref_awarded', 'INTEGER DEFAULT 0'), ('lang', 'TEXT'), ('menu_style', 'TEXT'), ('chat_mode', 'INTEGER DEFAULT 0'), ('waiting_prompt', 'INTEGER DEFAULT 0'), ('chat_count', 'INTEGER DEFAULT 0'), ('img_count', 'INTEGER DEFAULT 0'), ('quota_date', 'TEXT'), ('chat_model', 'TEXT'), ('img_model', 'TEXT'), ('vip', 'INTEGER DEFAULT 0'), ('last_checkin', 'TEXT'), ('last_loyalty', 'INTEGER'), ('admin', 'INTEGER DEFAULT 0'), ('captcha_ok', 'INTEGER DEFAULT 0'), ('banned', 'INTEGER DEFAULT 0'), ('week_model', 'TEXT'), ('week_key', 'TEXT'), ('last_active', 'INTEGER'), ('warned_at', 'INTEGER'), ('ref_credit', 'INTEGER DEFAULT 0'), ('key_locked', 'INTEGER DEFAULT 0'), ('rep', 'INTEGER DEFAULT 0'), ('quiz_last', 'INTEGER DEFAULT 0'), ('dice_last', 'INTEGER DEFAULT 0'), ('last_bonus_lvl', 'INTEGER DEFAULT 0'), ('rep_last', 'INTEGER'), ('badge_lock', 'INTEGER DEFAULT 0'), ('last_bonus_ts', 'INTEGER'), ('rank_cache', 'INTEGER DEFAULT 0'), ('ref_notify', 'INTEGER DEFAULT 1'), ('vid_model', 'TEXT'), ('mus_model', 'TEXT'), ('sub_penalized', 'INTEGER DEFAULT 0'), ('rep_give_day', 'TEXT'), ('rep_give_n', 'INTEGER DEFAULT 0'), ('api_blocked', 'INTEGER DEFAULT 0'), ('api_block_reason', 'TEXT'), ('gate_member_ok', 'INTEGER'), ('gate_member_ts', 'INTEGER DEFAULT 0'), ('gate_warned_at', 'INTEGER DEFAULT 0'), ('agent_model', 'TEXT'), ('effort', "TEXT DEFAULT ''"), ('prompt_on', 'INTEGER DEFAULT 0'), ('badge_until', 'INTEGER DEFAULT 0')) GROUP_LOG_INDEXES = { "idx_group_log_uid_ts": ("uid", "ts"), "idx_group_log_chat_ts_uid": ("chat_id", "ts", "uid"), "idx_group_log_ts": ("ts",), } class BotSchemaError(RuntimeError): """Startup cannot safely continue with an incompatible bot schema.""" def _columns(con, table): return {row[1]: row for row in con.execute(f'PRAGMA table_info("{table}")')} def _initial_schema(con): for ddl in TABLE_DDL: con.execute(ddl) columns = _columns(con, "users") for name, ddl in USER_COLUMNS: if name not in columns: con.execute(f'ALTER TABLE users ADD COLUMN "{name}" {ddl}') def _activity_indexes(con): for name, columns in GROUP_LOG_INDEXES.items(): con.execute(f'CREATE INDEX IF NOT EXISTS "{name}" ON group_log ({", ".join(columns)})') def _validate(con): expected = { "users": {"tg_id", "username", "token_name", "api_key", "created", "notified"} | {name for name, _ in USER_COLUMNS}, "group_log": {"chat_id", "uid", "username", "text", "ts"}, "sticker_cache": {"file_id", "emoji", "set_name", "added"}, "video_tasks": {"tid", "uid", "chat_id", "message_id", "prompt", "key", "ts"}, } for table, required in expected.items(): columns = _columns(con, table) if required - columns.keys(): raise BotSchemaError(f"incomplete bot table: {table}") if table == "users" and (columns["tg_id"][2].upper() != "INTEGER" or columns["tg_id"][5] != 1): raise BotSchemaError("users.tg_id must remain an INTEGER PRIMARY KEY") indexes = {row[1] for row in con.execute('PRAGMA index_list("group_log")')} for name, expected_columns in GROUP_LOG_INDEXES.items(): if name not in indexes: raise BotSchemaError(f"missing bot activity index: {name}") actual = tuple(row[2] for row in con.execute(f'PRAGMA index_info("{name}")')) if actual != expected_columns: raise BotSchemaError(f"incompatible bot activity index: {name}") def migrate_bot_schema(con): """Apply all pending bot migrations atomically, or fail startup explicitly. The caller owns the connection, not an active transaction. A legacy v0 DB is adopted by introspecting columns; duplicate columns are not exception flow. Future schema versions are refused rather than silently downgraded. """ if con.in_transaction: raise BotSchemaError("bot migration requires a connection outside a transaction") step = 0 try: con.execute("BEGIN IMMEDIATE") # Inspect under the same write lock as DDL: another starter may have # migrated the file while this connection was waiting for admission. current = con.execute("PRAGMA user_version").fetchone()[0] if not 0 <= current <= SCHEMA_VERSION: raise BotSchemaError(f"unsupported bot schema version: {current}") for version, migrate in ((1, _initial_schema), (2, _activity_indexes)): if current < version: step = version migrate(con) con.execute(f"PRAGMA user_version={version}") _validate(con) con.commit() except BaseException as exc: if con.in_transaction: con.rollback() if isinstance(exc, sqlite3.Error): raise BotSchemaError(f"bot schema migration v{step} failed ({type(exc).__name__})") from exc raise return SCHEMA_VERSION def initialize_bot_db(path): """Initialize only the bot-owned DB; keep its existing journal and timeout.""" con = sqlite3.connect(path, timeout=30) try: migrate_bot_schema(con) # Cleanup remains best-effort, unlike a required schema migration. try: with con: con.execute("DELETE FROM group_log WHERE ts < ?", (int(time.time()) - 30 * 86400,)) except sqlite3.Error as exc: logging.getLogger(__name__).warning( "bot log retention skipped (%s)", type(exc).__name__) finally: con.close()