models.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  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. "github.com/jinzhu/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. connStr := ""
  62. switch conf.Database.Type {
  63. case "mysql":
  64. conf.UseMySQL = true
  65. if conf.Database.Host[0] == '/' { // looks like a unix socket
  66. connStr = fmt.Sprintf("%s:%s@unix(%s)/%s%scharset=utf8mb4&parseTime=true",
  67. conf.Database.User, conf.Database.Password, conf.Database.Host, conf.Database.Name, Param)
  68. } else {
  69. connStr = fmt.Sprintf("%s:%s@tcp(%s)/%s%scharset=utf8mb4&parseTime=true",
  70. conf.Database.User, conf.Database.Password, conf.Database.Host, conf.Database.Name, Param)
  71. }
  72. var engineParams = map[string]string{"rowFormat": "DYNAMIC"}
  73. return xorm.NewEngineWithParams(conf.Database.Type, connStr, engineParams)
  74. case "postgres":
  75. conf.UsePostgreSQL = true
  76. host, port := parsePostgreSQLHostPort(conf.Database.Host)
  77. if host[0] == '/' { // looks like a unix socket
  78. connStr = fmt.Sprintf("postgres://%s:%s@:%s/%s%ssslmode=%s&host=%s",
  79. url.QueryEscape(conf.Database.User), url.QueryEscape(conf.Database.Password), port, conf.Database.Name, Param, conf.Database.SSLMode, host)
  80. } else {
  81. connStr = fmt.Sprintf("postgres://%s:%s@%s:%s/%s%ssslmode=%s",
  82. url.QueryEscape(conf.Database.User), url.QueryEscape(conf.Database.Password), host, port, conf.Database.Name, Param, conf.Database.SSLMode)
  83. }
  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(conf.Database.Type, 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. x.SetMapper(core.GonicMapper{})
  105. return x.StoreEngine("InnoDB").Sync2(legacyTables...)
  106. }
  107. func SetEngine() (*gorm.DB, error) {
  108. var err error
  109. x, err = getEngine()
  110. if err != nil {
  111. return nil, fmt.Errorf("connect to database: %v", err)
  112. }
  113. x.SetMapper(core.GonicMapper{})
  114. // WARNING: for serv command, MUST remove the output to os.stdout,
  115. // so use log file to instead print to stdout.
  116. sec := conf.File.Section("log.xorm")
  117. logger, err := log.NewFileWriter(path.Join(conf.Log.RootPath, "xorm.log"),
  118. log.FileRotationConfig{
  119. Rotate: sec.Key("ROTATE").MustBool(true),
  120. Daily: sec.Key("ROTATE_DAILY").MustBool(true),
  121. MaxSize: sec.Key("MAX_SIZE").MustInt64(100) * 1024 * 1024,
  122. MaxDays: sec.Key("MAX_DAYS").MustInt64(3),
  123. })
  124. if err != nil {
  125. return nil, fmt.Errorf("create 'xorm.log': %v", err)
  126. }
  127. x.SetMaxOpenConns(conf.Database.MaxOpenConns)
  128. x.SetMaxIdleConns(conf.Database.MaxIdleConns)
  129. x.SetConnMaxLifetime(time.Second)
  130. if conf.IsProdMode() {
  131. x.SetLogger(xorm.NewSimpleLogger3(logger, xorm.DEFAULT_LOG_PREFIX, xorm.DEFAULT_LOG_FLAG, core.LOG_WARNING))
  132. } else {
  133. x.SetLogger(xorm.NewSimpleLogger(logger))
  134. }
  135. x.ShowSQL(true)
  136. return Init()
  137. }
  138. func NewEngine() (err error) {
  139. if _, err = SetEngine(); err != nil {
  140. return err
  141. }
  142. if err = migrations.Migrate(x); err != nil {
  143. return fmt.Errorf("migrate: %v", err)
  144. }
  145. if err = x.StoreEngine("InnoDB").Sync2(legacyTables...); err != nil {
  146. return fmt.Errorf("sync structs to database tables: %v\n", err)
  147. }
  148. return nil
  149. }
  150. type Statistic struct {
  151. Counter struct {
  152. User, Org, PublicKey,
  153. Repo, Watch, Star, Action, Access,
  154. Issue, Comment, Oauth, Follow,
  155. Mirror, Release, LoginSource, Webhook,
  156. Milestone, Label, HookTask,
  157. Team, UpdateTask, Attachment int64
  158. }
  159. }
  160. func GetStatistic() (stats Statistic) {
  161. stats.Counter.User = CountUsers()
  162. stats.Counter.Org = CountOrganizations()
  163. stats.Counter.PublicKey, _ = x.Count(new(PublicKey))
  164. stats.Counter.Repo = CountRepositories(true)
  165. stats.Counter.Watch, _ = x.Count(new(Watch))
  166. stats.Counter.Star, _ = x.Count(new(Star))
  167. stats.Counter.Action, _ = x.Count(new(Action))
  168. stats.Counter.Access, _ = x.Count(new(Access))
  169. stats.Counter.Issue, _ = x.Count(new(Issue))
  170. stats.Counter.Comment, _ = x.Count(new(Comment))
  171. stats.Counter.Oauth = 0
  172. stats.Counter.Follow, _ = x.Count(new(Follow))
  173. stats.Counter.Mirror, _ = x.Count(new(Mirror))
  174. stats.Counter.Release, _ = x.Count(new(Release))
  175. stats.Counter.LoginSource = LoginSources.Count()
  176. stats.Counter.Webhook, _ = x.Count(new(Webhook))
  177. stats.Counter.Milestone, _ = x.Count(new(Milestone))
  178. stats.Counter.Label, _ = x.Count(new(Label))
  179. stats.Counter.HookTask, _ = x.Count(new(HookTask))
  180. stats.Counter.Team, _ = x.Count(new(Team))
  181. stats.Counter.Attachment, _ = x.Count(new(Attachment))
  182. return
  183. }
  184. func Ping() error {
  185. return x.Ping()
  186. }
  187. // The version table. Should have only one row with id==1
  188. type Version struct {
  189. ID int64
  190. Version int64
  191. }