db.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import pymysql
  2. from .config import settings
  3. def get_connection():
  4. return pymysql.connect(
  5. host=settings.db_host,
  6. port=settings.db_port,
  7. user=settings.db_user,
  8. password=settings.db_password,
  9. database=settings.db_name,
  10. charset="utf8mb4",
  11. cursorclass=pymysql.cursors.DictCursor,
  12. connect_timeout=settings.db_connect_timeout,
  13. read_timeout=30,
  14. write_timeout=30,
  15. autocommit=True,
  16. )
  17. _ANNOTATION_TABLE_DDL = """
  18. CREATE TABLE IF NOT EXISTS wave_annotation (
  19. id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '标注ID',
  20. wave_file_id BIGINT UNSIGNED NOT NULL COMMENT '所属波形文件ID(wave_file.id)',
  21. label VARCHAR(8) NOT NULL COMMENT '样本类型:正常 / 异常',
  22. period_start INT NOT NULL COMMENT '起始周期编号',
  23. period_end INT NOT NULL COMMENT '结束周期编号(含)',
  24. sample_index_start INT NOT NULL COMMENT '起始采样点索引',
  25. sample_index_end INT NOT NULL COMMENT '结束采样点索引(含)',
  26. created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  27. updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  28. PRIMARY KEY (id),
  29. KEY idx_wave_file (wave_file_id)
  30. ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COMMENT = '波形标注索引表';
  31. """
  32. def ensure_annotation_table() -> None:
  33. with get_connection() as connection:
  34. with connection.cursor() as cursor:
  35. cursor.execute(_ANNOTATION_TABLE_DDL)