From fd90b6cd467f5cf8bd41affbf94275e86392b0c6 Mon Sep 17 00:00:00 2001 From: Reditus <33814724+ReditusDraco@users.noreply.github.com> Date: Thu, 21 May 2026 16:48:00 +0100 Subject: [PATCH] feat(dashboard): Refactor database schema to dashboard namespace --- app/config.py | 1 + app/factory.py | 7 ++----- app/services/admin.py | 32 ++++++++++++++++---------------- app/services/chat.py | 17 ++++++----------- app/services/database.py | 26 +++++++++++--------------- app/services/player.py | 2 +- settings.yaml.example | 2 +- 7 files changed, 38 insertions(+), 49 deletions(-) diff --git a/app/config.py b/app/config.py index 19f1ab1..4c3a675 100644 --- a/app/config.py +++ b/app/config.py @@ -38,6 +38,7 @@ DEFAULTS = { 'min_connections': 2, 'max_connections': 10, 'owner': 'dune', + 'dashboard_schema': 'dashboard', }, 'kubernetes': { 'namespace': '', diff --git a/app/factory.py b/app/factory.py index 61749c5..b52e6b1 100644 --- a/app/factory.py +++ b/app/factory.py @@ -192,7 +192,7 @@ def create_app(settings_path=None): db_config, min_conn=settings['database']['min_connections'], max_conn=settings['database']['max_connections'], - db_owner=settings['database'].get('owner', 'dune') + dashboard_schema=settings['database'].get('dashboard_schema', 'dashboard') ) logging.debug(f"DatabaseService initialized: host={db_config['host']}, port={db_config['port']}, user={db_config['user']}") db_service.ensure_tables() @@ -225,10 +225,7 @@ def create_app(settings_path=None): player_svc = PlayerService(db_service) vehicle_svc = VehicleService(db_service) - chat_svc = ChatService( - db_service, k8s_service, ssh_service, static_cache, - db_owner=settings['database'].get('owner', 'dune') - ) + chat_svc = ChatService(db_service, k8s_service, ssh_service, static_cache) logging.debug("ChatService initialized") admin_svc = AdminService(db_service, ssh_service) logging.debug("AdminService initialized") diff --git a/app/services/admin.py b/app/services/admin.py index 0a2948c..769213e 100644 --- a/app/services/admin.py +++ b/app/services/admin.py @@ -50,7 +50,7 @@ class AdminService: if account_id: if duration_int == 0: cur.execute(""" - INSERT INTO dune.bans (player_id, account_id, reason, note, duration, banned_at, expires_at, active) + INSERT INTO dashboard.bans (player_id, account_id, reason, note, duration, banned_at, expires_at, active) VALUES (%s, %s, %s, %s, %s, NOW(), NULL, TRUE) ON CONFLICT (player_id) DO UPDATE SET account_id = EXCLUDED.account_id, reason = EXCLUDED.reason, @@ -59,7 +59,7 @@ class AdminService: """, [player_id, account_id, reason, note, duration_int]) else: cur.execute(""" - INSERT INTO dune.bans (player_id, account_id, reason, note, duration, banned_at, expires_at, active) + INSERT INTO dashboard.bans (player_id, account_id, reason, note, duration, banned_at, expires_at, active) VALUES (%s, %s, %s, %s, %s, NOW(), NOW() + INTERVAL '1 minute' * %s, TRUE) ON CONFLICT (player_id) DO UPDATE SET account_id = EXCLUDED.account_id, reason = EXCLUDED.reason, @@ -69,7 +69,7 @@ class AdminService: else: if duration_int == 0: cur.execute(""" - INSERT INTO dune.bans (player_id, reason, note, duration, banned_at, expires_at, active) + INSERT INTO dashboard.bans (player_id, reason, note, duration, banned_at, expires_at, active) VALUES (%s, %s, %s, %s, NOW(), NULL, TRUE) ON CONFLICT (player_id) DO UPDATE SET reason = EXCLUDED.reason, note = EXCLUDED.note, @@ -78,7 +78,7 @@ class AdminService: """, [player_id, reason, note, duration_int]) else: cur.execute(""" - INSERT INTO dune.bans (player_id, reason, note, duration, banned_at, expires_at, active) + INSERT INTO dashboard.bans (player_id, reason, note, duration, banned_at, expires_at, active) VALUES (%s, %s, %s, %s, NOW(), NOW() + INTERVAL '1 minute' * %s, TRUE) ON CONFLICT (player_id) DO UPDATE SET reason = EXCLUDED.reason, note = EXCLUDED.note, @@ -106,7 +106,7 @@ class AdminService: cur = None try: cur = conn.cursor() - cur.execute("DELETE FROM dune.bans WHERE player_id = %s", [player_id]) + cur.execute("DELETE FROM dashboard.bans WHERE player_id = %s", [player_id]) conn.commit() cur.execute("SELECT ps.account_id FROM dune.player_state ps WHERE ps.player_controller_id = %s", [player_id]) @@ -116,16 +116,16 @@ class AdminService: ips_to_unblock = [] if account_id: all_ips = self.db.query(""" - SELECT ip_address FROM dune.player_ips + SELECT ip_address FROM dashboard.player_ips WHERE player_id IN (SELECT player_controller_id FROM dune.player_state WHERE account_id = %s) """, [account_id]) or [] ips_to_unblock = [r.get('ip_address') for r in all_ips if r.get('ip_address')] else: - ip_row = self.db.query("SELECT ip_address FROM dune.player_ips WHERE player_id = %s", [player_id], one=True) + ip_row = self.db.query("SELECT ip_address FROM dashboard.player_ips WHERE player_id = %s", [player_id], one=True) if ip_row and ip_row.get('ip_address'): ips_to_unblock.append(ip_row.get('ip_address')) - cur.execute("INSERT INTO dune.player_actions (player_id, action_type, reason, duration_minutes) VALUES (%s, 'unban', 'Manual unban', 0)", [player_id]) + cur.execute("INSERT INTO dashboard.player_actions (player_id, action_type, reason, duration_minutes) VALUES (%s, 'unban', 'Manual unban', 0)", [player_id]) conn.commit() with self._iptables_lock: @@ -159,7 +159,7 @@ class AdminService: return False, "Player not found" player_name = player.get('character_name', 'Unknown') - ip_row = self.db.query("SELECT ip_address FROM dune.player_ips WHERE player_id = %s", [player_id], one=True) + ip_row = self.db.query("SELECT ip_address FROM dashboard.player_ips WHERE player_id = %s", [player_id], one=True) player_ip = ip_row.get('ip_address') if ip_row else None if not player_ip: @@ -180,7 +180,7 @@ class AdminService: thread = threading.Thread(target=temporary_block, args=(player_ip,), daemon=True) thread.start() - self.db.execute("INSERT INTO dune.player_actions (player_id, action_type, reason, duration_minutes, ip_address) VALUES (%s, 'kick', 'Temporary kick', 1, %s)", [player_id, player_ip]) + self.db.execute("INSERT INTO dashboard.player_actions (player_id, action_type, reason, duration_minutes, ip_address) VALUES (%s, 'kick', 'Temporary kick', 1, %s)", [player_id, player_ip]) audit_logger.info(f"KICK: player_id={player_id} player_name={player_name} ip={player_ip}") return True, f"Player {player_name} kicked (IP {player_ip} blocked for 60 seconds)" @@ -310,14 +310,14 @@ class AdminService: pid = row[0] if isinstance(row, (tuple, list)) else row.get('funcom_id') account_id = row[1] if isinstance(row, (tuple, list)) else row.get('account_id') cur.execute(""" - INSERT INTO dune.player_ips (player_id, ip_address, updated_at) + INSERT INTO dashboard.player_ips (player_id, ip_address, updated_at) VALUES (%s, %s, NOW()) ON CONFLICT (player_id) DO UPDATE SET ip_address = EXCLUDED.ip_address, updated_at = NOW() """, [pid, ip]) updated += 1 ban_check = self.db.query(""" - SELECT player_id FROM dune.bans + SELECT player_id FROM dashboard.bans WHERE (player_id = %s OR account_id = %s) AND (active = TRUE OR active IS NULL) LIMIT 1 """, [pid, account_id], one=True) @@ -344,7 +344,7 @@ class AdminService: def set_player_ip(self, player_id, ip_address): return self.db.execute(""" - INSERT INTO dune.player_ips (player_id, ip_address, updated_at) + INSERT INTO dashboard.player_ips (player_id, ip_address, updated_at) VALUES (%s, %s, NOW()) ON CONFLICT (player_id) DO UPDATE SET ip_address = EXCLUDED.ip_address, updated_at = NOW() """, [player_id, ip_address]) @@ -361,19 +361,19 @@ class AdminService: def get_bans(self, limit=50): return self.db.query(""" SELECT b.id, b.player_id, b.reason, b.active, b.banned_at, b.expires_at, ps.character_name - FROM dune.bans b + FROM dashboard.bans b LEFT JOIN dune.player_state ps ON b.player_id = ps.player_controller_id ORDER BY b.banned_at DESC LIMIT %s """, [limit]) or [] def get_player_ban(self, player_id): - return self.db.query("SELECT reason, note, duration, banned_at, expires_at FROM dune.bans WHERE player_id = %s", [player_id], one=True) + return self.db.query("SELECT reason, note, duration, banned_at, expires_at FROM dashboard.bans WHERE player_id = %s", [player_id], one=True) def get_player_history(self, player_id, limit=20): return self.db.query(""" SELECT action_type, reason, note, duration_minutes, created_at, ip_address - FROM dune.player_actions + FROM dashboard.player_actions WHERE player_id = %s ORDER BY created_at DESC LIMIT %s diff --git a/app/services/chat.py b/app/services/chat.py index bba0b53..a36f646 100644 --- a/app/services/chat.py +++ b/app/services/chat.py @@ -8,12 +8,11 @@ logger = logging.getLogger(__name__) class ChatService: - def __init__(self, db_service, k8s_service, ssh_service, cache, db_owner='dune'): + def __init__(self, db_service, k8s_service, ssh_service, cache): self.db = db_service self.k8s = k8s_service self.ssh = ssh_service self.cache = cache - self.db_owner = db_owner self.ensured_table = False def ensure_history_table(self): @@ -21,7 +20,7 @@ class ChatService: return True try: self.db.execute(""" - CREATE TABLE IF NOT EXISTS dune.chat_history ( + CREATE TABLE IF NOT EXISTS dashboard.chat_history ( id SERIAL PRIMARY KEY, timestamp TIMESTAMP DEFAULT NOW(), channel VARCHAR(50), @@ -34,11 +33,7 @@ class ChatService: is_admin BOOLEAN DEFAULT FALSE ) """) - self.db.execute("CREATE INDEX IF NOT EXISTS idx_chat_history_timestamp ON dune.chat_history (timestamp DESC)") - if self.db_owner: - from psycopg2 import sql - owner_ident = sql.Identifier(self.db_owner).as_string(None) - self.db.execute(f"ALTER TABLE IF EXISTS dune.chat_history OWNER TO {owner_ident}") + self.db.execute("CREATE INDEX IF NOT EXISTS idx_chat_history_timestamp ON dashboard.chat_history (timestamp DESC)") self.ensured_table = True logger.info("Chat history table ready") return True @@ -51,7 +46,7 @@ class ChatService: loc_y = location.get('Y', 0) if location else 0 loc_z = location.get('Z', 0) if location else 0 return self.db.execute(""" - INSERT INTO dune.chat_history (channel, sender, message, target, location_x, location_y, location_z, is_admin) + INSERT INTO dashboard.chat_history (channel, sender, message, target, location_x, location_y, location_z, is_admin) VALUES (%s, %s, %s, %s, %s, %s, %s, %s) """, [channel, sender, message, target, loc_x, loc_y, loc_z, is_admin]) @@ -66,7 +61,7 @@ class ChatService: cur = conn.cursor() for msg in messages: cur.execute(""" - INSERT INTO dune.chat_history (channel, sender, message, target, location_x, location_y, location_z, is_admin) + INSERT INTO dashboard.chat_history (channel, sender, message, target, location_x, location_y, location_z, is_admin) VALUES (%s, %s, %s, %s, %s, %s, %s, %s) """, [ msg['channel'], msg['sender'], msg['message'], @@ -92,7 +87,7 @@ class ChatService: return self.db.query(""" SELECT id, timestamp, channel, sender, message, target, location_x, location_y, location_z, is_admin - FROM dune.chat_history + FROM dashboard.chat_history ORDER BY timestamp DESC LIMIT %s """, [limit]) diff --git a/app/services/database.py b/app/services/database.py index f6c4ea4..0f0afe0 100644 --- a/app/services/database.py +++ b/app/services/database.py @@ -10,11 +10,11 @@ logger = logging.getLogger(__name__) class DatabaseService: - def __init__(self, db_config, min_conn=2, max_conn=10, db_owner='dune'): + def __init__(self, db_config, min_conn=2, max_conn=10, dashboard_schema='dashboard'): self.db_config = db_config self.min_conn = min_conn self.max_conn = max_conn - self.db_owner = db_owner + self.dashboard_schema = dashboard_schema self.pool = None def init_pool(self): @@ -142,17 +142,19 @@ class DatabaseService: if not conn: return cur = None + schema = self.dashboard_schema try: cur = conn.cursor() - cur.execute(""" - CREATE TABLE IF NOT EXISTS dune.player_ips ( + cur.execute(f"CREATE SCHEMA IF NOT EXISTS {schema}") + cur.execute(f""" + CREATE TABLE IF NOT EXISTS {schema}.player_ips ( player_id BIGINT PRIMARY KEY, ip_address INET NOT NULL, updated_at TIMESTAMP NOT NULL DEFAULT NOW() ) """) - cur.execute(""" - CREATE TABLE IF NOT EXISTS dune.bans ( + cur.execute(f""" + CREATE TABLE IF NOT EXISTS {schema}.bans ( id SERIAL PRIMARY KEY, player_id BIGINT UNIQUE, account_id BIGINT, @@ -164,8 +166,8 @@ class DatabaseService: active BOOLEAN DEFAULT TRUE ) """) - cur.execute(""" - CREATE TABLE IF NOT EXISTS dune.player_actions ( + cur.execute(f""" + CREATE TABLE IF NOT EXISTS {schema}.player_actions ( id SERIAL PRIMARY KEY, player_id BIGINT NOT NULL, action_type VARCHAR(50) NOT NULL, @@ -176,14 +178,8 @@ class DatabaseService: created_at TIMESTAMP NOT NULL DEFAULT NOW() ) """) - if self.db_owner: - from psycopg2 import sql - owner_ident = sql.Identifier(self.db_owner).as_string(conn) - cur.execute(f"ALTER TABLE IF EXISTS dune.player_ips OWNER TO {owner_ident}") - cur.execute(f"ALTER TABLE IF EXISTS dune.bans OWNER TO {owner_ident}") - cur.execute(f"ALTER TABLE IF EXISTS dune.player_actions OWNER TO {owner_ident}") conn.commit() - logger.info("Dashboard tables ensured (player_ips, bans, player_actions)") + logger.info(f"Dashboard tables ensured in schema '{schema}' (player_ips, bans, player_actions)") except Exception as e: logger.warning(f"Failed to ensure dashboard tables: {e}") if conn: diff --git a/app/services/player.py b/app/services/player.py index bce3adf..27fb474 100644 --- a/app/services/player.py +++ b/app/services/player.py @@ -141,7 +141,7 @@ class PlayerService: LEFT JOIN dune.factions f ON pf.faction_id = f.id LEFT JOIN dune.guild_members gm ON ps.player_controller_id = gm.player_id LEFT JOIN dune.guilds g ON gm.guild_id = g.guild_id - LEFT JOIN dune.player_ips pi ON ps.player_controller_id = pi.player_id + LEFT JOIN dashboard.player_ips pi ON ps.player_controller_id = pi.player_id WHERE {where_clause} ORDER BY player_name LIMIT %s OFFSET %s diff --git a/settings.yaml.example b/settings.yaml.example index 91c2b72..46dcb03 100644 --- a/settings.yaml.example +++ b/settings.yaml.example @@ -37,7 +37,7 @@ database: schema: "dune" min_connections: 2 max_connections: 10 - owner: "dune" # Game server DB user — tables are reassigned to this owner for backup compatibility + dashboard_schema: "dashboard" # Schema for dashboard's own tables (isolated from game DB for backup compatibility) # Kubernetes kubernetes: