fix: 数据库迁移支持 - 自动添加缺失字段
This commit is contained in:
+24
-1
@@ -15,9 +15,32 @@ class Database:
|
|||||||
self._init_db()
|
self._init_db()
|
||||||
|
|
||||||
def _init_db(self):
|
def _init_db(self):
|
||||||
"""初始化数据库"""
|
"""初始化数据库(支持迁移)"""
|
||||||
conn = sqlite3.connect(self.db_path)
|
conn = sqlite3.connect(self.db_path)
|
||||||
|
|
||||||
|
# 检查表是否存在
|
||||||
|
cursor = conn.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='images'")
|
||||||
|
table_exists = cursor.fetchone() is not None
|
||||||
|
|
||||||
|
if not table_exists:
|
||||||
|
# 新建数据库
|
||||||
conn.executescript(DB_SCHEMA)
|
conn.executescript(DB_SCHEMA)
|
||||||
|
else:
|
||||||
|
# 迁移:检查是否有 date_folder 字段
|
||||||
|
cursor = conn.execute("PRAGMA table_info(images)")
|
||||||
|
columns = [row[1] for row in cursor.fetchall()]
|
||||||
|
|
||||||
|
if 'date_folder' not in columns:
|
||||||
|
conn.execute("ALTER TABLE images ADD COLUMN date_folder TEXT")
|
||||||
|
|
||||||
|
if 'camera_id' not in columns:
|
||||||
|
conn.execute("ALTER TABLE images ADD COLUMN camera_id INTEGER DEFAULT 0")
|
||||||
|
|
||||||
|
# 检查 config 表
|
||||||
|
cursor = conn.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='config'")
|
||||||
|
if cursor.fetchone() is None:
|
||||||
|
conn.execute("CREATE TABLE IF NOT EXISTS config (key TEXT PRIMARY KEY, value TEXT)")
|
||||||
|
|
||||||
conn.commit()
|
conn.commit()
|
||||||
conn.close()
|
conn.close()
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user