76 lines
2.4 KiB
Python
76 lines
2.4 KiB
Python
from sqlalchemy import create_engine, event
|
|
from sqlalchemy.ext.declarative import declarative_base
|
|
from sqlalchemy.orm import sessionmaker
|
|
from config import get_settings
|
|
|
|
settings = get_settings()
|
|
|
|
engine = create_engine(
|
|
settings.DATABASE_URL,
|
|
connect_args={"check_same_thread": False},
|
|
)
|
|
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
|
|
|
Base = declarative_base()
|
|
|
|
|
|
def get_db():
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
def create_tables():
|
|
Base.metadata.create_all(bind=engine)
|
|
|
|
|
|
def run_migrations():
|
|
"""Apply lightweight schema migrations for SQLite."""
|
|
from sqlalchemy import inspect, text
|
|
insp = inspect(engine)
|
|
|
|
# AuditLog: add username column if missing
|
|
if "audit_log" in insp.get_table_names():
|
|
audit_cols = {c["name"] for c in insp.get_columns("audit_log")}
|
|
if "username" not in audit_cols:
|
|
with engine.connect() as conn:
|
|
conn.execute(text("ALTER TABLE audit_log ADD COLUMN username TEXT"))
|
|
conn.commit()
|
|
|
|
# Heartbeat: add missing columns
|
|
if "heartbeats" in insp.get_table_names():
|
|
hb_cols = {c["name"] for c in insp.get_columns("heartbeats")}
|
|
new_hb_cols = [
|
|
("sessions", "TEXT"),
|
|
("ram_used_gb", "REAL"),
|
|
("ram_available_gb", "REAL"),
|
|
("swap_total_gb", "REAL"),
|
|
("swap_used_gb", "REAL"),
|
|
("swap_free_gb", "REAL"),
|
|
("swap_percent", "REAL"),
|
|
]
|
|
with engine.connect() as conn:
|
|
for col, col_type in new_hb_cols:
|
|
if col not in hb_cols:
|
|
conn.execute(text(f"ALTER TABLE heartbeats ADD COLUMN {col} {col_type}"))
|
|
conn.commit()
|
|
|
|
# Computer: add missing columns
|
|
if "computers" in insp.get_table_names():
|
|
pc_cols = {c["name"] for c in insp.get_columns("computers")}
|
|
new_pc_cols = [
|
|
("current_ram_used_gb", "REAL"),
|
|
("current_ram_available_gb", "REAL"),
|
|
("current_swap_total_gb", "REAL"),
|
|
("current_swap_used_gb", "REAL"),
|
|
("current_swap_free_gb", "REAL"),
|
|
("current_swap_percent", "REAL"),
|
|
]
|
|
with engine.connect() as conn:
|
|
for col, col_type in new_pc_cols:
|
|
if col not in pc_cols:
|
|
conn.execute(text(f"ALTER TABLE computers ADD COLUMN {col} {col_type}"))
|
|
conn.commit()
|