feat: add schema drift handling and rebuild
This commit is contained in:
@@ -4,6 +4,7 @@ from __future__ import annotations
|
||||
import os
|
||||
import sqlite3
|
||||
import threading
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
@@ -42,6 +43,21 @@ def get_connection(db_path: str | None = None) -> sqlite3.Connection:
|
||||
_current_path = db_path
|
||||
return _conn
|
||||
|
||||
def _has_schema_version(conn: sqlite3.Connection) -> bool:
|
||||
try:
|
||||
conn.execute("SELECT 1 FROM schema_version").fetchone()
|
||||
return True
|
||||
except sqlite3.OperationalError:
|
||||
return False
|
||||
|
||||
def _has_settings_value_column(conn: sqlite3.Connection) -> bool:
|
||||
try:
|
||||
info = conn.execute("PRAGMA table_info(settings)").fetchall()
|
||||
columns = {row[1]: row[2] for row in info}
|
||||
return 'value' in columns
|
||||
except sqlite3.OperationalError:
|
||||
return False
|
||||
|
||||
|
||||
def init_db(db_path: str | None = None) -> sqlite3.Connection:
|
||||
conn = get_connection(db_path)
|
||||
@@ -53,6 +69,15 @@ def init_db(db_path: str | None = None) -> sqlite3.Connection:
|
||||
with _lock:
|
||||
conn.executescript(schema)
|
||||
conn.commit()
|
||||
if not _has_schema_version(conn):
|
||||
if not _has_settings_value_column(conn):
|
||||
logger = logging.getLogger("slab.db")
|
||||
logger.info("Detected pre-M3 DB, rebuilding schema")
|
||||
conn.executescript("DROP TABLE IF EXISTS settings")
|
||||
conn.executescript(schema)
|
||||
conn.commit()
|
||||
conn.execute("INSERT OR REPLACE INTO schema_version (version) VALUES (1)")
|
||||
|
||||
return conn
|
||||
|
||||
|
||||
|
||||
@@ -111,6 +111,8 @@ CREATE TABLE IF NOT EXISTS settings (
|
||||
value_enc TEXT
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS schema_version (version INTEGER PRIMARY KEY);
|
||||
|
||||
-- 7. prompts + prompt_revisions (append-only revisions)
|
||||
CREATE TABLE IF NOT EXISTS prompts (
|
||||
id INTEGER PRIMARY KEY,
|
||||
|
||||
Reference in New Issue
Block a user