Files
goauto/server/cmd/migrate/server.go
T
QiuSWandClaude Opus 5 e6f533b71e fix(#48): add the missing version-local migration for syb_session
Adding SYBSession to migrations.Migrate was not enough. Schema reaches an
existing database only through a version-local file; with the previous
version already recorded in sys_migration, Migrate never re-ran and the
table simply never appeared. The unit tests build a fresh database every
time, so they stayed green while the real database was missing a table —
which surfaced as "Error 1146: Table 'goauto.syb_session' doesn't exist"
on the first import attempt.

server/.gitignore was hiding these files. go-admin ignores version-local
because it is where generated local migrations land, but every GoAuto
migration belongs in version control; the existing ones had been forced
in with `git add -f`. Un-ignoring *.go there also recovers four migrations
that were never committed at all — 1786700000000 through 1786700300000,
covering the base schema, device registration, heartbeat and collection
execution. A fresh clone could not have built a working database.

Guard the class of mistake rather than just this instance:

  - migrations.VerifyTables checks every model's table after migrating and
    names what is missing along with the fix.
  - The migrate command runs it, so the failure lands at migrate time
    instead of at the first request that needs the table.
  - initDB no longer discards migrateModel's error. Upstream had
    `_ = migrateModel()` followed by an unconditional "初始化成功", so a
    failed migration reported success and the launcher believed it.

Also records the two-step rule in Common-Changes: a new model needs both
the model registration and a new version file.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-20 10:10:11 +08:00

132 lines
3.6 KiB
Go

package migrate
import (
"bytes"
"fmt"
"github.com/go-admin-team/go-admin-core/sdk"
"github.com/go-admin-team/go-admin-core/sdk/pkg"
"os"
"strconv"
"text/template"
"time"
"github.com/go-admin-team/go-admin-core/config/source/file"
"github.com/spf13/cobra"
"github.com/go-admin-team/go-admin-core/sdk/config"
goautomigrations "go-admin/app/goauto/migrations"
"go-admin/cmd/migrate/migration"
_ "go-admin/cmd/migrate/migration/version"
_ "go-admin/cmd/migrate/migration/version-local"
"go-admin/common/database"
"go-admin/common/models"
ext "go-admin/config"
)
var (
configYml string
generate bool
goAdmin bool
host string
StartCmd = &cobra.Command{
Use: "migrate",
Short: "Initialize the database",
Example: "go-admin migrate -c config/settings.yml",
Run: func(cmd *cobra.Command, args []string) {
run()
},
}
)
// fixme 在您看不见代码的时候运行迁移,我觉得是不安全的,所以编译后最好不要去执行迁移
func init() {
StartCmd.PersistentFlags().StringVarP(&configYml, "config", "c", "config/settings.yml", "Start server with provided configuration file")
StartCmd.PersistentFlags().BoolVarP(&generate, "generate", "g", false, "generate migration file")
StartCmd.PersistentFlags().BoolVarP(&goAdmin, "goAdmin", "a", false, "generate go-admin migration file")
StartCmd.PersistentFlags().StringVarP(&host, "domain", "d", "*", "select tenant host")
}
func run() {
if !generate {
fmt.Println(`start init`)
//1. 读取配置
config.Setup(
file.NewSource(file.WithPath(configYml)),
ext.ApplyLocalConfig,
ext.ApplyEnvironment,
initDB,
)
} else {
fmt.Println(`generate migration file`)
_ = genFile()
}
}
func migrateModel() error {
if host == "" {
host = "*"
}
db := sdk.Runtime.GetDbByKey(host)
if db == nil {
if len(sdk.Runtime.GetDb()) == 1 && host == "*" {
for k, v := range sdk.Runtime.GetDb() {
db = v
host = k
break
}
}
}
if db == nil {
return fmt.Errorf("未找到数据库配置")
}
if config.DatabasesConfig[host].Driver == "mysql" {
//初始化数据库时候用
db.Set("gorm:table_options", "ENGINE=InnoDB CHARSET=utf8mb4")
}
err := db.Debug().AutoMigrate(&models.Migration{})
if err != nil {
return err
}
migration.Migrate.SetDb(db.Debug())
migration.Migrate.Migrate()
// GoAuto 改动(#48):迁移跑完后核对 GoAuto 的表是否都在。
// 新增模型时若忘了加 version-local 版本文件,迁移会「成功」但表不会建出来,
// 直到运行时才炸成一句 Error 1146。这里让它在迁移阶段就报出表名。
return goautomigrations.VerifyTables(db)
}
func initDB() {
//3. 初始化数据库链接
database.Setup()
//4. 数据库迁移
fmt.Println("数据库迁移开始")
// GoAuto 改动(#48):上游这里是 `_ = migrateModel()`,丢掉错误后无条件
// 打印「成功」——迁移失败也会报成功,启动脚本据此认为一切正常。
if err := migrateModel(); err != nil {
fmt.Println("数据库迁移失败:", err)
os.Exit(1)
}
fmt.Println(`数据库基础数据初始化成功`)
}
func genFile() error {
t1, err := template.ParseFiles("template/migrate.template")
if err != nil {
return err
}
m := map[string]string{}
m["GenerateTime"] = strconv.FormatInt(time.Now().UnixNano()/1e6, 10)
m["Package"] = "version_local"
if goAdmin {
m["Package"] = "version"
}
var b1 bytes.Buffer
err = t1.Execute(&b1, m)
if goAdmin {
pkg.FileCreate(b1, "./cmd/migrate/migration/version/"+m["GenerateTime"]+"_migrate.go")
} else {
pkg.FileCreate(b1, "./cmd/migrate/migration/version-local/"+m["GenerateTime"]+"_migrate.go")
}
return nil
}