package mysql import ( "fmt" "strings" "time" "gorm.io/gorm" "gorm.io/gorm/logger" "github.com/go-gormigrate/gormigrate/v2" "go-sms/internal/model/entity" errscodes "go-sms/internal/pkg/errors" "go-sms/internal/util" ) // Migrations 迁移清单(顺序执行,ID 单调递增;禁止修改已发布 ID)。 // casbinRule 适配 gorm-adapter 的 casbin_rule 表结构(建表用)。 type casbinRule struct { ID uint `gorm:"primaryKey;autoIncrement"` Ptype string `gorm:"size:100"` V0 string `gorm:"size:100;index:idx_casbin_rule,priority:1"` V1 string `gorm:"size:100;index:idx_casbin_rule,priority:2"` V2 string `gorm:"size:100"` V3 string `gorm:"size:100"` V4 string `gorm:"size:100"` V5 string `gorm:"size:100"` } func (casbinRule) TableName() string { return "casbin_rule" } // rbacSeeds 基础角色策略 + 内置超管绑定(与 scripts/init_rbac.sql 参考一致)。 func rbacSeeds() []casbinRule { p := func(role, obj, act string) casbinRule { return casbinRule{Ptype: "p", V0: role, V1: obj, V2: act} } g := func(accountID, role string) casbinRule { return casbinRule{Ptype: "g", V0: accountID, V1: role} } return []casbinRule{ // 角色策略 p("admin", "*", "*"), p("ops", "*", "read"), p("ops", "account", "write"), p("ops", "channel", "write"), p("ops", "message", "write"), p("ops", "audit", "write"), p("service", "account", "read"), p("service", "message", "read"), p("service", "stats", "read"), p("group", "account", "read"), p("group", "message", "write"), p("customer", "message", "write"), p("customer", "stats", "read"), // 内置超管(账户 1)绑定 admin g("1", "admin"), } } func Migrations() []*gormigrate.Migration { return []*gormigrate.Migration{ { // v0:36 张表初始结构(与 scripts/init_schema.sql 语义对齐) ID: "v0_init_schema", Migrate: func(tx *gorm.DB) error { return tx.AutoMigrate(entity.All()...) }, Rollback: func(tx *gorm.DB) error { all := entity.All() for i := len(all) - 1; i >= 0; i-- { // 倒序删除 if err := tx.Migrator().DropTable(all[i]); err != nil { return err } } return nil }, }, { // v1:种子数据(内置角色 + UT:xxxx 错误码体系,发送链路依赖) ID: "v1_seed_base_data", Migrate: func(tx *gorm.DB) error { roles := []entity.AccountRole{ {Code: "admin", Name: "管理员", IsBuiltIn: 1}, {Code: "ops", Name: "客户运维", IsBuiltIn: 1}, {Code: "service", Name: "客服", IsBuiltIn: 1}, {Code: "group", Name: "集团", IsBuiltIn: 1}, {Code: "customer", Name: "客户", IsBuiltIn: 1}, } if err := tx.Create(&roles).Error; err != nil { return err } errCodes := []entity.SystemErrorCode{ {Code: "UT:0006", Name: "黑名单", Action: 0}, {Code: "UT:0009", Name: "屏蔽地区", Action: 0}, {Code: "UT:0010", Name: "二级黑关键字/通道黑关键字", Action: 0}, {Code: "UT:0012", Name: "通道号错误", Action: 0}, {Code: "UT:0013", Name: "签名错误", Action: 0}, {Code: "UT:0014", Name: "退订错误(缺退订标识)", Action: 0}, {Code: "UT:0015", Name: "审核拒绝", Action: 0}, {Code: "UT:0016", Name: "频繁发送", Action: 0}, {Code: "UT:0021", Name: "参数不符(变量限制)", Action: 0}, {Code: "UT:0023", Name: "一级黑关键字", Action: 0}, {Code: "UT:0026", Name: "第三方黑名单", Action: 0}, {Code: "UT:0027", Name: "空号", Action: 0}, {Code: "-1", Name: "已屏蔽的子端口号", Action: 0}, {Code: "-3", Name: "发送限制/提交失败", Action: 1}, // 可重发 } return tx.Create(&errCodes).Error }, Rollback: func(tx *gorm.DB) error { // 硬删(软删行会占用唯一键导致重新迁移冲突) if err := tx.Unscoped().Where("1=1").Delete(&entity.AccountRole{}).Error; err != nil { return err } return tx.Unscoped().Where("1=1").Delete(&entity.SystemErrorCode{}).Error }, }, { // v2:错误码前缀更名 UT: → ISC:(平台标识规范变更,数据修正) ID: "v2_rename_error_code_prefix", Migrate: func(tx *gorm.DB) error { return tx.Exec("UPDATE system_error_code SET code = CONCAT('ISC:', SUBSTRING(code, 4)) WHERE code LIKE 'UT:%'").Error }, Rollback: func(tx *gorm.DB) error { return tx.Exec("UPDATE system_error_code SET code = CONCAT('UT:', SUBSTRING(code, 5)) WHERE code LIKE 'ISC:%'").Error }, }, { // v3:错误码数字段收编为三位(ISC:0xxx → ISC:0xx,规范二次更正) ID: "v3_error_code_three_digits", Migrate: func(tx *gorm.DB) error { // SUBSTRING 1-based:去掉首位 0,取第 6-8 位(ISC:0021 → ISC:021) return tx.Exec("UPDATE system_error_code SET code = CONCAT('ISC:', SUBSTRING(code, 6)) WHERE code LIKE 'ISC:0%' AND LENGTH(code) = 8").Error }, Rollback: func(tx *gorm.DB) error { return tx.Exec("UPDATE system_error_code SET code = CONCAT('ISC:0', SUBSTRING(code, 5)) WHERE code LIKE 'ISC:0%' AND LENGTH(code) = 7").Error }, }, { // v4:错误码表扩充对齐权威业务码表(Day 15 修订)。 // 以 internal/pkg/errors All() 为单一事实来源,重建 ISC 段种子 // (保留 -1/-3 通道原始转义码)。 ID: "v4_expand_error_codes", Migrate: func(tx *gorm.DB) error { if err := tx.Exec("DELETE FROM system_error_code WHERE code REGEXP '^ISC:[0-9]{3}$'").Error; err != nil { return err } var seeds []entity.SystemErrorCode for _, e := range errscodes.All() { if e.Code == errscodes.OK.Code { continue // 成功码不入错误表 } seeds = append(seeds, entity.SystemErrorCode{Code: e.Code, Name: e.Msg, Action: 0}) } return tx.Create(&seeds).Error }, Rollback: func(tx *gorm.DB) error { // 种子重建类迁移不回滚(结构无损,回滚无业务意义) return nil }, }, { // v5:RBAC 基础角色策略(casbin_rule 表 + admin/客户运维/客服/集团/客户)。 ID: "v5_seed_rbac", Migrate: func(tx *gorm.DB) error { if err := tx.AutoMigrate(&casbinRule{}); err != nil { return err } var n int64 tx.Model(&casbinRule{}).Count(&n) if n > 0 { // 幂等:已有策略不重复种入 return nil } seeds := rbacSeeds() return tx.Create(&seeds).Error }, Rollback: func(tx *gorm.DB) error { return tx.Where("1=1").Delete(&casbinRule{}).Error }, }, { // v6(Day 31):实体列幂等同步——存量库(经 scripts/init_schema.sql 或 v0 建表) // 与实体后续扩展列(账号 Day 28 real_id_card 等、通道 Day 31 协议接入/运营 16 列) // 的差量补齐。AutoMigrate 幂等:已有列跳过,缺列自动 ALTER ADD。 ID: "v6_sync_entity_columns", Migrate: func(tx *gorm.DB) error { return tx.AutoMigrate(entity.All()...) }, Rollback: func(tx *gorm.DB) error { return nil // 列同步不可逆,回滚为空操作 }, }, { // v7(Day 40 · A-3.14):通道日志表——连接事件逐条+提交/回执窗口聚合, // 为通道排障(A-3.14:连接/提交/回执完整记录)与告警留痕提供持久层。 ID: "v7_create_channel_log", Migrate: func(tx *gorm.DB) error { return tx.AutoMigrate(&entity.ChannelLog{}) }, Rollback: func(tx *gorm.DB) error { return tx.Migrator().DropTable(&entity.ChannelLog{}) }, }, { // v8(Day 41):模板表补列——TemplateSMS 新增 reason(审核拒绝原因)/audit_at // 等列的幂等补齐。教训:实体加列后版本化迁移必须跟版,否则存量库(v7+)停在 // 旧版本,v1 全量 AutoMigrate 不再执行,新列缺失导致 INSERT 1054(dev 库实测踩中)。 ID: "v8_template_sms_columns", Migrate: func(tx *gorm.DB) error { return tx.AutoMigrate(&entity.TemplateSMS{}) }, Rollback: func(tx *gorm.DB) error { return nil // 列同步不可逆,回滚为空操作 }, }, { // v9(Day 42):发送拦截日志表——拦截器链命中原因落库(send_block_log)。 ID: "v9_send_block_log", Migrate: func(tx *gorm.DB) error { return tx.AutoMigrate(&entity.SendBlockLog{}) }, Rollback: func(tx *gorm.DB) error { return tx.Migrator().DropTable(&entity.SendBlockLog{}) }, }, { // v10(Day 46):外部 HTTP API 列同步——account_config.api_secret(接口密钥 // MD5 态)、message_task.call_data、message_detail.ext_code/call_data。 // 同 v8 教训:实体加列须跟版,存量库缺列导致 INSERT 1054。 ID: "v10_openapi_columns", Migrate: func(tx *gorm.DB) error { return tx.AutoMigrate(&entity.AccountConfig{}, &entity.MessageTask{}, &entity.MessageDetail{}) }, Rollback: func(tx *gorm.DB) error { return nil // 列同步不可逆,回滚为空操作 }, }, { // v11(Day 49):上行码号分配+视频短信 biz_type——uplink_code 建表 // (码号→账号,精确/前缀两级匹配,A-4.18)、message_task.business // (sms/video 记录隔离;同 v8/v10 教训实体加列须跟版)。 ID: "v11_uplink_video", Migrate: func(tx *gorm.DB) error { return tx.AutoMigrate(&entity.UplinkCode{}, &entity.MessageTask{}) }, Rollback: func(tx *gorm.DB) error { return tx.Migrator().DropTable(&entity.UplinkCode{}) }, }, { // v12(Day 53 · runbook §6.4 P0):前端错误上报表 fe_error_log—— // request.ts 拦截器+window.onerror 双路采集,trace_id 关联后端日志链。 ID: "v12_fe_error_log", Migrate: func(tx *gorm.DB) error { return tx.AutoMigrate(&entity.FeErrorLog{}) }, Rollback: func(tx *gorm.DB) error { return tx.Migrator().DropTable(&entity.FeErrorLog{}) }, }, { // v13(Day 56):段级回执配对表——提交侧逐段登记 msg_id+mobile→detail_id, // 回执消费者按段置态聚合判终态(长短信 1~9 片段级配对,A-5.2); // 兼作回执持久化层(receipts 查询源,重启后回执可查)。 ID: "v13_report_seg", Migrate: func(tx *gorm.DB) error { return tx.AutoMigrate(&entity.MessageReportSeg{}) }, Rollback: func(tx *gorm.DB) error { return tx.Migrator().DropTable(&entity.MessageReportSeg{}) }, }, { // v14(Day 60 · D24-25 下行明细页):message_task.source 受理来源列 // (1API 2CMPP 3SMPP 4WEB,下行明细 v2 筛选维度;同 v8/v10/v11 教训 // 实体加列须跟版)。存量回填:协议接入(access 落库 submit_ip='protocol') // 统一标 2(CMPP 主流,SMPP 历史量可忽略,不细分);其余存量(HTTP API 与 // Web 控制台共用真实 IP,无法区分)统一默认 1。 ID: "v14_task_source", Migrate: func(tx *gorm.DB) error { if err := tx.AutoMigrate(&entity.MessageTask{}); err != nil { return err } return tx.Exec("UPDATE message_task SET source = 2 WHERE submit_ip = 'protocol' AND source = 1").Error }, Rollback: func(tx *gorm.DB) error { return nil // 列同步不可逆,回滚为空操作 }, }, { // v15(Day 62 · CMPP 接入配额前端可配):account_config 账号级 // cmpp_max_conns/cmpp_speed 两列(0=回退服务端系统默认;同 v8/v10/v11 // 教训实体加列须跟版)。存量 0=沿用系统默认,行为零变更。 ID: "v15_cmpp_account_limits", Migrate: func(tx *gorm.DB) error { return tx.AutoMigrate(&entity.AccountConfig{}) }, Rollback: func(tx *gorm.DB) error { return nil // 列同步不可逆,回滚为空操作 }, }, { // v16(Day 64 · 明细查询性能):message_detail 补 created_at 与 // (channel_id, created_at) 两索引——190 万行/2GB 表此前仅 // task/account_mobile/status_time 索引,时间窗查询必全表扫 // (HDD 实测 /sms/downlink-details 46-82s 超时);channel_id // 复合同时服务通道筛选与账号级 steer 排障。INPLACE 不锁 DML, // 不走 entity tag(SnowflakeModel 公共结构,避免波及全部雪花表)。 ID: "v16_detail_query_index", Migrate: func(tx *gorm.DB) error { // 空库单块重放(迁移测试)场景表未建:先补建;存量库表在则直接加索引。 if !tx.Migrator().HasTable(&entity.MessageDetail{}) { if err := tx.AutoMigrate(&entity.MessageDetail{}); err != nil { return err } } if err := tx.Exec("CREATE INDEX idx_detail_created ON message_detail (created_at)").Error; err != nil { return err } return tx.Exec("CREATE INDEX idx_detail_channel_created ON message_detail (channel_id, created_at)").Error }, Rollback: func(tx *gorm.DB) error { return nil // 索引可手工 DROP,回滚为空操作 }, }, { // v17(Day 66 · 明细查询单表化):message_detail 冗余 business/source 两列 // ——原 Count/分页常挂 JOIN message_task(business 筛选),340 万行+HDD 冷 // 缓存逐 task 随机回表实测 29.5s(百万级压测写入冲刷 buffer_pool 后); // 单表条件走 idx_business_created 覆盖扫描。存量回填不走迁移(340 万行 // 大事务,由运维后台 UPDATE JOIN 幂等补,读路径回填窗口 IN('sms','')/OR 0 // 兼容);生产列/索引可能已手工前置,AutoMigrate/HasIndex 幂等。 ID: "v17_detail_business_source", Migrate: func(tx *gorm.DB) error { if !tx.Migrator().HasTable(&entity.MessageDetail{}) { // 空库单块重放(迁移测试) if err := tx.AutoMigrate(&entity.MessageDetail{}); err != nil { return err } } // 加列走显式 SQL 不走 AutoMigrate——glebarez SQLite 下 entity 加字段 // 会触发表 diff 重建,v16 已建查询索引被抹(同 v16"不走 entity tag"教训)。 if !tx.Migrator().HasColumn(&entity.MessageDetail{}, "Business") { if err := tx.Exec("ALTER TABLE message_detail ADD COLUMN business VARCHAR(16) NOT NULL DEFAULT 'sms'").Error; err != nil { return err } } if !tx.Migrator().HasColumn(&entity.MessageDetail{}, "Source") { if err := tx.Exec("ALTER TABLE message_detail ADD COLUMN source TINYINT NOT NULL DEFAULT 1").Error; err != nil { return err } } if !tx.Migrator().HasIndex(&entity.MessageDetail{}, "idx_business_created") { return tx.Exec("CREATE INDEX idx_business_created ON message_detail (business, created_at)").Error } return nil }, Rollback: func(tx *gorm.DB) error { return nil // 列/索引可手工 DROP,回滚为空操作 }, }, { // Day68:运营总览日汇总表(全平台一行/天,60s ticker 增量 UPSERT)。 // 新表无历史索引可抹——AutoMigrate 安全(同 v13 各建各表路径)。 ID: "v18_stats_daily", Migrate: func(tx *gorm.DB) error { if tx.Migrator().HasTable(&entity.StatsDaily{}) { return nil } return tx.AutoMigrate(&entity.StatsDaily{}) }, Rollback: func(tx *gorm.DB) error { return nil // 表可手工 DROP,回滚为空操作 }, }, { // Day71:入向长短信挂起组持久化(聚合窗 10s→72h+不齐不发挂起制; // 一行=一封未收齐长短信,首片 INSERT/续片 UPDATE/到齐 DELETE, // 72h 到期 reaper 扫描失败终态后清行——表常态近空,仅异常组驻留)。 // 新表无历史索引可抹——AutoMigrate 安全(同 v18 路径)。 ID: "v19_longsms_pending", Migrate: func(tx *gorm.DB) error { if tx.Migrator().HasTable(&entity.LongSmsPending{}) { return nil } return tx.AutoMigrate(&entity.LongSmsPending{}) }, Rollback: func(tx *gorm.DB) error { return nil // 表可手工 DROP,回滚为空操作 }, }, { // S2(结算域 D 层)表基线,详见 docs/review/s2-settle-table-review.md: // ①billing_consume_log 补 unknown_count/updated_at——消耗事实源 // (R2:stats_user_daily 废弃),幂等 UPSERT 重跑需更新痕迹; // ②account_user 补 rebate_rate——代理返点率(R4,小数表示); // ③DROP stats_user_daily——同粒度双空壳,单一事实源归 billing_ // consume_log;空库路径 v0 已不再建它,DROP IF EXISTS 双方言幂等; // ④新表 settle_ladder——阶梯价档位(R5,出账时按月成功总量落档); // ⑤casbin 补结算域策略(ops settle:write / customer settle:read, // 逐条 NOT EXISTS 守卫;末段迁移单块重放路径无 casbin_rule 表, // HasTable 守卫跳过,全量链路种入)。 // 加列走显式 SQL 不走 AutoMigrate——glebarez SQLite 下 entity 加 // 字段触发表 diff 重建会抹既有索引(v16/v17 教训);空库守卫分支 // AutoMigrate 整表无此风险(表本不存在)。 ID: "v20_settle_domain", Migrate: func(tx *gorm.DB) error { if !tx.Migrator().HasTable(&entity.BillingConsumeLog{}) { // 空库守卫(同 v16/v17) if err := tx.AutoMigrate(&entity.BillingConsumeLog{}); err != nil { return err } } if !tx.Migrator().HasColumn(&entity.BillingConsumeLog{}, "UnknownCount") { if err := tx.Exec("ALTER TABLE billing_consume_log ADD COLUMN unknown_count INT NOT NULL DEFAULT 0").Error; err != nil { return err } } if !tx.Migrator().HasColumn(&entity.BillingConsumeLog{}, "UpdatedAt") { if err := tx.Exec("ALTER TABLE billing_consume_log ADD COLUMN updated_at DATETIME NULL DEFAULT NULL").Error; err != nil { return err } } if !tx.Migrator().HasTable(&entity.AccountUser{}) { // 空库守卫 if err := tx.AutoMigrate(&entity.AccountUser{}); err != nil { return err } } if !tx.Migrator().HasColumn(&entity.AccountUser{}, "RebateRate") { if err := tx.Exec("ALTER TABLE account_user ADD COLUMN rebate_rate DECIMAL(5,4) NOT NULL DEFAULT 0").Error; err != nil { return err } } if err := tx.Exec("DROP TABLE IF EXISTS stats_user_daily").Error; err != nil { return err } if !tx.Migrator().HasTable(&entity.SettleLadder{}) { // 新表,AutoMigrate 安全(同 v18/v19) if err := tx.AutoMigrate(&entity.SettleLadder{}); err != nil { return err } } if tx.Migrator().HasTable(&casbinRule{}) { // v5 才建 casbin_rule policies := []casbinRule{ {Ptype: "p", V0: "ops", V1: "settle", V2: "write"}, {Ptype: "p", V0: "customer", V1: "settle", V2: "read"}, // 客户查自己账单,scope 在 handler 侧过滤 } for _, p := range policies { var n int64 if err := tx.Model(&casbinRule{}). Where("ptype = ? AND v0 = ? AND v1 = ? AND v2 = ?", p.Ptype, p.V0, p.V1, p.V2). Count(&n).Error; err != nil { return err } if n == 0 { if err := tx.Create(&p).Error; err != nil { return err } } } } return nil }, Rollback: func(tx *gorm.DB) error { return nil // 列/表/策略可手工重建或清除,回滚为空操作(v16~v19 惯例) }, }, // v21(S4·C1)回调推送域:callback_task 队列表(指数退避+死信可查) // + ops 角色回调管理策略。表仅 AutoMigrate 空库守卫建(同 v18~v20 惯例; // 存量库首跑由 migrate 链自动补建,无列变更)。 { ID: "v21_callback_domain", Migrate: func(tx *gorm.DB) error { if !tx.Migrator().HasTable(&entity.CallbackTask{}) { if err := tx.AutoMigrate(&entity.CallbackTask{}); err != nil { return err } } if tx.Migrator().HasTable(&casbinRule{}) { // v5 才建 casbin_rule policies := []casbinRule{ {Ptype: "p", V0: "ops", V1: "callback", V2: "read"}, // 死信/任务查询 {Ptype: "p", V0: "ops", V1: "callback", V2: "write"}, // 死信重派 } for _, p := range policies { var n int64 if err := tx.Model(&casbinRule{}). Where("ptype = ? AND v0 = ? AND v1 = ? AND v2 = ?", p.Ptype, p.V0, p.V1, p.V2). Count(&n).Error; err != nil { return err } if n == 0 { if err := tx.Create(&p).Error; err != nil { return err } } } } return nil }, Rollback: func(tx *gorm.DB) error { return nil // 新表可手工清除,回滚为空操作(v16~v20 惯例) }, }, // v22(S4·D3)明细按天分区:RANGE(id)(雪花高位=时间戳,当天零点边界 // 可精确计算;主键即分区键无需改造唯一键)。分区集=热 5 天+未来 3 天 // 缓冲+pmax 兜底;滚动维护与过期 DROP 由 archive.Service 承担(归档校验 // 通过才删,见 internal/service/archive/partition.go)。MySQL only—— // sqlite 单测无分区(物理优化,方言守卫跳过)。 { ID: "v22_detail_partitions", Migrate: func(tx *gorm.DB) error { if tx.Name() != "mysql" { return nil } var n int64 if err := tx.Raw( "SELECT COUNT(*) FROM information_schema.PARTITIONS " + "WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'message_detail' " + "AND PARTITION_NAME IS NOT NULL"). // 非分区表也占一行(NULL),须排除 Scan(&n).Error; err != nil { return err } if n > 0 { return nil // 已分区(链路重放/EnsurePartitions 已先行) } now := time.Now() today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()) var parts []string for i := -4; i <= 3; i++ { // 热 5 天(今日-4..今日)+未来 3 天 day := today.AddDate(0, 0, i) boundary := (day.AddDate(0, 0, 1).UnixMilli() - util.Epoch) << (util.WorkerIDBits + util.SequenceBits) parts = append(parts, fmt.Sprintf("PARTITION p%s VALUES LESS THAN (%d)", day.Format("20060102"), boundary)) } parts = append(parts, "PARTITION pmax VALUES LESS THAN MAXVALUE") return tx.Exec("ALTER TABLE message_detail PARTITION BY RANGE (id) (" + strings.Join(parts, ", ") + ")").Error }, Rollback: func(tx *gorm.DB) error { return nil // REMOVE PARTITIONING 可手工执行,回滚为空操作(v16~v21 惯例) }, }, } } // NewMigrator 构造 gormigrate(版本记录表固定为 schema_migrations,满足验收约定)。 func NewMigrator(db *gorm.DB) *gormigrate.Gormigrate { opts := gormigrate.DefaultOptions opts.TableName = "schema_migrations" return gormigrate.New(db.Session(&gorm.Session{Logger: logger.Discard}), opts, Migrations()) } // CurrentMigrationVersion 查询 schema_migrations 当前版本(未初始化返回 nil)。 // 排序按版本号数值(如 v10>v9)——纯字典序会把 v10 排在 v9 前(历史坑:Day46 实测)。 func CurrentMigrationVersion(db *gorm.DB) (*string, error) { var rows []string if err := db.Raw("SELECT id FROM schema_migrations").Scan(&rows).Error; err != nil { return nil, err } var best *string var bestNum int64 = -1 for i := range rows { var n int64 if len(rows[i]) > 1 && rows[i][0] == 'v' { _, _ = fmt.Sscanf(rows[i], "v%d", &n) } if n > bestNum { bestNum = n best = &rows[i] } } return best, nil }