migrate_contents.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #!/usr/bin/env python3
  2. """
  3. 数据库迁移脚本:为contents表添加新字段
  4. """
  5. import sqlite3
  6. from pathlib import Path
  7. DB_PATH = Path(__file__).parent / "knowhub.db"
  8. def migrate():
  9. print(f"数据库路径: {DB_PATH}")
  10. if not DB_PATH.exists():
  11. print("数据库不存在,无需迁移")
  12. return
  13. conn = sqlite3.connect(str(DB_PATH))
  14. cursor = conn.cursor()
  15. # 检查是否已有新字段
  16. cursor.execute("PRAGMA table_info(contents)")
  17. columns = {row[1] for row in cursor.fetchall()}
  18. print(f"现有字段: {columns}")
  19. migrations = []
  20. if "secure_body" not in columns:
  21. migrations.append("ALTER TABLE contents ADD COLUMN secure_body TEXT DEFAULT ''")
  22. if "content_type" not in columns:
  23. migrations.append("ALTER TABLE contents ADD COLUMN content_type TEXT DEFAULT 'text'")
  24. if "metadata" not in columns:
  25. migrations.append("ALTER TABLE contents ADD COLUMN metadata TEXT DEFAULT '{}'")
  26. if "updated_at" not in columns:
  27. migrations.append("ALTER TABLE contents ADD COLUMN updated_at TEXT DEFAULT ''")
  28. if not migrations:
  29. print("✅ 数据库已是最新版本,无需迁移")
  30. conn.close()
  31. return
  32. print(f"执行 {len(migrations)} 个迁移...")
  33. for sql in migrations:
  34. print(f" {sql}")
  35. cursor.execute(sql)
  36. conn.commit()
  37. conn.close()
  38. print("✅ 迁移完成")
  39. if __name__ == "__main__":
  40. migrate()