database.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. // Copyright 2020 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package database
  5. import (
  6. "fmt"
  7. "path/filepath"
  8. "strings"
  9. "time"
  10. "github.com/pkg/errors"
  11. "gorm.io/gorm"
  12. "gorm.io/gorm/logger"
  13. "gorm.io/gorm/schema"
  14. log "unknwon.dev/clog/v2"
  15. "gogs.io/gogs/internal/conf"
  16. "gogs.io/gogs/internal/dbutil"
  17. )
  18. func newLogWriter() (logger.Writer, error) {
  19. sec := conf.File.Section("log.gorm")
  20. w, err := log.NewFileWriter(
  21. filepath.Join(conf.Log.RootPath, "gorm.log"),
  22. log.FileRotationConfig{
  23. Rotate: sec.Key("ROTATE").MustBool(true),
  24. Daily: sec.Key("ROTATE_DAILY").MustBool(true),
  25. MaxSize: sec.Key("MAX_SIZE").MustInt64(100) * 1024 * 1024,
  26. MaxDays: sec.Key("MAX_DAYS").MustInt64(3),
  27. },
  28. )
  29. if err != nil {
  30. return nil, errors.Wrap(err, `create "gorm.log"`)
  31. }
  32. return &dbutil.Logger{Writer: w}, nil
  33. }
  34. // Tables is the list of struct-to-table mappings.
  35. //
  36. // NOTE: Lines are sorted in alphabetical order, each letter in its own line.
  37. //
  38. // ⚠️ WARNING: This list is meant to be read-only.
  39. var Tables = []any{
  40. new(Access), new(AccessToken), new(Action),
  41. new(EmailAddress),
  42. new(Follow),
  43. new(LFSObject), new(LoginSource),
  44. new(Notice),
  45. }
  46. // NewConnection returns a new database connection with the given logger.
  47. func NewConnection(w logger.Writer) (*gorm.DB, error) {
  48. level := logger.Info
  49. if conf.IsProdMode() {
  50. level = logger.Warn
  51. }
  52. // NOTE: AutoMigrate does not respect logger passed in gorm.Config.
  53. logger.Default = logger.New(w, logger.Config{
  54. SlowThreshold: 100 * time.Millisecond,
  55. LogLevel: level,
  56. })
  57. db, err := dbutil.OpenDB(
  58. conf.Database,
  59. &gorm.Config{
  60. SkipDefaultTransaction: true,
  61. NamingStrategy: schema.NamingStrategy{
  62. SingularTable: true,
  63. },
  64. NowFunc: func() time.Time {
  65. return time.Now().UTC().Truncate(time.Microsecond)
  66. },
  67. },
  68. )
  69. if err != nil {
  70. return nil, errors.Wrap(err, "open database")
  71. }
  72. sqlDB, err := db.DB()
  73. if err != nil {
  74. return nil, errors.Wrap(err, "get underlying *sql.DB")
  75. }
  76. sqlDB.SetMaxOpenConns(conf.Database.MaxOpenConns)
  77. sqlDB.SetMaxIdleConns(conf.Database.MaxIdleConns)
  78. sqlDB.SetConnMaxLifetime(time.Minute)
  79. switch conf.Database.Type {
  80. case "postgres":
  81. conf.UsePostgreSQL = true
  82. case "mysql":
  83. conf.UseMySQL = true
  84. db = db.Set("gorm:table_options", "ENGINE=InnoDB").Session(&gorm.Session{})
  85. case "sqlite3":
  86. conf.UseSQLite3 = true
  87. case "mssql":
  88. conf.UseMSSQL = true
  89. default:
  90. panic("unreachable")
  91. }
  92. // NOTE: GORM has problem detecting existing columns, see
  93. // https://github.com/gogs/gogs/issues/6091. Therefore, only use it to create new
  94. // tables, and do customize migration with future changes.
  95. for _, table := range Tables {
  96. if db.Migrator().HasTable(table) {
  97. continue
  98. }
  99. name := strings.TrimPrefix(fmt.Sprintf("%T", table), "*database.")
  100. err = db.Migrator().AutoMigrate(table)
  101. if err != nil {
  102. return nil, errors.Wrapf(err, "auto migrate %q", name)
  103. }
  104. log.Trace("Auto migrated %q", name)
  105. }
  106. loadedLoginSourceFilesStore, err = loadLoginSourceFiles(filepath.Join(conf.CustomDir(), "conf", "auth.d"), db.NowFunc)
  107. if err != nil {
  108. return nil, errors.Wrap(err, "load login source files")
  109. }
  110. // Initialize the database handle.
  111. Handle = &DB{db: db}
  112. return db, nil
  113. }
  114. // DB is the database handler for the storage layer.
  115. type DB struct {
  116. db *gorm.DB
  117. }
  118. // Handle is the global database handle. It could be `nil` during the
  119. // installation mode.
  120. //
  121. // NOTE: Because we need to register all the routes even during the installation
  122. // mode (which initially has no database configuration), we have to use a global
  123. // variable since we can't pass a database handler around before it's available.
  124. //
  125. // NOTE: It is not guarded by a mutex because it is only written once either
  126. // during the service start or during the installation process (which is a
  127. // single-thread process).
  128. var Handle *DB
  129. func (db *DB) AccessTokens() *AccessTokensStore {
  130. return newAccessTokensStore(db.db)
  131. }
  132. func (db *DB) Actions() *ActionsStore {
  133. return newActionsStore(db.db)
  134. }
  135. func (db *DB) LFS() *LFSStore {
  136. return newLFSStore(db.db)
  137. }
  138. // NOTE: It is not guarded by a mutex because it only gets written during the
  139. // service start.
  140. var loadedLoginSourceFilesStore loginSourceFilesStore
  141. func (db *DB) LoginSources() *LoginSourcesStore {
  142. return newLoginSourcesStore(db.db, loadedLoginSourceFilesStore)
  143. }
  144. func (db *DB) Notices() *NoticesStore {
  145. return newNoticesStore(db.db)
  146. }
  147. func (db *DB) Organizations() *OrganizationsStore {
  148. return newOrganizationsStoreStore(db.db)
  149. }
  150. func (db *DB) Permissions() *PermissionsStore {
  151. return newPermissionsStore(db.db)
  152. }
  153. func (db *DB) PublicKey() *PublicKeysStore {
  154. return newPublicKeysStore(db.db)
  155. }
  156. func (db *DB) Repositories() *RepositoriesStore {
  157. return newReposStore(db.db)
  158. }
  159. func (db *DB) TwoFactors() *TwoFactorsStore {
  160. return newTwoFactorsStore(db.db)
  161. }
  162. func (db *DB) Users() *UsersStore {
  163. return newUsersStore(db.db)
  164. }