db.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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 db
  5. import (
  6. "fmt"
  7. "net/url"
  8. "path/filepath"
  9. "strings"
  10. "time"
  11. "github.com/pkg/errors"
  12. "gorm.io/driver/mysql"
  13. "gorm.io/driver/postgres"
  14. "gorm.io/driver/sqlite"
  15. "gorm.io/driver/sqlserver"
  16. "gorm.io/gorm"
  17. "gorm.io/gorm/logger"
  18. "gorm.io/gorm/schema"
  19. log "unknwon.dev/clog/v2"
  20. "gogs.io/gogs/internal/conf"
  21. "gogs.io/gogs/internal/dbutil"
  22. )
  23. // parsePostgreSQLHostPort parses given input in various forms defined in
  24. // https://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING
  25. // and returns proper host and port number.
  26. func parsePostgreSQLHostPort(info string) (host, port string) {
  27. host, port = "127.0.0.1", "5432"
  28. if strings.Contains(info, ":") && !strings.HasSuffix(info, "]") {
  29. idx := strings.LastIndex(info, ":")
  30. host = info[:idx]
  31. port = info[idx+1:]
  32. } else if len(info) > 0 {
  33. host = info
  34. }
  35. return host, port
  36. }
  37. func parseMSSQLHostPort(info string) (host, port string) {
  38. host, port = "127.0.0.1", "1433"
  39. if strings.Contains(info, ":") {
  40. host = strings.Split(info, ":")[0]
  41. port = strings.Split(info, ":")[1]
  42. } else if strings.Contains(info, ",") {
  43. host = strings.Split(info, ",")[0]
  44. port = strings.TrimSpace(strings.Split(info, ",")[1])
  45. } else if len(info) > 0 {
  46. host = info
  47. }
  48. return host, port
  49. }
  50. // parseDSN takes given database options and returns parsed DSN.
  51. func parseDSN(opts conf.DatabaseOpts) (dsn string, err error) {
  52. // In case the database name contains "?" with some parameters
  53. concate := "?"
  54. if strings.Contains(opts.Name, concate) {
  55. concate = "&"
  56. }
  57. switch opts.Type {
  58. case "mysql":
  59. if opts.Host[0] == '/' { // Looks like a unix socket
  60. dsn = fmt.Sprintf("%s:%s@unix(%s)/%s%scharset=utf8mb4&parseTime=true",
  61. opts.User, opts.Password, opts.Host, opts.Name, concate)
  62. } else {
  63. dsn = fmt.Sprintf("%s:%s@tcp(%s)/%s%scharset=utf8mb4&parseTime=true",
  64. opts.User, opts.Password, opts.Host, opts.Name, concate)
  65. }
  66. case "postgres":
  67. host, port := parsePostgreSQLHostPort(opts.Host)
  68. if host[0] == '/' { // looks like a unix socket
  69. dsn = fmt.Sprintf("postgres://%s:%s@:%s/%s%ssslmode=%s&host=%s",
  70. url.QueryEscape(opts.User), url.QueryEscape(opts.Password), port, opts.Name, concate, opts.SSLMode, host)
  71. } else {
  72. dsn = fmt.Sprintf("postgres://%s:%s@%s:%s/%s%ssslmode=%s",
  73. url.QueryEscape(opts.User), url.QueryEscape(opts.Password), host, port, opts.Name, concate, opts.SSLMode)
  74. }
  75. case "mssql":
  76. host, port := parseMSSQLHostPort(opts.Host)
  77. dsn = fmt.Sprintf("server=%s; port=%s; database=%s; user id=%s; password=%s;",
  78. host, port, opts.Name, opts.User, opts.Password)
  79. case "sqlite3":
  80. dsn = "file:" + opts.Path + "?cache=shared&mode=rwc"
  81. default:
  82. return "", errors.Errorf("unrecognized dialect: %s", opts.Type)
  83. }
  84. return dsn, nil
  85. }
  86. func newLogWriter() (logger.Writer, error) {
  87. sec := conf.File.Section("log.gorm")
  88. w, err := log.NewFileWriter(
  89. filepath.Join(conf.Log.RootPath, "gorm.log"),
  90. log.FileRotationConfig{
  91. Rotate: sec.Key("ROTATE").MustBool(true),
  92. Daily: sec.Key("ROTATE_DAILY").MustBool(true),
  93. MaxSize: sec.Key("MAX_SIZE").MustInt64(100) * 1024 * 1024,
  94. MaxDays: sec.Key("MAX_DAYS").MustInt64(3),
  95. },
  96. )
  97. if err != nil {
  98. return nil, errors.Wrap(err, `create "gorm.log"`)
  99. }
  100. return &dbutil.Logger{Writer: w}, nil
  101. }
  102. func openDB(opts conf.DatabaseOpts, cfg *gorm.Config) (*gorm.DB, error) {
  103. dsn, err := parseDSN(opts)
  104. if err != nil {
  105. return nil, errors.Wrap(err, "parse DSN")
  106. }
  107. var dialector gorm.Dialector
  108. switch opts.Type {
  109. case "mysql":
  110. dialector = mysql.Open(dsn)
  111. case "postgres":
  112. dialector = postgres.Open(dsn)
  113. case "mssql":
  114. dialector = sqlserver.Open(dsn)
  115. case "sqlite3":
  116. dialector = sqlite.Open(dsn)
  117. default:
  118. panic("unreachable")
  119. }
  120. return gorm.Open(dialector, cfg)
  121. }
  122. // Tables is the list of struct-to-table mappings.
  123. //
  124. // NOTE: Lines are sorted in alphabetical order, each letter in its own line.
  125. var Tables = []interface{}{
  126. new(Access), new(AccessToken),
  127. new(LFSObject), new(LoginSource),
  128. }
  129. func Init(w logger.Writer) (*gorm.DB, error) {
  130. level := logger.Info
  131. if conf.IsProdMode() {
  132. level = logger.Warn
  133. }
  134. // NOTE: AutoMigrate does not respect logger passed in gorm.Config.
  135. logger.Default = logger.New(w, logger.Config{
  136. SlowThreshold: 100 * time.Millisecond,
  137. LogLevel: level,
  138. })
  139. db, err := openDB(conf.Database, &gorm.Config{
  140. NamingStrategy: schema.NamingStrategy{
  141. SingularTable: true,
  142. },
  143. NowFunc: func() time.Time {
  144. return time.Now().UTC().Truncate(time.Microsecond)
  145. },
  146. })
  147. if err != nil {
  148. return nil, errors.Wrap(err, "open database")
  149. }
  150. sqlDB, err := db.DB()
  151. if err != nil {
  152. return nil, errors.Wrap(err, "get underlying *sql.DB")
  153. }
  154. sqlDB.SetMaxOpenConns(conf.Database.MaxOpenConns)
  155. sqlDB.SetMaxIdleConns(conf.Database.MaxIdleConns)
  156. sqlDB.SetConnMaxLifetime(time.Minute)
  157. switch conf.Database.Type {
  158. case "postgres":
  159. conf.UsePostgreSQL = true
  160. case "mysql":
  161. conf.UseMySQL = true
  162. db = db.Set("gorm:table_options", "ENGINE=InnoDB").Session(&gorm.Session{})
  163. case "sqlite3":
  164. conf.UseSQLite3 = true
  165. case "mssql":
  166. conf.UseMSSQL = true
  167. default:
  168. panic("unreachable")
  169. }
  170. // NOTE: GORM has problem detecting existing columns, see https://github.com/gogs/gogs/issues/6091.
  171. // Therefore only use it to create new tables, and do customized migration with future changes.
  172. for _, table := range Tables {
  173. if db.Migrator().HasTable(table) {
  174. continue
  175. }
  176. name := strings.TrimPrefix(fmt.Sprintf("%T", table), "*db.")
  177. err = db.Migrator().AutoMigrate(table)
  178. if err != nil {
  179. return nil, errors.Wrapf(err, "auto migrate %q", name)
  180. }
  181. log.Trace("Auto migrated %q", name)
  182. }
  183. sourceFiles, err := loadLoginSourceFiles(filepath.Join(conf.CustomDir(), "conf", "auth.d"), db.NowFunc)
  184. if err != nil {
  185. return nil, errors.Wrap(err, "load login source files")
  186. }
  187. // Initialize stores, sorted in alphabetical order.
  188. AccessTokens = &accessTokens{DB: db}
  189. LoginSources = &loginSources{DB: db, files: sourceFiles}
  190. LFS = &lfs{DB: db}
  191. Perms = &perms{DB: db}
  192. Repos = &repos{DB: db}
  193. TwoFactors = &twoFactors{DB: db}
  194. Users = &users{DB: db}
  195. return db, nil
  196. }