202 lines
7.4 KiB
Go
202 lines
7.4 KiB
Go
package mysql
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"testing"
|
|
|
|
"github.com/glebarez/sqlite"
|
|
"github.com/go-gormigrate/gormigrate/v2"
|
|
"gorm.io/gorm"
|
|
"gorm.io/gorm/logger"
|
|
|
|
"go-sms/internal/model/entity"
|
|
)
|
|
|
|
// TestMigrations_IdempotentAndVersioned Day 41(dev 库实测踩中 1054 后补):
|
|
// 迁移列表 ID 唯一;末两个迁移单块幂等可重放,终版号正确。
|
|
// 教训:实体加列后版本必须跟版,否则存量库停旧版,v1 全量 AutoMigrate 不再执行。
|
|
// 注:全量迁移在 sqlite 上不幂等(v1+v6 双 AutoMigrate,glebarez 索引不查重),方言
|
|
// 兼容属存量缺口,不在本测试扩线;全量以 dev MySQL 实库验证(2026-09-10 v1→v8 通过)。
|
|
func TestMigrations_IdempotentAndVersioned(t *testing.T) {
|
|
seen := map[string]bool{}
|
|
var last *gormigrate.Migration
|
|
for _, mig := range Migrations() {
|
|
if seen[mig.ID] {
|
|
t.Fatalf("迁移 ID 重复: %s", mig.ID)
|
|
}
|
|
seen[mig.ID] = true
|
|
last = mig
|
|
}
|
|
if last == nil || last.ID != "v22_detail_partitions" {
|
|
t.Fatalf("终版迁移应为 v22_detail_partitions,实际 %v", last)
|
|
}
|
|
|
|
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
|
if err != nil {
|
|
t.Fatalf("打开内存库失败: %v", err)
|
|
}
|
|
if s, e := db.DB(); e == nil {
|
|
s.SetMaxOpenConns(1) // sqlite :memory: 多连接=多个空库
|
|
}
|
|
opts := gormigrate.DefaultOptions
|
|
opts.TableName = "schema_migrations"
|
|
// 注册末七迁移(现 v16..v22;历史 v10/V11 含 MessageTask AutoMigrate,gleberez
|
|
// sqlite 索引不查重,双块连跑撞 idx_account_time——同 v1+v6 已知方言缺口;
|
|
// v15 AutoMigrate 加列、v16/v17/v20 空库守卫补建表后加列/索引、v22 分区 MySQL 守卫(sqlite 跳过)、
|
|
// v18/v19/v21 新表 AutoMigrate,v20 另含 DROP IF EXISTS 与 casbin HasTable 守卫,
|
|
// 单块两遍覆盖幂等)。
|
|
migs := Migrations()
|
|
gm := gormigrate.New(db.Session(&gorm.Session{Logger: logger.Discard}), opts, migs[len(migs)-7:])
|
|
if err := gm.Migrate(); err != nil {
|
|
t.Fatalf("v16..v22 首遍失败: %v", err)
|
|
}
|
|
if err := gm.Migrate(); err != nil {
|
|
t.Fatalf("v16..v22 二遍不幂等: %v", err)
|
|
}
|
|
v, err := CurrentMigrationVersion(db)
|
|
if err != nil {
|
|
t.Fatalf("查版本失败: %v", err)
|
|
}
|
|
if v == nil || *v != "v22_detail_partitions" {
|
|
t.Fatalf("版本应为 v22_detail_partitions,实际 %v", v)
|
|
}
|
|
// (v13/v14/v15 断言随窗口右移移除:各表/列由 v13~v15 建,
|
|
// 现窗口 v16..v22 不含;全量链路覆盖仍由 dev MySQL 实库验证。)
|
|
// Day 64:v16 后 message_detail 应有明细查询两索引(空库守卫路径建表+显式加索引)。
|
|
if !db.Migrator().HasIndex(&entity.MessageDetail{}, "idx_detail_created") ||
|
|
!db.Migrator().HasIndex(&entity.MessageDetail{}, "idx_detail_channel_created") {
|
|
t.Fatal("v16 后应存在 idx_detail_created/idx_detail_channel_created 索引")
|
|
}
|
|
// Day 66:v17 后 message_detail 应有 business/source 冗余列+单表化索引。
|
|
if !db.Migrator().HasColumn(&entity.MessageDetail{}, "Business") ||
|
|
!db.Migrator().HasColumn(&entity.MessageDetail{}, "Source") {
|
|
t.Fatal("v17 后应存在 business/source 冗余列")
|
|
}
|
|
if !db.Migrator().HasIndex(&entity.MessageDetail{}, "idx_business_created") {
|
|
t.Fatal("v17 后应存在 idx_business_created 索引")
|
|
}
|
|
// S2:v20 后 billing_consume_log 应有 unknown_count/updated_at 列,
|
|
// account_user 应有 rebate_rate 列,settle_ladder 建表且 stats_user_daily 废弃。
|
|
if !db.Migrator().HasColumn(&entity.BillingConsumeLog{}, "UnknownCount") ||
|
|
!db.Migrator().HasColumn(&entity.BillingConsumeLog{}, "UpdatedAt") {
|
|
t.Fatal("v20 后 billing_consume_log 应有 unknown_count/updated_at 列")
|
|
}
|
|
if !db.Migrator().HasColumn(&entity.AccountUser{}, "RebateRate") {
|
|
t.Fatal("v20 后 account_user 应有 rebate_rate 列")
|
|
}
|
|
if !db.Migrator().HasTable(&entity.SettleLadder{}) {
|
|
t.Fatal("v20 后应存在 settle_ladder 表")
|
|
}
|
|
if db.Migrator().HasTable("stats_user_daily") {
|
|
t.Fatal("v20 后 stats_user_daily 应已 DROP(R2 单一事实源裁决)")
|
|
}
|
|
// S4·C1:v21 后 callback_task 建表(空库守卫 AutoMigrate 路径)。
|
|
if !db.Migrator().HasTable(&entity.CallbackTask{}) {
|
|
t.Fatal("v21 后应存在 callback_task 表")
|
|
}
|
|
}
|
|
|
|
// newTestDB 内存 SQLite + 自动建表。
|
|
func newTestDB(t *testing.T) *gorm.DB {
|
|
t.Helper()
|
|
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
|
if err != nil {
|
|
t.Fatalf("打开内存库失败: %v", err)
|
|
}
|
|
if err := db.AutoMigrate(&entity.AccountUser{}); err != nil {
|
|
t.Fatalf("AutoMigrate 失败: %v", err)
|
|
}
|
|
return db
|
|
}
|
|
|
|
// TestBaseDAO_CRUDAndSoftDelete 覆盖 Create/GetByID/Updates/List/Delete 全链路。
|
|
func TestBaseDAO_CRUDAndSoftDelete(t *testing.T) {
|
|
db := newTestDB(t)
|
|
dao := NewBaseDAO[*entity.AccountUser](db)
|
|
ctx := context.Background()
|
|
|
|
// Create + GetByID
|
|
u := &entity.AccountUser{Username: "day11", PasswordHash: "x", Role: "customer", Balance: 100}
|
|
if err := dao.Create(ctx, u); err != nil {
|
|
t.Fatalf("Create: %v", err)
|
|
}
|
|
if u.ID == 0 {
|
|
t.Fatal("自增主键未回填")
|
|
}
|
|
got, err := dao.GetByID(ctx, u.ID)
|
|
if err != nil || got.Username != "day11" {
|
|
t.Fatalf("GetByID: (%v, %+v)", err, got)
|
|
}
|
|
|
|
// Updates(部分更新)
|
|
if err := dao.Updates(ctx, u.ID, map[string]any{"balance": int64(88), "status": int8(0)}); err != nil {
|
|
t.Fatalf("Updates: %v", err)
|
|
}
|
|
got, _ = dao.GetByID(ctx, u.ID)
|
|
if got.Balance != 88 || got.Status != 0 {
|
|
t.Fatalf("Updates 未生效: balance=%d status=%d", got.Balance, got.Status)
|
|
}
|
|
|
|
// CreateBatch + List(条件/分页/计数)
|
|
var batch []*entity.AccountUser
|
|
for i := 0; i < 5; i++ {
|
|
batch = append(batch, &entity.AccountUser{Username: fmt.Sprintf("batch-%d", i), Role: "ops"})
|
|
}
|
|
if err := dao.CreateBatch(ctx, batch, 2); err != nil {
|
|
t.Fatalf("CreateBatch: %v", err)
|
|
}
|
|
rows, total, err := dao.List(ctx, 0, 10, "id", "username LIKE ?", "batch-%")
|
|
if err != nil || total != 5 || len(rows) != 5 {
|
|
t.Fatalf("List: (%v, total=%d, rows=%d)", err, total, len(rows))
|
|
}
|
|
_, totalAll, _ := dao.List(ctx, 0, 10, "", nil)
|
|
if totalAll != 6 {
|
|
t.Fatalf("总数 = %d, 期望 6", totalAll)
|
|
}
|
|
|
|
// Delete 软删:GetByID 不可见,总数减少
|
|
if err := dao.Delete(ctx, u.ID); err != nil {
|
|
t.Fatalf("Delete: %v", err)
|
|
}
|
|
if _, err := dao.GetByID(ctx, u.ID); !errors.Is(err, ErrNotFound) {
|
|
t.Fatalf("软删后应 ErrNotFound: %v", err)
|
|
}
|
|
_, totalAll, _ = dao.List(ctx, 0, 10, "", nil)
|
|
if totalAll != 5 {
|
|
t.Fatalf("软删后总数 = %d, 期望 5", totalAll)
|
|
}
|
|
|
|
// 幂等/不存在
|
|
if err := dao.Delete(ctx, 99999); !errors.Is(err, ErrNotFound) {
|
|
t.Fatalf("删除不存在应 ErrNotFound: %v", err)
|
|
}
|
|
if err := dao.Updates(ctx, 99999, map[string]any{"balance": int64(1)}); !errors.Is(err, ErrNotFound) {
|
|
t.Fatalf("更新不存在应 ErrNotFound: %v", err)
|
|
}
|
|
}
|
|
|
|
// TestBaseDAO_SnowflakeModel 验证雪花主键实体 Create 不覆盖显式 ID。
|
|
func TestBaseDAO_SnowflakeModel(t *testing.T) {
|
|
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := db.AutoMigrate(&entity.MessageDetail{}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
dao := NewBaseDAO[*entity.MessageDetail](db)
|
|
ctx := context.Background()
|
|
|
|
const snowflakeID = int64(7300000000000001)
|
|
d := &entity.MessageDetail{SnowflakeModel: entity.SnowflakeModel{ID: snowflakeID}, Mobile: "13800138000", Status: 0}
|
|
if err := dao.Create(ctx, d); err != nil {
|
|
t.Fatalf("Create: %v", err)
|
|
}
|
|
got, err := dao.GetByID(ctx, snowflakeID)
|
|
if err != nil || got.Mobile != "13800138000" {
|
|
t.Fatalf("雪花 ID 读写: (%v, %+v)", err, got)
|
|
}
|
|
}
|