database.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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(GPGKey),
  44. new(LFSObject), new(LoginSource),
  45. new(Notice),
  46. }
  47. // NewConnection returns a new database connection with the given logger.
  48. func NewConnection(w logger.Writer) (*gorm.DB, error) {
  49. level := logger.Info
  50. if conf.IsProdMode() {
  51. level = logger.Warn
  52. }
  53. // NOTE: AutoMigrate does not respect logger passed in gorm.Config.
  54. logger.Default = logger.New(w, logger.Config{
  55. SlowThreshold: 100 * time.Millisecond,
  56. LogLevel: level,
  57. })
  58. db, err := dbutil.OpenDB(
  59. conf.Database,
  60. &gorm.Config{
  61. SkipDefaultTransaction: true,
  62. NamingStrategy: schema.NamingStrategy{
  63. SingularTable: true,
  64. },
  65. NowFunc: func() time.Time {
  66. return time.Now().UTC().Truncate(time.Microsecond)
  67. },
  68. },
  69. )
  70. if err != nil {
  71. return nil, errors.Wrap(err, "open database")
  72. }
  73. sqlDB, err := db.DB()
  74. if err != nil {
  75. return nil, errors.Wrap(err, "get underlying *sql.DB")
  76. }
  77. sqlDB.SetMaxOpenConns(conf.Database.MaxOpenConns)
  78. sqlDB.SetMaxIdleConns(conf.Database.MaxIdleConns)
  79. sqlDB.SetConnMaxLifetime(time.Minute)
  80. switch conf.Database.Type {
  81. case "postgres":
  82. conf.UsePostgreSQL = true
  83. case "mysql":
  84. conf.UseMySQL = true
  85. db = db.Set("gorm:table_options", "ENGINE=InnoDB").Session(&gorm.Session{})
  86. case "sqlite3":
  87. conf.UseSQLite3 = true
  88. case "mssql":
  89. conf.UseMSSQL = true
  90. default:
  91. panic("unreachable")
  92. }
  93. // NOTE: GORM has problem detecting existing columns, see
  94. // https://github.com/gogs/gogs/issues/6091. Therefore, only use it to create new
  95. // tables, and do customize migration with future changes.
  96. for _, table := range Tables {
  97. if db.Migrator().HasTable(table) {
  98. continue
  99. }
  100. name := strings.TrimPrefix(fmt.Sprintf("%T", table), "*database.")
  101. err = db.Migrator().AutoMigrate(table)
  102. if err != nil {
  103. return nil, errors.Wrapf(err, "auto migrate %q", name)
  104. }
  105. log.Trace("Auto migrated %q", name)
  106. }
  107. loadedLoginSourceFilesStore, err = loadLoginSourceFiles(filepath.Join(conf.CustomDir(), "conf", "auth.d"), db.NowFunc)
  108. if err != nil {
  109. return nil, errors.Wrap(err, "load login source files")
  110. }
  111. // Initialize the database handle.
  112. Handle = &DB{db: db}
  113. return db, nil
  114. }
  115. // DB is the database handler for the storage layer.
  116. type DB struct {
  117. db *gorm.DB
  118. }
  119. // Handle is the global database handle. It could be `nil` during the
  120. // installation mode.
  121. //
  122. // NOTE: Because we need to register all the routes even during the installation
  123. // mode (which initially has no database configuration), we have to use a global
  124. // variable since we can't pass a database handler around before it's available.
  125. //
  126. // NOTE: It is not guarded by a mutex because it is only written once either
  127. // during the service start or during the installation process (which is a
  128. // single-thread process).
  129. var Handle *DB
  130. func (db *DB) AccessTokens() *AccessTokensStore {
  131. return newAccessTokensStore(db.db)
  132. }
  133. func (db *DB) Actions() *ActionsStore {
  134. return newActionsStore(db.db)
  135. }
  136. func (db *DB) GPGKeys() *GPGKeysStore {
  137. return newGPGKeysStore(db.db)
  138. }
  139. func (db *DB) LFS() *LFSStore {
  140. return newLFSStore(db.db)
  141. }
  142. // NOTE: It is not guarded by a mutex because it only gets written during the
  143. // service start.
  144. var loadedLoginSourceFilesStore loginSourceFilesStore
  145. func (db *DB) LoginSources() *LoginSourcesStore {
  146. return newLoginSourcesStore(db.db, loadedLoginSourceFilesStore)
  147. }
  148. func (db *DB) Notices() *NoticesStore {
  149. return newNoticesStore(db.db)
  150. }
  151. func (db *DB) Organizations() *OrganizationsStore {
  152. return newOrganizationsStoreStore(db.db)
  153. }
  154. func (db *DB) Permissions() *PermissionsStore {
  155. return newPermissionsStore(db.db)
  156. }
  157. func (db *DB) PublicKey() *PublicKeysStore {
  158. return newPublicKeysStore(db.db)
  159. }
  160. func (db *DB) Repositories() *RepositoriesStore {
  161. return newReposStore(db.db)
  162. }
  163. func (db *DB) TwoFactors() *TwoFactorsStore {
  164. return newTwoFactorsStore(db.db)
  165. }
  166. func (db *DB) Users() *UsersStore {
  167. return newUsersStore(db.db)
  168. }