diff --git a/backend/internal/database/database.go b/backend/internal/database/database.go index fe501ca..390ca8f 100644 --- a/backend/internal/database/database.go +++ b/backend/internal/database/database.go @@ -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() { diff --git a/backend/internal/model/models.go b/backend/internal/model/models.go index a31fd3b..9f3f0fb 100644 --- a/backend/internal/model/models.go +++ b/backend/internal/model/models.go @@ -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"` } diff --git a/backend/internal/router/admin/devices.go b/backend/internal/router/admin/devices.go index 5f088ae..0b17a6f 100644 --- a/backend/internal/router/admin/devices.go +++ b/backend/internal/router/admin/devices.go @@ -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 } diff --git a/backend/internal/router/agent/agent.go b/backend/internal/router/agent/agent.go index eb7ab92..1871e37 100644 --- a/backend/internal/router/agent/agent.go +++ b/backend/internal/router/agent/agent.go @@ -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 } diff --git a/backend/internal/router/app/account.go b/backend/internal/router/app/account.go index c8d7443..9edf38b 100644 --- a/backend/internal/router/app/account.go +++ b/backend/internal/router/app/account.go @@ -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, diff --git a/backend/internal/router/app/auth.go b/backend/internal/router/app/auth.go index 0d980f4..a392615 100644 --- a/backend/internal/router/app/auth.go +++ b/backend/internal/router/app/auth.go @@ -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, diff --git a/backend/internal/router/app/devices.go b/backend/internal/router/app/devices.go index ed3c00b..043d0ec 100644 --- a/backend/internal/router/app/devices.go +++ b/backend/internal/router/app/devices.go @@ -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 }