models.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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. "path/filepath"
  12. "strings"
  13. "time"
  14. "github.com/pkg/errors"
  15. "gorm.io/gorm"
  16. "gorm.io/gorm/logger"
  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. "gogs.io/gogs/internal/dbutil"
  23. )
  24. // Engine represents a XORM engine or session.
  25. type Engine interface {
  26. Delete(interface{}) (int64, error)
  27. Exec(...interface{}) (sql.Result, error)
  28. Find(interface{}, ...interface{}) error
  29. Get(interface{}) (bool, error)
  30. ID(interface{}) *xorm.Session
  31. In(string, ...interface{}) *xorm.Session
  32. Insert(...interface{}) (int64, error)
  33. InsertOne(interface{}) (int64, error)
  34. Iterate(interface{}, xorm.IterFunc) error
  35. Sql(string, ...interface{}) *xorm.Session
  36. Table(interface{}) *xorm.Session
  37. Where(interface{}, ...interface{}) *xorm.Session
  38. }
  39. var (
  40. x *xorm.Engine
  41. legacyTables []interface{}
  42. HasEngine bool
  43. )
  44. func init() {
  45. legacyTables = append(legacyTables,
  46. new(User), new(PublicKey), new(TwoFactor), new(TwoFactorRecoveryCode),
  47. new(Repository), new(DeployKey), new(Collaboration), new(Upload),
  48. new(Watch), new(Star), new(Follow), new(Action),
  49. new(Issue), new(PullRequest), new(Comment), new(Attachment), new(IssueUser),
  50. new(Label), new(IssueLabel), new(Milestone),
  51. new(Mirror), new(Release), new(Webhook), new(HookTask),
  52. new(ProtectBranch), new(ProtectBranchWhitelist),
  53. new(Team), new(OrgUser), new(TeamUser), new(TeamRepo),
  54. new(Notice), new(EmailAddress))
  55. gonicNames := []string{"SSL"}
  56. for _, name := range gonicNames {
  57. core.LintGonicMapper[name] = true
  58. }
  59. }
  60. func getEngine() (*xorm.Engine, error) {
  61. Param := "?"
  62. if strings.Contains(conf.Database.Name, Param) {
  63. Param = "&"
  64. }
  65. driver := conf.Database.Type
  66. connStr := ""
  67. switch conf.Database.Type {
  68. case "mysql":
  69. conf.UseMySQL = true
  70. if conf.Database.Host[0] == '/' { // looks like a unix socket
  71. connStr = fmt.Sprintf("%s:%s@unix(%s)/%s%scharset=utf8mb4&parseTime=true",
  72. conf.Database.User, conf.Database.Password, conf.Database.Host, conf.Database.Name, Param)
  73. } else {
  74. connStr = fmt.Sprintf("%s:%s@tcp(%s)/%s%scharset=utf8mb4&parseTime=true",
  75. conf.Database.User, conf.Database.Password, conf.Database.Host, conf.Database.Name, Param)
  76. }
  77. var engineParams = map[string]string{"rowFormat": "DYNAMIC"}
  78. return xorm.NewEngineWithParams(conf.Database.Type, connStr, engineParams)
  79. case "postgres":
  80. conf.UsePostgreSQL = true
  81. host, port := parsePostgreSQLHostPort(conf.Database.Host)
  82. if host[0] == '/' { // looks like a unix socket
  83. connStr = fmt.Sprintf("postgres://%s:%s@:%s/%s%ssslmode=%s&host=%s",
  84. url.QueryEscape(conf.Database.User), url.QueryEscape(conf.Database.Password), port, conf.Database.Name, Param, conf.Database.SSLMode, host)
  85. } else {
  86. connStr = fmt.Sprintf("postgres://%s:%s@%s:%s/%s%ssslmode=%s",
  87. url.QueryEscape(conf.Database.User), url.QueryEscape(conf.Database.Password), host, port, conf.Database.Name, Param, conf.Database.SSLMode)
  88. }
  89. driver = "pgx"
  90. case "mssql":
  91. conf.UseMSSQL = true
  92. host, port := parseMSSQLHostPort(conf.Database.Host)
  93. 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)
  94. case "sqlite3":
  95. if err := os.MkdirAll(path.Dir(conf.Database.Path), os.ModePerm); err != nil {
  96. return nil, fmt.Errorf("create directories: %v", err)
  97. }
  98. conf.UseSQLite3 = true
  99. connStr = "file:" + conf.Database.Path + "?cache=shared&mode=rwc"
  100. default:
  101. return nil, fmt.Errorf("unknown database type: %s", conf.Database.Type)
  102. }
  103. return xorm.NewEngine(driver, connStr)
  104. }
  105. func NewTestEngine() error {
  106. x, err := getEngine()
  107. if err != nil {
  108. return fmt.Errorf("connect to database: %v", err)
  109. }
  110. x.SetMapper(core.GonicMapper{})
  111. return x.StoreEngine("InnoDB").Sync2(legacyTables...)
  112. }
  113. func SetEngine() (*gorm.DB, error) {
  114. var err error
  115. x, err = getEngine()
  116. if err != nil {
  117. return nil, fmt.Errorf("connect to database: %v", err)
  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. return x.Ping()
  206. }
  207. // The version table. Should have only one row with id==1
  208. type Version struct {
  209. ID int64
  210. Version int64
  211. }