db: skip auto migrate for existing "version" table (#7057)

This commit is contained in:
Joe Chen 2022-06-14 15:47:11 +08:00 committed by GitHub
parent c0db4a7f1b
commit 4a3dc6c774
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 11 additions and 6 deletions

View File

@ -96,8 +96,9 @@ func Init(w logger.Writer) (*gorm.DB, error) {
panic("unreachable") panic("unreachable")
} }
// NOTE: GORM has problem detecting existing columns, see https://github.com/gogs/gogs/issues/6091. // NOTE: GORM has problem detecting existing columns, see
// Therefore only use it to create new tables, and do customized migration with future changes. // https://github.com/gogs/gogs/issues/6091. Therefore only use it to create new
// tables, and do customized migration with future changes.
for _, table := range Tables { for _, table := range Tables {
if db.Migrator().HasTable(table) { if db.Migrator().HasTable(table) {
continue continue

View File

@ -58,13 +58,17 @@ var migrations = []Migration{
// Migrate migrates the database schema and/or data to the current version. // Migrate migrates the database schema and/or data to the current version.
func Migrate(db *gorm.DB) error { func Migrate(db *gorm.DB) error {
// NOTE: GORM has problem migrating tables that happen to have columns with the
// same name, see https://github.com/gogs/gogs/issues/7056.
if !db.Migrator().HasTable(new(Version)) {
err := db.AutoMigrate(new(Version)) err := db.AutoMigrate(new(Version))
if err != nil { if err != nil {
return errors.Wrap(err, `auto migrate "version" table`) return errors.Wrap(err, `auto migrate "version" table`)
} }
}
var current Version var current Version
err = db.Where("id = ?", 1).First(&current).Error err := db.Where("id = ?", 1).First(&current).Error
if err == gorm.ErrRecordNotFound { if err == gorm.ErrRecordNotFound {
err = db.Create( err = db.Create(
&Version{ &Version{