You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

db.go 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Copyright 2021 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package common
  4. import (
  5. "context"
  6. "fmt"
  7. "time"
  8. "code.gitea.io/gitea/models/db"
  9. "code.gitea.io/gitea/models/migrations"
  10. "code.gitea.io/gitea/modules/log"
  11. "code.gitea.io/gitea/modules/setting"
  12. "xorm.io/xorm"
  13. )
  14. // InitDBEngine In case of problems connecting to DB, retry connection. Eg, PGSQL in Docker Container on Synology
  15. func InitDBEngine(ctx context.Context) (err error) {
  16. log.Info("Beginning ORM engine initialization.")
  17. for i := 0; i < setting.Database.DBConnectRetries; i++ {
  18. select {
  19. case <-ctx.Done():
  20. return fmt.Errorf("Aborted due to shutdown:\nin retry ORM engine initialization")
  21. default:
  22. }
  23. log.Info("ORM engine initialization attempt #%d/%d...", i+1, setting.Database.DBConnectRetries)
  24. if err = db.InitEngineWithMigration(ctx, migrateWithSetting); err == nil {
  25. break
  26. } else if i == setting.Database.DBConnectRetries-1 {
  27. return err
  28. }
  29. log.Error("ORM engine initialization attempt #%d/%d failed. Error: %v", i+1, setting.Database.DBConnectRetries, err)
  30. log.Info("Backing off for %d seconds", int64(setting.Database.DBConnectBackoff/time.Second))
  31. time.Sleep(setting.Database.DBConnectBackoff)
  32. }
  33. db.HasEngine = true
  34. return nil
  35. }
  36. func migrateWithSetting(x *xorm.Engine) error {
  37. if setting.Database.AutoMigration {
  38. return migrations.Migrate(x)
  39. }
  40. if current, err := migrations.GetCurrentDBVersion(x); err != nil {
  41. return err
  42. } else if current < 0 {
  43. // execute migrations when the database isn't initialized even if AutoMigration is false
  44. return migrations.Migrate(x)
  45. } else if expected := migrations.ExpectedVersion(); current != expected {
  46. log.Fatal(`"database.AUTO_MIGRATION" is disabled, but current database version %d is not equal to the expected version %d.`+
  47. `You can set "database.AUTO_MIGRATION" to true or migrate manually by running "gitea [--config /path/to/app.ini] migrate"`, current, expected)
  48. }
  49. return nil
  50. }