models.go 6.7 KB

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