- Profiler and monitoring: schema_migrations table, additive ordered
migrations, single write lock, integrity check, consistent backup via
the SQLite backup API (newest 5 kept), row-count verification before
commit, refusal to start on a database newer than the code.
- Profiler baseline migration is generated from the models and adds every
missing column (replaces ensure_columns and the manual add_*.py scripts).
- migrate.py in each component (--check exit 0/2/1, --db); services migrate
at start, OVPMON_AUTO_MIGRATE=0 only checks.
- Tests: test_migrations.py per component; verified on databases created by
the code of commit 3836049 and on the live stand.
- Docs: Database_Migrations reference, change summary, deployment
scenarios plan, README, Index.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
46 lines
1.5 KiB
Python
46 lines
1.5 KiB
Python
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)
|