import sqlite3 import os from pathlib import Path from flask import current_app, g import click def get_db(): """Stellt eine Datenbankverbindung für den aktuellen Request bereit""" if 'db' not in g: db_path = current_app.config['DATABASE_PATH'] # Stelle sicher, dass das instance Verzeichnis existiert Path(db_path).parent.mkdir(parents=True, exist_ok=True) g.db = sqlite3.connect(db_path) g.db.row_factory = sqlite3.Row return g.db def close_db(e=None): """Schließt die Datenbankverbindung am Ende des Requests""" db = g.pop('db', None) if db is not None: db.close() def ensure_schema(): """Ergänzt bestehende Datenbanken um das Gruppen-Account-Zuordnungsmodell. Neue Installationen erhalten das Schema über ``migrations/schema.sql``. Für bestehende Datenbanken wird die frühere 1:1-Verknüpfung ``groups.account_id`` in die neue Tabelle ``group_accounts`` übernommen und die alte Spalte durch einen Tabellen-Neubau entfernt. """ db = get_db() groups_table = db.execute( "SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'groups'" ).fetchone() if not groups_table: return db.executescript(''' CREATE TABLE IF NOT EXISTS group_accounts ( tenant_id INTEGER NOT NULL, group_id INTEGER NOT NULL, account_id INTEGER NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (tenant_id, group_id, account_id), UNIQUE (tenant_id, account_id), FOREIGN KEY (tenant_id) REFERENCES tenants(id), FOREIGN KEY (group_id) REFERENCES groups(id), FOREIGN KEY (account_id) REFERENCES accounts(id) ); CREATE INDEX IF NOT EXISTS idx_group_accounts_group ON group_accounts(tenant_id, group_id); CREATE INDEX IF NOT EXISTS idx_groups_tenant ON groups(tenant_id); ''') db.commit() columns = { row['name'] for row in db.execute('PRAGMA table_info(groups)').fetchall() } if 'account_id' not in columns: return db.execute( '''INSERT OR IGNORE INTO group_accounts (tenant_id, group_id, account_id) SELECT g.tenant_id, g.id, g.account_id FROM groups g JOIN accounts a ON a.id = g.account_id AND a.tenant_id = g.tenant_id WHERE g.account_id IS NOT NULL AND a.role = 'Gruppe' ''' ) db.commit() # SQLite kann eine UNIQUE-Spalte nicht per ALTER TABLE DROP COLUMN # entfernen. Deshalb wird die Tabelle ohne die alte Spalte neu aufgebaut. # Die bereits kopierten Zuordnungen bleiben dabei erhalten. fk_enabled = db.execute('PRAGMA foreign_keys').fetchone()[0] db.execute('PRAGMA foreign_keys = OFF') try: db.execute('DROP TABLE IF EXISTS groups_new') db.execute('BEGIN IMMEDIATE') db.execute(''' CREATE TABLE groups_new ( id INTEGER PRIMARY KEY AUTOINCREMENT, tenant_id INTEGER NOT NULL, aliasname TEXT, state TEXT NOT NULL DEFAULT 'offen' CHECK(state IN ('offen', 'unterwegs', 'online', 'pausierend', 'fertig')), last_lat REAL, last_lon REAL, last_pos_at TIMESTAMP, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (tenant_id) REFERENCES tenants(id) ) ''') db.execute(''' INSERT INTO groups_new (id, tenant_id, aliasname, state, last_lat, last_lon, last_pos_at, created_at, updated_at) SELECT id, tenant_id, aliasname, state, last_lat, last_lon, last_pos_at, created_at, updated_at FROM groups ''') db.execute('DROP TABLE groups') db.execute('ALTER TABLE groups_new RENAME TO groups') db.execute('CREATE INDEX IF NOT EXISTS idx_groups_tenant ON groups(tenant_id)') db.commit() except sqlite3.DatabaseError as exc: db.rollback() try: db.execute('DROP TABLE IF EXISTS groups_new') db.commit() except sqlite3.DatabaseError: pass current_app.logger.warning( 'groups.account_id konnte nicht entfernt werden: %s', exc ) finally: db.execute('PRAGMA foreign_keys = ON' if fk_enabled else 'PRAGMA foreign_keys = OFF') def init_db(): """Initialisiert die Datenbank mit dem Schema""" db = get_db() schema_path = Path(current_app.root_path).parent / 'migrations' / 'schema.sql' with open(schema_path, 'r', encoding='utf-8') as f: db.executescript(f.read()) db.commit() ensure_schema() @click.command('init-db') def init_db_command(): """CLI-Befehl zum Initialisieren der Datenbank""" init_db() click.echo('Datenbank wurde initialisiert.')