1
0

database.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. package database
  2. import (
  3. "fmt"
  4. "path/filepath"
  5. "strings"
  6. "time"
  7. "github.com/cockroachdb/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. default:
  85. panic("unreachable")
  86. }
  87. // NOTE: GORM has problem detecting existing columns, see
  88. // https://github.com/gogs/gogs/issues/6091. Therefore, only use it to create new
  89. // tables, and do customize migration with future changes.
  90. for _, table := range Tables {
  91. if db.Migrator().HasTable(table) {
  92. continue
  93. }
  94. name := strings.TrimPrefix(fmt.Sprintf("%T", table), "*database.")
  95. err = db.Migrator().AutoMigrate(table)
  96. if err != nil {
  97. return nil, errors.Wrapf(err, "auto migrate %q", name)
  98. }
  99. log.Trace("Auto migrated %q", name)
  100. }
  101. loadedLoginSourceFilesStore, err = loadLoginSourceFiles(filepath.Join(conf.CustomDir(), "conf", "auth.d"), db.NowFunc)
  102. if err != nil {
  103. return nil, errors.Wrap(err, "load login source files")
  104. }
  105. // Initialize the database handle.
  106. Handle = &DB{db: db}
  107. return db, nil
  108. }
  109. // DB is the database handler for the storage layer.
  110. type DB struct {
  111. db *gorm.DB
  112. }
  113. // Handle is the global database handle. It could be `nil` during the
  114. // installation mode.
  115. //
  116. // NOTE: Because we need to register all the routes even during the installation
  117. // mode (which initially has no database configuration), we have to use a global
  118. // variable since we can't pass a database handler around before it's available.
  119. //
  120. // NOTE: It is not guarded by a mutex because it is only written once either
  121. // during the service start or during the installation process (which is a
  122. // single-thread process).
  123. var Handle *DB
  124. func (db *DB) AccessTokens() *AccessTokensStore {
  125. return newAccessTokensStore(db.db)
  126. }
  127. func (db *DB) Actions() *ActionsStore {
  128. return newActionsStore(db.db)
  129. }
  130. func (db *DB) LFS() *LFSStore {
  131. return newLFSStore(db.db)
  132. }
  133. // NOTE: It is not guarded by a mutex because it only gets written during the
  134. // service start.
  135. var loadedLoginSourceFilesStore loginSourceFilesStore
  136. func (db *DB) LoginSources() *LoginSourcesStore {
  137. return newLoginSourcesStore(db.db, loadedLoginSourceFilesStore)
  138. }
  139. func (db *DB) Notices() *NoticesStore {
  140. return newNoticesStore(db.db)
  141. }
  142. func (db *DB) Organizations() *OrganizationsStore {
  143. return newOrganizationsStoreStore(db.db)
  144. }
  145. func (db *DB) Permissions() *PermissionsStore {
  146. return newPermissionsStore(db.db)
  147. }
  148. func (db *DB) PublicKey() *PublicKeysStore {
  149. return newPublicKeysStore(db.db)
  150. }
  151. func (db *DB) Repositories() *RepositoriesStore {
  152. return newReposStore(db.db)
  153. }
  154. func (db *DB) TwoFactors() *TwoFactorsStore {
  155. return newTwoFactorsStore(db.db)
  156. }
  157. func (db *DB) Users() *UsersStore {
  158. return newUsersStore(db.db)
  159. }