models.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. // Copyright 2014 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. "database/sql"
  7. "fmt"
  8. "os"
  9. "path"
  10. "path/filepath"
  11. "strings"
  12. "time"
  13. "github.com/pkg/errors"
  14. "gorm.io/gorm"
  15. "gorm.io/gorm/logger"
  16. log "unknwon.dev/clog/v2"
  17. "xorm.io/core"
  18. "xorm.io/xorm"
  19. "gogs.io/gogs/internal/conf"
  20. "gogs.io/gogs/internal/db/migrations"
  21. "gogs.io/gogs/internal/dbutil"
  22. )
  23. // Engine represents a XORM engine or session.
  24. type Engine interface {
  25. Delete(interface{}) (int64, error)
  26. Exec(...interface{}) (sql.Result, error)
  27. Find(interface{}, ...interface{}) error
  28. Get(interface{}) (bool, error)
  29. ID(interface{}) *xorm.Session
  30. In(string, ...interface{}) *xorm.Session
  31. Insert(...interface{}) (int64, error)
  32. InsertOne(interface{}) (int64, error)
  33. Iterate(interface{}, xorm.IterFunc) error
  34. Sql(string, ...interface{}) *xorm.Session
  35. Table(interface{}) *xorm.Session
  36. Where(interface{}, ...interface{}) *xorm.Session
  37. }
  38. var (
  39. x *xorm.Engine
  40. legacyTables []interface{}
  41. HasEngine bool
  42. )
  43. func init() {
  44. legacyTables = append(legacyTables,
  45. new(User), new(PublicKey), new(TwoFactor), new(TwoFactorRecoveryCode),
  46. new(Repository), new(DeployKey), new(Collaboration), new(Upload),
  47. new(Watch), new(Star), new(Follow), new(Action),
  48. new(Issue), new(PullRequest), new(Comment), new(Attachment), new(IssueUser),
  49. new(Label), new(IssueLabel), new(Milestone),
  50. new(Mirror), new(Release), new(Webhook), new(HookTask),
  51. new(ProtectBranch), new(ProtectBranchWhitelist),
  52. new(Team), new(OrgUser), new(TeamUser), new(TeamRepo),
  53. new(Notice), new(EmailAddress))
  54. gonicNames := []string{"SSL"}
  55. for _, name := range gonicNames {
  56. core.LintGonicMapper[name] = true
  57. }
  58. }
  59. func getEngine() (*xorm.Engine, error) {
  60. Param := "?"
  61. if strings.Contains(conf.Database.Name, Param) {
  62. Param = "&"
  63. }
  64. driver := conf.Database.Type
  65. connStr := ""
  66. switch conf.Database.Type {
  67. case "mysql":
  68. conf.UseMySQL = true
  69. if conf.Database.Host[0] == '/' { // looks like a unix socket
  70. connStr = fmt.Sprintf("%s:%s@unix(%s)/%s%scharset=utf8mb4&parseTime=true",
  71. conf.Database.User, conf.Database.Password, conf.Database.Host, conf.Database.Name, Param)
  72. } else {
  73. connStr = fmt.Sprintf("%s:%s@tcp(%s)/%s%scharset=utf8mb4&parseTime=true",
  74. conf.Database.User, conf.Database.Password, conf.Database.Host, conf.Database.Name, Param)
  75. }
  76. var engineParams = map[string]string{"rowFormat": "DYNAMIC"}
  77. return xorm.NewEngineWithParams(conf.Database.Type, connStr, engineParams)
  78. case "postgres":
  79. conf.UsePostgreSQL = true
  80. host, port := parsePostgreSQLHostPort(conf.Database.Host)
  81. connStr = fmt.Sprintf("user='%s' password='%s' host='%s' port='%s' dbname='%s' sslmode='%s' search_path='%s'",
  82. conf.Database.User, conf.Database.Password, host, port, conf.Database.Name, conf.Database.SSLMode, conf.Database.Schema)
  83. driver = "pgx"
  84. case "mssql":
  85. conf.UseMSSQL = true
  86. host, port := parseMSSQLHostPort(conf.Database.Host)
  87. connStr = fmt.Sprintf("server=%s; port=%s; database=%s; user id=%s; password=%s;", host, port, conf.Database.Name, conf.Database.User, conf.Database.Password)
  88. case "sqlite3":
  89. if err := os.MkdirAll(path.Dir(conf.Database.Path), os.ModePerm); err != nil {
  90. return nil, fmt.Errorf("create directories: %v", err)
  91. }
  92. conf.UseSQLite3 = true
  93. connStr = "file:" + conf.Database.Path + "?cache=shared&mode=rwc"
  94. default:
  95. return nil, fmt.Errorf("unknown database type: %s", conf.Database.Type)
  96. }
  97. return xorm.NewEngine(driver, connStr)
  98. }
  99. func NewTestEngine() error {
  100. x, err := getEngine()
  101. if err != nil {
  102. return fmt.Errorf("connect to database: %v", err)
  103. }
  104. if conf.UsePostgreSQL {
  105. x.SetSchema(conf.Database.Schema)
  106. }
  107. x.SetMapper(core.GonicMapper{})
  108. return x.StoreEngine("InnoDB").Sync2(legacyTables...)
  109. }
  110. func SetEngine() (*gorm.DB, error) {
  111. var err error
  112. x, err = getEngine()
  113. if err != nil {
  114. return nil, fmt.Errorf("connect to database: %v", err)
  115. }
  116. if conf.UsePostgreSQL {
  117. x.SetSchema(conf.Database.Schema)
  118. }
  119. x.SetMapper(core.GonicMapper{})
  120. var logPath string
  121. if conf.HookMode {
  122. logPath = filepath.Join(conf.Log.RootPath, "hooks", "xorm.log")
  123. } else {
  124. logPath = filepath.Join(conf.Log.RootPath, "xorm.log")
  125. }
  126. sec := conf.File.Section("log.xorm")
  127. fileWriter, err := log.NewFileWriter(logPath,
  128. log.FileRotationConfig{
  129. Rotate: sec.Key("ROTATE").MustBool(true),
  130. Daily: sec.Key("ROTATE_DAILY").MustBool(true),
  131. MaxSize: sec.Key("MAX_SIZE").MustInt64(100) * 1024 * 1024,
  132. MaxDays: sec.Key("MAX_DAYS").MustInt64(3),
  133. },
  134. )
  135. if err != nil {
  136. return nil, fmt.Errorf("create 'xorm.log': %v", err)
  137. }
  138. x.SetMaxOpenConns(conf.Database.MaxOpenConns)
  139. x.SetMaxIdleConns(conf.Database.MaxIdleConns)
  140. x.SetConnMaxLifetime(time.Second)
  141. if conf.IsProdMode() {
  142. x.SetLogger(xorm.NewSimpleLogger3(fileWriter, xorm.DEFAULT_LOG_PREFIX, xorm.DEFAULT_LOG_FLAG, core.LOG_WARNING))
  143. } else {
  144. x.SetLogger(xorm.NewSimpleLogger(fileWriter))
  145. }
  146. x.ShowSQL(true)
  147. var gormLogger logger.Writer
  148. if conf.HookMode {
  149. gormLogger = &dbutil.Logger{Writer: fileWriter}
  150. } else {
  151. gormLogger, err = newLogWriter()
  152. if err != nil {
  153. return nil, errors.Wrap(err, "new log writer")
  154. }
  155. }
  156. return Init(gormLogger)
  157. }
  158. func NewEngine() (err error) {
  159. if _, err = SetEngine(); err != nil {
  160. return err
  161. }
  162. if err = migrations.Migrate(x); err != nil {
  163. return fmt.Errorf("migrate: %v", err)
  164. }
  165. if err = x.StoreEngine("InnoDB").Sync2(legacyTables...); err != nil {
  166. return fmt.Errorf("sync structs to database tables: %v\n", err)
  167. }
  168. return nil
  169. }
  170. type Statistic struct {
  171. Counter struct {
  172. User, Org, PublicKey,
  173. Repo, Watch, Star, Action, Access,
  174. Issue, Comment, Oauth, Follow,
  175. Mirror, Release, LoginSource, Webhook,
  176. Milestone, Label, HookTask,
  177. Team, UpdateTask, Attachment int64
  178. }
  179. }
  180. func GetStatistic() (stats Statistic) {
  181. stats.Counter.User = CountUsers()
  182. stats.Counter.Org = CountOrganizations()
  183. stats.Counter.PublicKey, _ = x.Count(new(PublicKey))
  184. stats.Counter.Repo = CountRepositories(true)
  185. stats.Counter.Watch, _ = x.Count(new(Watch))
  186. stats.Counter.Star, _ = x.Count(new(Star))
  187. stats.Counter.Action, _ = x.Count(new(Action))
  188. stats.Counter.Access, _ = x.Count(new(Access))
  189. stats.Counter.Issue, _ = x.Count(new(Issue))
  190. stats.Counter.Comment, _ = x.Count(new(Comment))
  191. stats.Counter.Oauth = 0
  192. stats.Counter.Follow, _ = x.Count(new(Follow))
  193. stats.Counter.Mirror, _ = x.Count(new(Mirror))
  194. stats.Counter.Release, _ = x.Count(new(Release))
  195. stats.Counter.LoginSource = LoginSources.Count()
  196. stats.Counter.Webhook, _ = x.Count(new(Webhook))
  197. stats.Counter.Milestone, _ = x.Count(new(Milestone))
  198. stats.Counter.Label, _ = x.Count(new(Label))
  199. stats.Counter.HookTask, _ = x.Count(new(HookTask))
  200. stats.Counter.Team, _ = x.Count(new(Team))
  201. stats.Counter.Attachment, _ = x.Count(new(Attachment))
  202. return stats
  203. }
  204. func Ping() error {
  205. if x == nil {
  206. return errors.New("database not available")
  207. }
  208. return x.Ping()
  209. }
  210. // The version table. Should have only one row with id==1
  211. type Version struct {
  212. ID int64
  213. Version int64
  214. }