refactor(model): 从根上消除 device_id 字段歧义,撤掉迁移特例
上一版用 skipMigrateOnMySQL 绕过了 GORM 的误判,属于打补丁。真正的根因是 DeviceSession.DeviceID 与 UserDevice.DeviceID 同名,GORM 推断外键时选错对象。 - DeviceSession.DeviceID → UserDeviceID,tag 钉死 column:device_id 与索引名 idx_device_sessions_device_id(与线上现有索引同名,不产生任何 DDL 变更) - 双向关系显式写 foreignKey:UserDeviceID;references:ID - 删除 skipMigrateOnMySQL 及相关预检函数,AutoMigrate 恢复对这些表的正常管理 - JSON 键仍为 device_id,接口不变;所有 Go 引用同步改名 验证:全新 sqlite 建库列/索引与线上一致;老库登录后 device_sessions 正确写入 user_devices.id;四处 PRAGMA 的 sqlite 守卫保留
This commit is contained in:
@@ -251,9 +251,6 @@ func runMigrations() {
|
||||
}
|
||||
for _, m := range models {
|
||||
var err error
|
||||
if skipMigrateOnMySQL(m) {
|
||||
continue
|
||||
}
|
||||
if DB.Migrator().HasTable(m) {
|
||||
err = DB.AutoMigrate(m)
|
||||
} else {
|
||||
@@ -807,55 +804,6 @@ func isSQLiteDB() bool {
|
||||
return t == "sqlite" || t == ""
|
||||
}
|
||||
|
||||
// isMySQLDB 当前连接是不是 mysql
|
||||
func isMySQLDB() bool { return strings.ToLower(config.GetString("database.type")) == "mysql" }
|
||||
|
||||
// skipMigrateOnMySQL 决定是否跳过某张表的 AutoMigrate。
|
||||
//
|
||||
// 背景:UserDevice 与 DeviceSession 里都有名为 device_id 的字段(前者是设备指纹字符串,
|
||||
// 后者是指向 user_devices.id 的数值外键)。GORM 在推断这两个关系时会选错 foreignKey,
|
||||
// 每次启动都试图把 user_devices.device_id 改回数值类型(MySQL 报 1265 Data truncated),
|
||||
// 同时去 DROP 一个早已不存在的 uni_device_sessions_instance_id(报 1091)。
|
||||
//
|
||||
// 这两张表的结构已由 fixDeviceIDColumnType() 与显式 DDL 兜住,只要关键列/索引齐全
|
||||
// 就跳过 AutoMigrate,日志干净、也不会对线上表做无意义的 DDL 尝试。
|
||||
// 以后给这两张表加字段,需要在这里补一条 ensureColumn(或手动迁移)。
|
||||
func skipMigrateOnMySQL(m interface{}) bool {
|
||||
if !isMySQLDB() {
|
||||
return false
|
||||
}
|
||||
switch m.(type) {
|
||||
case *model.UserDevice:
|
||||
return mysqlColumnReady("user_devices", "device_id", "varchar")
|
||||
case *model.DeviceSession:
|
||||
return mysqlColumnReady("device_sessions", "device_id", "bigint") &&
|
||||
mysqlIndexExists("device_sessions", "idx_device_instance")
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// mysqlColumnReady 列存在且类型前缀符合预期
|
||||
func mysqlColumnReady(table, column, typePrefix string) bool {
|
||||
var ct string
|
||||
if err := DB.Raw("SELECT column_type FROM information_schema.columns "+
|
||||
"WHERE table_schema = DATABASE() AND table_name = ? AND column_name = ?", table, column).
|
||||
Scan(&ct).Error; err != nil || ct == "" {
|
||||
return false
|
||||
}
|
||||
return strings.HasPrefix(strings.ToLower(ct), typePrefix)
|
||||
}
|
||||
|
||||
// mysqlIndexExists 索引是否已存在
|
||||
func mysqlIndexExists(table, index string) bool {
|
||||
var n int64
|
||||
if err := DB.Raw("SELECT COUNT(*) FROM information_schema.statistics "+
|
||||
"WHERE table_schema = DATABASE() AND table_name = ? AND index_name = ?", table, index).
|
||||
Scan(&n).Error; err != nil {
|
||||
return false
|
||||
}
|
||||
return n > 0
|
||||
}
|
||||
|
||||
// fixDeviceIDColumnType 把 user_devices.device_id 从数值类型改成字符串类型。
|
||||
// 只在 MySQL 上执行;列类型已经是 varchar 时跳过,可重复执行。
|
||||
func fixDeviceIDColumnType() {
|
||||
|
||||
@@ -842,13 +842,20 @@ type UserDevice struct {
|
||||
|
||||
User AppUser `gorm:"foreignKey:UserID" json:"user,omitempty"`
|
||||
Application Application `gorm:"foreignKey:ApplicationID" json:"application,omitempty"`
|
||||
Sessions []DeviceSession `gorm:"foreignKey:DeviceID;references:ID" json:"sessions,omitempty"`
|
||||
Sessions []DeviceSession `gorm:"foreignKey:UserDeviceID;references:ID" json:"sessions,omitempty"`
|
||||
}
|
||||
|
||||
// DeviceSession 设备会话模型(多开实例,运行时)
|
||||
// DeviceSession 一条「设备上的一个实例」的在线记录。
|
||||
//
|
||||
// 注意 UserDeviceID 的命名:它对应列 device_id,指向 user_devices.id。
|
||||
// 早先这个字段叫 DeviceID,和 UserDevice.DeviceID(设备指纹字符串)同名,
|
||||
// 导致 GORM 推断外键时选错对象,每次 AutoMigrate 都想把 user_devices.device_id
|
||||
// 改成数值型(MySQL 报 1265)并 DROP 不存在的索引(1091)。
|
||||
// 改名后关系不再有歧义;列名与索引名都用 tag 钉死,表结构保持原样。
|
||||
type DeviceSession struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
DeviceID uint `gorm:"index" json:"device_id"`
|
||||
UserDeviceID uint `gorm:"column:device_id;index:idx_device_sessions_device_id" json:"device_id"`
|
||||
UserID uint `gorm:"index" json:"user_id"`
|
||||
ApplicationID uint `gorm:"index" json:"application_id"`
|
||||
InstanceID string `gorm:"size:100;uniqueIndex:idx_device_instance" json:"instance_id"`
|
||||
@@ -856,7 +863,7 @@ type DeviceSession struct {
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
|
||||
Device UserDevice `gorm:"foreignKey:DeviceID" json:"device,omitempty"`
|
||||
Device UserDevice `gorm:"foreignKey:UserDeviceID;references:ID" json:"device,omitempty"`
|
||||
User AppUser `gorm:"foreignKey:UserID" json:"user,omitempty"`
|
||||
Application Application `gorm:"foreignKey:ApplicationID" json:"application,omitempty"`
|
||||
}
|
||||
|
||||
@@ -431,7 +431,7 @@ func HandleGetSessions(c *gin.Context) {
|
||||
sessionsWithDetails := make([]SessionWithDetails, 0, len(sessions))
|
||||
for _, session := range sessions {
|
||||
var device model.UserDevice
|
||||
if err := database.DB.First(&device, session.DeviceID).Error; err != nil {
|
||||
if err := database.DB.First(&device, session.UserDeviceID).Error; err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
|
||||
@@ -1581,7 +1581,7 @@ func handleGetSessions(c *gin.Context) {
|
||||
result := make([]SessionWithDetails, 0, len(sessions))
|
||||
for _, session := range sessions {
|
||||
var device model.UserDevice
|
||||
if err := database.DB.First(&device, session.DeviceID).Error; err != nil {
|
||||
if err := database.DB.First(&device, session.UserDeviceID).Error; err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
|
||||
@@ -185,7 +185,7 @@ func handleAppHeartbeat(c *gin.Context) {
|
||||
|
||||
if sessionErr != nil {
|
||||
session = model.DeviceSession{
|
||||
DeviceID: device.ID,
|
||||
UserDeviceID: device.ID,
|
||||
UserID: user.ID,
|
||||
ApplicationID: app.ID,
|
||||
InstanceID: instanceID,
|
||||
|
||||
@@ -370,7 +370,7 @@ func handleAppRegister(c *gin.Context) {
|
||||
|
||||
if sessionErr != nil {
|
||||
session = model.DeviceSession{
|
||||
DeviceID: device.ID,
|
||||
UserDeviceID: device.ID,
|
||||
UserID: user.ID,
|
||||
ApplicationID: appModel.ID,
|
||||
InstanceID: instanceID,
|
||||
@@ -664,7 +664,7 @@ func handleAppLogin(c *gin.Context) {
|
||||
var session model.DeviceSession
|
||||
if err := database.DB.Where("device_id = ? AND instance_id = ?", device.ID, instanceID).First(&session).Error; err != nil {
|
||||
session = model.DeviceSession{
|
||||
DeviceID: device.ID,
|
||||
UserDeviceID: device.ID,
|
||||
UserID: user.ID,
|
||||
ApplicationID: appModel.ID,
|
||||
InstanceID: instanceID,
|
||||
|
||||
@@ -277,7 +277,7 @@ func handleAppGetInstances(c *gin.Context) {
|
||||
|
||||
var device model.UserDevice
|
||||
for _, d := range devices {
|
||||
if d.ID == session.DeviceID {
|
||||
if d.ID == session.UserDeviceID {
|
||||
device = d
|
||||
break
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user