Support disabling database auto migration (#22053)

Gitea will migrate the database model version automatically, but it
should be able to be disabled and keep Gitea shutdown if the version is
not matched.
This commit is contained in:
Jason Song 2022-12-07 23:58:31 +08:00 committed by GitHub
parent e2fa84fddc
commit 0a85537c79
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 27 additions and 1 deletions

View file

@ -12,6 +12,8 @@ import (
"code.gitea.io/gitea/models/migrations"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting"
"xorm.io/xorm"
)
// InitDBEngine In case of problems connecting to DB, retry connection. Eg, PGSQL in Docker Container on Synology
@ -24,7 +26,7 @@ func InitDBEngine(ctx context.Context) (err error) {
default:
}
log.Info("ORM engine initialization attempt #%d/%d...", i+1, setting.Database.DBConnectRetries)
if err = db.InitEngineWithMigration(ctx, migrations.Migrate); err == nil {
if err = db.InitEngineWithMigration(ctx, migrateWithSetting); err == nil {
break
} else if i == setting.Database.DBConnectRetries-1 {
return err
@ -36,3 +38,20 @@ func InitDBEngine(ctx context.Context) (err error) {
db.HasEngine = true
return nil
}
func migrateWithSetting(x *xorm.Engine) error {
if setting.Database.AutoMigration {
return migrations.Migrate(x)
}
if current, err := migrations.GetCurrentDBVersion(x); err != nil {
return err
} else if current < 0 {
// execute migrations when the database isn't initialized even if AutoMigration is false
return migrations.Migrate(x)
} else if expected := migrations.ExpectedVersion(); current != expected {
log.Fatal(`"database.AUTO_MIGRATION" is disabled, but current database version %d is not equal to the expected version %d.`+
`You can set "database.AUTO_MIGRATION" to true or migrate manually by running "gitea [--config /path/to/app.ini] migrate"`, current, expected)
}
return nil
}