gitea源码

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. // Copyright 2024 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package db
  4. import (
  5. "context"
  6. "fmt"
  7. "strings"
  8. "code.gitea.io/gitea/modules/log"
  9. "code.gitea.io/gitea/modules/setting"
  10. "xorm.io/xorm"
  11. "xorm.io/xorm/names"
  12. )
  13. func init() {
  14. gonicNames := []string{"SSL", "UID"}
  15. for _, name := range gonicNames {
  16. names.LintGonicMapper[name] = true
  17. }
  18. }
  19. // newXORMEngine returns a new XORM engine from the configuration
  20. func newXORMEngine() (*xorm.Engine, error) {
  21. connStr, err := setting.DBConnStr()
  22. if err != nil {
  23. return nil, err
  24. }
  25. var engine *xorm.Engine
  26. if setting.Database.Type.IsPostgreSQL() && len(setting.Database.Schema) > 0 {
  27. // OK whilst we sort out our schema issues - create a schema aware postgres
  28. registerPostgresSchemaDriver()
  29. engine, err = xorm.NewEngine("postgresschema", connStr)
  30. } else {
  31. engine, err = xorm.NewEngine(setting.Database.Type.String(), connStr)
  32. }
  33. if err != nil {
  34. return nil, err
  35. }
  36. switch setting.Database.Type {
  37. case "mysql":
  38. engine.Dialect().SetParams(map[string]string{"rowFormat": "DYNAMIC"})
  39. case "mssql":
  40. engine.Dialect().SetParams(map[string]string{"DEFAULT_VARCHAR": "nvarchar"})
  41. }
  42. engine.SetSchema(setting.Database.Schema)
  43. return engine, nil
  44. }
  45. // InitEngine initializes the xorm.Engine and sets it as XORM's default context
  46. func InitEngine(ctx context.Context) error {
  47. xe, err := newXORMEngine()
  48. if err != nil {
  49. if strings.Contains(err.Error(), "SQLite3 support") {
  50. return fmt.Errorf(`sqlite3 requires: -tags sqlite,sqlite_unlock_notify%s%w`, "\n", err)
  51. }
  52. return fmt.Errorf("failed to connect to database: %w", err)
  53. }
  54. xe.SetMapper(names.GonicMapper{})
  55. // WARNING: for serv command, MUST remove the output to os.stdout,
  56. // so use log file to instead print to stdout.
  57. xe.SetLogger(NewXORMLogger(setting.Database.LogSQL))
  58. xe.ShowSQL(setting.Database.LogSQL)
  59. xe.SetMaxOpenConns(setting.Database.MaxOpenConns)
  60. xe.SetMaxIdleConns(setting.Database.MaxIdleConns)
  61. xe.SetConnMaxLifetime(setting.Database.ConnMaxLifetime)
  62. if setting.Database.SlowQueryThreshold > 0 {
  63. xe.AddHook(&EngineHook{
  64. Threshold: setting.Database.SlowQueryThreshold,
  65. Logger: log.GetLogger("xorm"),
  66. })
  67. }
  68. SetDefaultEngine(ctx, xe)
  69. return nil
  70. }
  71. // SetDefaultEngine sets the default engine for db
  72. func SetDefaultEngine(ctx context.Context, eng *xorm.Engine) {
  73. xormEngine = eng
  74. xormEngine.SetDefaultContext(ctx)
  75. }
  76. // UnsetDefaultEngine closes and unsets the default engine
  77. // We hope the SetDefaultEngine and UnsetDefaultEngine can be paired, but it's impossible now,
  78. // there are many calls to InitEngine -> SetDefaultEngine directly to overwrite the `xormEngine` and `xormContext` without close
  79. // Global database engine related functions are all racy and there is no graceful close right now.
  80. func UnsetDefaultEngine() {
  81. if xormEngine != nil {
  82. _ = xormEngine.Close()
  83. xormEngine = nil
  84. }
  85. }
  86. // InitEngineWithMigration initializes a new xorm.Engine and sets it as the XORM's default context
  87. // This function must never call .Sync() if the provided migration function fails.
  88. // When called from the "doctor" command, the migration function is a version check
  89. // that prevents the doctor from fixing anything in the database if the migration level
  90. // is different from the expected value.
  91. func InitEngineWithMigration(ctx context.Context, migrateFunc func(context.Context, *xorm.Engine) error) (err error) {
  92. if err = InitEngine(ctx); err != nil {
  93. return err
  94. }
  95. if err = xormEngine.Ping(); err != nil {
  96. return err
  97. }
  98. preprocessDatabaseCollation(xormEngine)
  99. // We have to run migrateFunc here in case the user is re-running installation on a previously created DB.
  100. // If we do not then table schemas will be changed and there will be conflicts when the migrations run properly.
  101. //
  102. // Installation should only be being re-run if users want to recover an old database.
  103. // However, we should think carefully about should we support re-install on an installed instance,
  104. // as there may be other problems due to secret reinitialization.
  105. if err = migrateFunc(ctx, xormEngine); err != nil {
  106. return fmt.Errorf("migrate: %w", err)
  107. }
  108. if err = SyncAllTables(); err != nil {
  109. return fmt.Errorf("sync database struct error: %w", err)
  110. }
  111. for _, initFunc := range registeredInitFuncs {
  112. if err := initFunc(); err != nil {
  113. return fmt.Errorf("initFunc failed: %w", err)
  114. }
  115. }
  116. return nil
  117. }