models.go 6.7 KB

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