import sqlite3 import configparser import os import logging import migrations class DatabaseManager: def __init__(self, config_file='config.ini'): self.config_file = config_file self.config = configparser.ConfigParser() self.logger = logging.getLogger(__name__) self.load_config() def load_config(self): if os.path.exists(self.config_file): self.config.read(self.config_file) # Priority: ENV > Config File > Fallback env_db_path = os.getenv('OVPMON_OPENVPN_MONITOR_DB_PATH') if env_db_path: self.db_path = env_db_path else: self.db_path = self.config.get('openvpn_monitor', 'db_path', fallback='openvpn_monitor.db') def get_connection(self): """Get a database connection""" return sqlite3.connect(self.db_path) def init_database(self): """Initialize the database schema (applies pending migrations)""" # Create directory if needed db_dir = os.path.dirname(self.db_path) if db_dir and not os.path.exists(db_dir): try: os.makedirs(db_dir) except OSError: pass self.logger.info(f"Using database: {self.db_path}") # Schema creation and upgrades live in migrations.py (versioned, with a backup before # any change). Exits with a clear message if the database is newer than this code or # migrations are pending while OVPMON_AUTO_MIGRATE=0. migrations.startup_or_exit(self.db_path)