Files
syops/backend/init_local_db.py
T

113 lines
4.2 KiB
Python

"""
backend/init_local_db.py
用途:通过 Alembic 初始化当前版本的本地 SQLite,并写入最小管理账号和演示 Agent。
依赖:Flask-Migrate、应用工厂、User/Agent 模型。
逻辑:空库按当前模型建表并 stamp 到迁移 head,已有版本库执行 upgrade;随后写种子数据。未受 Alembic 管理的旧库明确阻断。
"""
from __future__ import annotations
import os
import sqlite3
import sys
from pathlib import Path
BACKEND_DIR = Path(__file__).resolve().parent
sys.path.append(str(BACKEND_DIR))
def _database_path() -> Path:
"""返回本地 SQLite 路径;验收或多工作区可通过环境变量使用隔离数据库。"""
configured = str(os.getenv('HXOPS_LOCAL_DATABASE_PATH') or '').strip()
return Path(configured).expanduser().resolve() if configured else BACKEND_DIR / 'local_test.db'
def _legacy_unversioned_database(path: Path) -> bool:
"""识别已有业务表但缺少 Alembic 版本表的旧库,避免不安全地在未知基线上升级。"""
if not path.is_file() or path.stat().st_size == 0:
return False
with sqlite3.connect(path) as connection:
tables = {
str(row[0])
for row in connection.execute("SELECT name FROM sqlite_master WHERE type='table'")
if str(row[0]) and not str(row[0]).startswith('sqlite_')
}
return bool(tables) and 'alembic_version' not in tables
def _is_blank_database(path: Path) -> bool:
"""判断目标是否为可安全按当前模型初始化的全新空白 SQLite。"""
if not path.is_file() or path.stat().st_size == 0:
return True
with sqlite3.connect(path) as connection:
count = connection.execute(
"SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'",
).fetchone()[0]
return int(count or 0) == 0
def main() -> int:
"""迁移并初始化本地数据库;只对空库或已有 Alembic 版本库执行原地升级。"""
db_path = _database_path()
db_path.parent.mkdir(parents=True, exist_ok=True)
blank_database = _is_blank_database(db_path)
if _legacy_unversioned_database(db_path):
print(
f"Refusing to modify legacy unversioned database: {db_path}\n"
"Set HXOPS_LOCAL_DATABASE_PATH to a new file for a clean local environment, "
"or migrate the legacy database manually after backing it up.",
file=sys.stderr,
)
return 2
os.environ['DATABASE_URL'] = f"sqlite:///{db_path.as_posix()}"
os.environ.setdefault('FIXED_ASSETS_SYNC_ENABLED', 'false')
print(f"Setting DATABASE_URL to: {os.environ['DATABASE_URL']}")
from flask_migrate import stamp, upgrade
from app import create_app, db
from app.models import Agent, User
app = create_app('development')
with app.app_context():
migration_directory = str(BACKEND_DIR / 'migrations')
if blank_database:
print(f"Creating current local schema at {db_path}...")
db.create_all()
stamp(directory=migration_directory, revision='head')
print("Current schema created and stamped at migration head.")
else:
print(f"Applying database migrations at {db_path}...")
upgrade(directory=migration_directory)
print("Database migrations completed.")
user = User.query.filter_by(username='admin').first()
if user is None:
print("Seeding initial user 'admin'...")
user = User(username='admin', email='admin@example.com', role='admin')
db.session.add(user)
else:
print("Updating local admin password...")
user.set_password('Hxit@54321')
if Agent.query.first() is None:
print("Seeding initial agent 'Demo Agent'...")
db.session.add(Agent(
name='Demo Agent',
description='A test agent for local verification',
type='api',
dify_api_key='test-key',
is_active=True,
))
db.session.commit()
print("Database seeded successfully.")
return 0
if __name__ == '__main__':
raise SystemExit(main())