Files
OpenVPN-Monitoring-Simple/APP_CORE/db.py
T

45 lines
1.5 KiB
Python
Raw Normal View History

2026-01-09 01:05:50 +03:00
import sqlite3
import configparser
import os
import logging
import migrations
2026-01-09 01:05:50 +03:00
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)
2026-02-06 09:02:59 +03:00
# 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')
2026-01-09 01:05:50 +03:00
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)"""
2026-01-09 01:05:50 +03:00
# 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)