database.go 4.7 KB

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