Files
mokeeText/backend/init_db.py
2026-07-15 16:08:17 +08:00

60 lines
1.9 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""数据库初始化 — 建表 + 插入默认数据"""
import sys
sys.stdout.reconfigure(encoding='utf-8')
from models import engine, Base, SessionLocal, Folder
def migrate():
"""数据库迁移 — 处理表结构变更"""
from sqlalchemy import text
with engine.connect() as conn:
# V2.2: uploads 表新增 file_id 列data 改为可空
try:
conn.execute(text("ALTER TABLE uploads ADD COLUMN file_id VARCHAR(64) NULL AFTER content_type"))
except Exception:
pass # 列已存在则跳过
try:
conn.execute(text("ALTER TABLE uploads MODIFY COLUMN data LONGBLOB NULL"))
except Exception:
pass
conn.commit()
print("[OK] 数据库迁移完成")
def init_database():
"""创建所有表,并插入默认文件夹"""
# 建表
Base.metadata.create_all(bind=engine)
print("[OK] 数据库表创建完成")
# 执行迁移
migrate()
# 插入默认数据
db = SessionLocal()
try:
# 笔记默认文件夹
if db.query(Folder).filter_by(type="note").count() == 0:
for name in ["工作", "个人", "学习"]:
db.add(Folder(name=name, type="note"))
db.add(Folder(name="未分类", type="note"))
print("[OK] 笔记文件夹已创建: 工作、个人、学习、未分类")
# 网站默认文件夹
if db.query(Folder).filter_by(type="website").count() == 0:
for name in ["代码托管", "云服务", "开发工具"]:
db.add(Folder(name=name, type="website"))
db.add(Folder(name="未分类", type="website"))
print("[OK] 网站文件夹已创建: 代码托管、云服务、开发工具、未分类")
db.commit()
print("[OK] 默认数据插入完成")
finally:
db.close()
if __name__ == "__main__":
init_database()