-- ============================================================
-- addon/mqttbroker/upgrade_time_fields.sql
-- 时间字段统一约定：create_at / update_at / delete_at
-- 适用：已安装过 mqttbroker 插件的旧库（install.sql 的 IF NOT EXISTS 不会改已存在的表）
-- 用法：在数据库客户端执行本文件即可（幂等，重复执行仅 CHANGE 同名列，无副作用）
-- ============================================================

ALTER TABLE `__PREFIX__mqttbroker_connection`
  CHANGE `connect_time` `create_at` INT DEFAULT NULL COMMENT '连接时间',
  CHANGE `update_time`  `update_at` INT DEFAULT NULL COMMENT '更新时间';

ALTER TABLE `__PREFIX__mqttbroker_message`
  CHANGE `create_time` `create_at` INT DEFAULT NULL COMMENT '时间',
  DROP INDEX `idx_create_time`,
  ADD INDEX `idx_create_at` (`create_at`);

ALTER TABLE `__PREFIX__mqttbroker_topic`
  CHANGE `create_time` `create_at` INT DEFAULT NULL COMMENT '订阅时间';

ALTER TABLE `__PREFIX__mqttbroker_auth`
  CHANGE `create_time` `create_at` INT DEFAULT NULL,
  CHANGE `update_time` `update_at` INT DEFAULT NULL;

ALTER TABLE `__PREFIX__mqttbroker_acl`
  CHANGE `create_time` `create_at` INT DEFAULT NULL;

ALTER TABLE `__PREFIX__mqttbroker_retain`
  CHANGE `update_time` `update_at` INT DEFAULT NULL;

ALTER TABLE `__PREFIX__mqttbroker_offline`
  CHANGE `create_time` `create_at` INT DEFAULT NULL;

ALTER TABLE `__PREFIX__mqttbroker_rule`
  CHANGE `create_time` `create_at` INT DEFAULT NULL;

ALTER TABLE `__PREFIX__mqttbroker_outbox`
  CHANGE `create_time` `create_at` INT DEFAULT NULL;

-- 会员直通用：补 member_id 列（兼容已装旧库；重复执行不会报错）
SET @db = DATABASE();
SET @has = (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = @db AND TABLE_NAME = '__PREFIX__mqttbroker_auth' AND COLUMN_NAME = 'member_id');
SET @sql = IF(@has = 0, 'ALTER TABLE `__PREFIX__mqttbroker_auth` ADD `member_id` int unsigned NOT NULL DEFAULT 0 COMMENT ''归属框架会员ID（会员直通回填）''', 'SELECT 1');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
