init_db.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. # -*- coding: utf-8 -*-
  2. # Author : Charley
  3. # Python : 3.12.10
  4. # Date : 2026/08/18
  5. """读取 schema.sql 幂等建表(集物星球爬虫库)。"""
  6. import os
  7. import sys
  8. from loguru import logger
  9. from mysql_pool import MySQLConnectionPool
  10. def init_db(log) -> None:
  11. """读取同目录 schema.sql,逐条执行建表语句。
  12. Args:
  13. log: 日志对象。
  14. Raises:
  15. FileNotFoundError: schema.sql 不存在时抛出。
  16. """
  17. sql_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "schema.sql")
  18. if not os.path.isfile(sql_path):
  19. raise FileNotFoundError(f"schema.sql 不存在: {sql_path}")
  20. with open(sql_path, "r", encoding="utf-8") as f:
  21. content = f.read()
  22. pool = MySQLConnectionPool(log=log)
  23. if not pool.check_pool_health():
  24. log.error("数据库连接池异常")
  25. return
  26. # 按分号切分逐条执行,跳过空行与注释行
  27. stmts = [s.strip() for s in content.split(";") if s.strip()]
  28. for stmt in stmts:
  29. lines = [ln for ln in stmt.splitlines() if not ln.strip().startswith("--")]
  30. clean = "\n".join(lines).strip()
  31. if not clean:
  32. continue
  33. try:
  34. pool._execute(clean, commit=True)
  35. head = clean.splitlines()[0][:60]
  36. log.success(f"执行成功: {head}")
  37. except Exception as e:
  38. log.warning(f"执行失败(可能已存在): {e}")
  39. if __name__ == "__main__":
  40. logger.remove()
  41. logger.add(sys.stderr, level="INFO", format="[{time:HH:mm:ss}] {level} {message}")
  42. init_db(logger)