-- Partitioned logs table draft
-- 目标：按月分区日志表，提升写入吞吐和查询历史的性能
-- 说明：本草案为初步设计，待评审后落地实现
-- Assumptions:
-- - MariaDB 10.x 版本，支持分区按 RANGE (TO_DAYS(log_time))
-- - 日志字段与现有采集日志表接近
-- - 每月一个分区，覆盖历史数据的归档策略待定
DROP TABLE IF EXISTS logs_partitioned;
CREATE TABLE logs_partitioned (
  id BIGINT AUTO_INCREMENT PRIMARY KEY,
  machine_id INT NOT NULL,
  program_name VARCHAR(128) NOT NULL,
  log_time DATETIME NOT NULL,
  log_level VARCHAR(16) DEFAULT 'INFO',
  raw_payload JSON,
  analysis_summary TEXT,
  analysis_version VARCHAR(64) DEFAULT 'v1',
  -- 便于按机床与时间筛选的组合索引
  KEY idx_machine_time (machine_id, log_time),
  KEY idx_program_time (program_name, log_time)
)
PARTITION BY RANGE (TO_DAYS(log_time)) (
  PARTITION p202401 VALUES LESS THAN (TO_DAYS('2024-02-01')),
  PARTITION p202402 VALUES LESS THAN (TO_DAYS('2024-03-01')),
  PARTITION p202403 VALUES LESS THAN (TO_DAYS('2024-04-01')),
  PARTITION p202404 VALUES LESS THAN (TO_DAYS('2024-05-01')),
  PARTITION p202405 VALUES LESS THAN (TO_DAYS('2024-06-01')),
  PARTITION p202406 VALUES LESS THAN (TO_DAYS('2024-07-01')),
  PARTITION p202407 VALUES LESS THAN (TO_DAYS('2024-08-01')),
  PARTITION p202408 VALUES LESS THAN (TO_DAYS('2024-09-01')),
  PARTITION p202409 VALUES LESS THAN (TO_DAYS('2024-10-01')),
  PARTITION p202410 VALUES LESS THAN (TO_DAYS('2024-11-01')),
  PARTITION p202411 VALUES LESS THAN (TO_DAYS('2024-12-01')),
  PARTITION p202412 VALUES LESS THAN (TO_DAYS('2025-01-01')),
  PARTITION p202501 VALUES LESS THAN (TO_DAYS('2025-02-01'))
);

-- 备注：
- 未来月份的分区建议通过定期执行脚本自动追加分区
- 可以通过 ALTER TABLE logs_partitioned REORGANIZE PARTITION ...? 进行滚动归档
