updated view and database

This commit is contained in:
ske087
2026-06-24 15:21:40 +03:00
parent cb12a8f1cf
commit a48b3afb83
14 changed files with 372 additions and 205 deletions
+30
View File
@@ -42,11 +42,41 @@ class DatabaseConfig:
"""Create all database tables"""
try:
Base.metadata.create_all(self.engine)
self.ensure_schema()
logging.info("Database tables created successfully")
return True
except Exception as e:
logging.error(f"Error creating database tables: {e}")
return False
def ensure_schema(self):
"""Idempotently add columns that were introduced after the table was first
created. SQLAlchemy's create_all() never ALTERs existing tables, so new
columns on an existing SQLite database must be added manually.
"""
from sqlalchemy import text
# Columns added over time: (table, column, SQL type definition)
required_columns = [
('devices', 'wmt_last_seen', 'DATETIME'),
('devices', 'config_synced_at', 'DATETIME'),
('devices', 'custom_chrome_url', 'VARCHAR(500)'),
]
try:
with self.engine.connect() as conn:
for table, column, col_type in required_columns:
exists = conn.execute(
text("SELECT name FROM sqlite_master WHERE type='table' AND name=:t"),
{'t': table},
).fetchone()
if not exists:
continue
cols = [row[1] for row in conn.execute(text(f"PRAGMA table_info({table})")).fetchall()]
if column not in cols:
conn.execute(text(f"ALTER TABLE {table} ADD COLUMN {column} {col_type}"))
conn.commit()
logging.info(f"Schema: added column {table}.{column}")
except Exception as e:
logging.error(f"Error ensuring schema columns: {e}")
def drop_tables(self):
"""Drop all database tables (use with caution!)"""