models.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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. "io"
  9. "net/url"
  10. "os"
  11. "path"
  12. "path/filepath"
  13. "strings"
  14. "time"
  15. "github.com/jinzhu/gorm"
  16. "github.com/pkg/errors"
  17. log "unknwon.dev/clog/v2"
  18. "xorm.io/core"
  19. "xorm.io/xorm"
  20. "gogs.io/gogs/internal/conf"
  21. "gogs.io/gogs/internal/db/migrations"
  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(Access), 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. connStr := ""
  65. switch conf.Database.Type {
  66. case "mysql":
  67. conf.UseMySQL = true
  68. if conf.Database.Host[0] == '/' { // looks like a unix socket
  69. connStr = fmt.Sprintf("%s:%s@unix(%s)/%s%scharset=utf8mb4&parseTime=true",
  70. conf.Database.User, conf.Database.Password, conf.Database.Host, conf.Database.Name, Param)
  71. } else {
  72. connStr = fmt.Sprintf("%s:%s@tcp(%s)/%s%scharset=utf8mb4&parseTime=true",
  73. conf.Database.User, conf.Database.Password, conf.Database.Host, conf.Database.Name, Param)
  74. }
  75. var engineParams = map[string]string{"rowFormat": "DYNAMIC"}
  76. return xorm.NewEngineWithParams(conf.Database.Type, connStr, engineParams)
  77. case "postgres":
  78. conf.UsePostgreSQL = true
  79. host, port := parsePostgreSQLHostPort(conf.Database.Host)
  80. if host[0] == '/' { // looks like a unix socket
  81. connStr = fmt.Sprintf("postgres://%s:%s@:%s/%s%ssslmode=%s&host=%s",
  82. url.QueryEscape(conf.Database.User), url.QueryEscape(conf.Database.Password), port, conf.Database.Name, Param, conf.Database.SSLMode, host)
  83. } else {
  84. connStr = fmt.Sprintf("postgres://%s:%s@%s:%s/%s%ssslmode=%s",
  85. url.QueryEscape(conf.Database.User), url.QueryEscape(conf.Database.Password), host, port, conf.Database.Name, Param, conf.Database.SSLMode)
  86. }
  87. case "mssql":
  88. conf.UseMSSQL = true
  89. host, port := parseMSSQLHostPort(conf.Database.Host)
  90. 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)
  91. case "sqlite3":
  92. if err := os.MkdirAll(path.Dir(conf.Database.Path), os.ModePerm); err != nil {
  93. return nil, fmt.Errorf("create directories: %v", err)
  94. }
  95. conf.UseSQLite3 = true
  96. connStr = "file:" + conf.Database.Path + "?cache=shared&mode=rwc"
  97. default:
  98. return nil, fmt.Errorf("unknown database type: %s", conf.Database.Type)
  99. }
  100. return xorm.NewEngine(conf.Database.Type, connStr)
  101. }
  102. func NewTestEngine() error {
  103. x, err := getEngine()
  104. if err != nil {
  105. return fmt.Errorf("connect to database: %v", err)
  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. x.SetMapper(core.GonicMapper{})
  117. var logPath string
  118. if conf.HookMode {
  119. logPath = filepath.Join(conf.Log.RootPath, "hooks", "xorm.log")
  120. } else {
  121. logPath = filepath.Join(conf.Log.RootPath, "xorm.log")
  122. }
  123. sec := conf.File.Section("log.xorm")
  124. fileWriter, err := log.NewFileWriter(logPath,
  125. log.FileRotationConfig{
  126. Rotate: sec.Key("ROTATE").MustBool(true),
  127. Daily: sec.Key("ROTATE_DAILY").MustBool(true),
  128. MaxSize: sec.Key("MAX_SIZE").MustInt64(100) * 1024 * 1024,
  129. MaxDays: sec.Key("MAX_DAYS").MustInt64(3),
  130. },
  131. )
  132. if err != nil {
  133. return nil, fmt.Errorf("create 'xorm.log': %v", err)
  134. }
  135. x.SetMaxOpenConns(conf.Database.MaxOpenConns)
  136. x.SetMaxIdleConns(conf.Database.MaxIdleConns)
  137. x.SetConnMaxLifetime(time.Second)
  138. if conf.IsProdMode() {
  139. x.SetLogger(xorm.NewSimpleLogger3(fileWriter, xorm.DEFAULT_LOG_PREFIX, xorm.DEFAULT_LOG_FLAG, core.LOG_WARNING))
  140. } else {
  141. x.SetLogger(xorm.NewSimpleLogger(fileWriter))
  142. }
  143. x.ShowSQL(true)
  144. var w io.Writer
  145. if conf.HookMode {
  146. w = fileWriter
  147. } else {
  148. w, err = getLogWriter()
  149. if err != nil {
  150. return nil, errors.Wrap(err, "get log writer")
  151. }
  152. }
  153. return Init(w)
  154. }
  155. func NewEngine() (err error) {
  156. if _, err = SetEngine(); err != nil {
  157. return err
  158. }
  159. if err = migrations.Migrate(x); err != nil {
  160. return fmt.Errorf("migrate: %v", err)
  161. }
  162. if err = x.StoreEngine("InnoDB").Sync2(legacyTables...); err != nil {
  163. return fmt.Errorf("sync structs to database tables: %v\n", err)
  164. }
  165. return nil
  166. }
  167. type Statistic struct {
  168. Counter struct {
  169. User, Org, PublicKey,
  170. Repo, Watch, Star, Action, Access,
  171. Issue, Comment, Oauth, Follow,
  172. Mirror, Release, LoginSource, Webhook,
  173. Milestone, Label, HookTask,
  174. Team, UpdateTask, Attachment int64
  175. }
  176. }
  177. func GetStatistic() (stats Statistic) {
  178. stats.Counter.User = CountUsers()
  179. stats.Counter.Org = CountOrganizations()
  180. stats.Counter.PublicKey, _ = x.Count(new(PublicKey))
  181. stats.Counter.Repo = CountRepositories(true)
  182. stats.Counter.Watch, _ = x.Count(new(Watch))
  183. stats.Counter.Star, _ = x.Count(new(Star))
  184. stats.Counter.Action, _ = x.Count(new(Action))
  185. stats.Counter.Access, _ = x.Count(new(Access))
  186. stats.Counter.Issue, _ = x.Count(new(Issue))
  187. stats.Counter.Comment, _ = x.Count(new(Comment))
  188. stats.Counter.Oauth = 0
  189. stats.Counter.Follow, _ = x.Count(new(Follow))
  190. stats.Counter.Mirror, _ = x.Count(new(Mirror))
  191. stats.Counter.Release, _ = x.Count(new(Release))
  192. stats.Counter.LoginSource = LoginSources.Count()
  193. stats.Counter.Webhook, _ = x.Count(new(Webhook))
  194. stats.Counter.Milestone, _ = x.Count(new(Milestone))
  195. stats.Counter.Label, _ = x.Count(new(Label))
  196. stats.Counter.HookTask, _ = x.Count(new(HookTask))
  197. stats.Counter.Team, _ = x.Count(new(Team))
  198. stats.Counter.Attachment, _ = x.Count(new(Attachment))
  199. return
  200. }
  201. func Ping() error {
  202. return x.Ping()
  203. }
  204. // The version table. Should have only one row with id==1
  205. type Version struct {
  206. ID int64
  207. Version int64
  208. }