models.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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 database
  5. import (
  6. "context"
  7. "database/sql"
  8. "fmt"
  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/database/migrations"
  22. "gogs.io/gogs/internal/dbutil"
  23. )
  24. // Engine represents a XORM engine or session.
  25. type Engine interface {
  26. Delete(any) (int64, error)
  27. Exec(...any) (sql.Result, error)
  28. Find(any, ...any) error
  29. Get(any) (bool, error)
  30. ID(any) *xorm.Session
  31. In(string, ...any) *xorm.Session
  32. Insert(...any) (int64, error)
  33. InsertOne(any) (int64, error)
  34. Iterate(any, xorm.IterFunc) error
  35. Sql(string, ...any) *xorm.Session
  36. Table(any) *xorm.Session
  37. Where(any, ...any) *xorm.Session
  38. }
  39. var (
  40. x *xorm.Engine
  41. legacyTables []any
  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),
  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. )
  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. 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 := dbutil.ParsePostgreSQLHostPort(conf.Database.Host)
  82. connStr = fmt.Sprintf("user='%s' password='%s' host='%s' port='%s' dbname='%s' sslmode='%s' search_path='%s'",
  83. conf.Database.User, conf.Database.Password, host, port, conf.Database.Name, conf.Database.SSLMode, conf.Database.Schema)
  84. driver = "pgx"
  85. case "mssql":
  86. conf.UseMSSQL = true
  87. host, port := dbutil.ParseMSSQLHostPort(conf.Database.Host)
  88. 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)
  89. case "sqlite3":
  90. if err := os.MkdirAll(path.Dir(conf.Database.Path), os.ModePerm); err != nil {
  91. return nil, fmt.Errorf("create directories: %v", err)
  92. }
  93. conf.UseSQLite3 = true
  94. connStr = "file:" + conf.Database.Path + "?cache=shared&mode=rwc"
  95. default:
  96. return nil, fmt.Errorf("unknown database type: %s", conf.Database.Type)
  97. }
  98. return xorm.NewEngine(driver, connStr)
  99. }
  100. func NewTestEngine() error {
  101. x, err := getEngine()
  102. if err != nil {
  103. return fmt.Errorf("connect to database: %v", err)
  104. }
  105. if conf.UsePostgreSQL {
  106. x.SetSchema(conf.Database.Schema)
  107. }
  108. x.SetMapper(core.GonicMapper{})
  109. return x.StoreEngine("InnoDB").Sync2(legacyTables...)
  110. }
  111. func SetEngine() (*gorm.DB, error) {
  112. var err error
  113. x, err = getEngine()
  114. if err != nil {
  115. return nil, fmt.Errorf("connect to database: %v", err)
  116. }
  117. if conf.UsePostgreSQL {
  118. x.SetSchema(conf.Database.Schema)
  119. }
  120. x.SetMapper(core.GonicMapper{})
  121. var logPath string
  122. if conf.HookMode {
  123. logPath = filepath.Join(conf.Log.RootPath, "hooks", "xorm.log")
  124. } else {
  125. logPath = filepath.Join(conf.Log.RootPath, "xorm.log")
  126. }
  127. sec := conf.File.Section("log.xorm")
  128. fileWriter, err := log.NewFileWriter(logPath,
  129. log.FileRotationConfig{
  130. Rotate: sec.Key("ROTATE").MustBool(true),
  131. Daily: sec.Key("ROTATE_DAILY").MustBool(true),
  132. MaxSize: sec.Key("MAX_SIZE").MustInt64(100) * 1024 * 1024,
  133. MaxDays: sec.Key("MAX_DAYS").MustInt64(3),
  134. },
  135. )
  136. if err != nil {
  137. return nil, fmt.Errorf("create 'xorm.log': %v", err)
  138. }
  139. x.SetMaxOpenConns(conf.Database.MaxOpenConns)
  140. x.SetMaxIdleConns(conf.Database.MaxIdleConns)
  141. x.SetConnMaxLifetime(time.Second)
  142. if conf.IsProdMode() {
  143. x.SetLogger(xorm.NewSimpleLogger3(fileWriter, xorm.DEFAULT_LOG_PREFIX, xorm.DEFAULT_LOG_FLAG, core.LOG_ERR))
  144. } else {
  145. x.SetLogger(xorm.NewSimpleLogger(fileWriter))
  146. }
  147. x.ShowSQL(true)
  148. var gormLogger logger.Writer
  149. if conf.HookMode {
  150. gormLogger = &dbutil.Logger{Writer: fileWriter}
  151. } else {
  152. gormLogger, err = newLogWriter()
  153. if err != nil {
  154. return nil, errors.Wrap(err, "new log writer")
  155. }
  156. }
  157. return NewConnection(gormLogger)
  158. }
  159. func NewEngine() error {
  160. db, err := SetEngine()
  161. if err != nil {
  162. return err
  163. }
  164. if err = migrations.Migrate(db); err != nil {
  165. return fmt.Errorf("migrate: %v", err)
  166. }
  167. if err = x.StoreEngine("InnoDB").Sync2(legacyTables...); err != nil {
  168. return errors.Wrap(err, "sync tables")
  169. }
  170. return nil
  171. }
  172. type Statistic struct {
  173. Counter struct {
  174. User, Org, PublicKey,
  175. Repo, Watch, Star, Action, Access,
  176. Issue, Comment, Oauth, Follow,
  177. Mirror, Release, LoginSource, Webhook,
  178. Milestone, Label, HookTask,
  179. Team, UpdateTask, Attachment int64
  180. }
  181. }
  182. func GetStatistic(ctx context.Context) (stats Statistic) {
  183. stats.Counter.User = Handle.Users().Count(ctx)
  184. stats.Counter.Org = CountOrganizations()
  185. stats.Counter.PublicKey, _ = x.Count(new(PublicKey))
  186. stats.Counter.Repo = CountRepositories(true)
  187. stats.Counter.Watch, _ = x.Count(new(Watch))
  188. stats.Counter.Star, _ = x.Count(new(Star))
  189. stats.Counter.Action, _ = x.Count(new(Action))
  190. stats.Counter.Access, _ = x.Count(new(Access))
  191. stats.Counter.Issue, _ = x.Count(new(Issue))
  192. stats.Counter.Comment, _ = x.Count(new(Comment))
  193. stats.Counter.Oauth = 0
  194. stats.Counter.Follow, _ = x.Count(new(Follow))
  195. stats.Counter.Mirror, _ = x.Count(new(Mirror))
  196. stats.Counter.Release, _ = x.Count(new(Release))
  197. stats.Counter.LoginSource = Handle.LoginSources().Count(ctx)
  198. stats.Counter.Webhook, _ = x.Count(new(Webhook))
  199. stats.Counter.Milestone, _ = x.Count(new(Milestone))
  200. stats.Counter.Label, _ = x.Count(new(Label))
  201. stats.Counter.HookTask, _ = x.Count(new(HookTask))
  202. stats.Counter.Team, _ = x.Count(new(Team))
  203. stats.Counter.Attachment, _ = x.Count(new(Attachment))
  204. return stats
  205. }
  206. func Ping() error {
  207. if x == nil {
  208. return errors.New("database not available")
  209. }
  210. return x.Ping()
  211. }
  212. // The version table. Should have only one row with id==1
  213. type Version struct {
  214. ID int64
  215. Version int64
  216. }