db.go 5.5 KB

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