models.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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/cockroachdb/errors"
  12. "github.com/glebarez/go-sqlite"
  13. "gorm.io/gorm"
  14. "gorm.io/gorm/logger"
  15. log "unknwon.dev/clog/v2"
  16. "xorm.io/core"
  17. "xorm.io/xorm"
  18. "gogs.io/gogs/internal/conf"
  19. "gogs.io/gogs/internal/database/migrations"
  20. "gogs.io/gogs/internal/dbutil"
  21. )
  22. // Engine represents a XORM engine or session.
  23. type Engine interface {
  24. Delete(any) (int64, error)
  25. Exec(...any) (sql.Result, error)
  26. Find(any, ...any) error
  27. Get(any) (bool, error)
  28. ID(any) *xorm.Session
  29. In(string, ...any) *xorm.Session
  30. Insert(...any) (int64, error)
  31. InsertOne(any) (int64, error)
  32. Iterate(any, xorm.IterFunc) error
  33. Sql(string, ...any) *xorm.Session
  34. Table(any) *xorm.Session
  35. Where(any, ...any) *xorm.Session
  36. }
  37. var (
  38. x *xorm.Engine
  39. legacyTables []any
  40. HasEngine bool
  41. )
  42. func init() {
  43. // Register the pure-Go SQLite driver as "sqlite3" for XORM compatibility.
  44. sql.Register("sqlite3", &sqlite.Driver{})
  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 "sqlite3":
  86. if err := os.MkdirAll(path.Dir(conf.Database.Path), os.ModePerm); err != nil {
  87. return nil, errors.Newf("create directories: %v", err)
  88. }
  89. conf.UseSQLite3 = true
  90. connStr = "file:" + conf.Database.Path + "?cache=shared&mode=rwc"
  91. default:
  92. return nil, errors.Newf("unknown database type: %s", conf.Database.Type)
  93. }
  94. return xorm.NewEngine(driver, connStr)
  95. }
  96. func NewTestEngine() error {
  97. x, err := getEngine()
  98. if err != nil {
  99. return errors.Newf("connect to database: %v", err)
  100. }
  101. if conf.UsePostgreSQL {
  102. x.SetSchema(conf.Database.Schema)
  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, errors.Newf("connect to database: %v", err)
  112. }
  113. if conf.UsePostgreSQL {
  114. x.SetSchema(conf.Database.Schema)
  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, errors.Newf("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_ERR))
  140. } else {
  141. x.SetLogger(xorm.NewSimpleLogger(fileWriter))
  142. }
  143. x.ShowSQL(true)
  144. var gormLogger logger.Writer
  145. if conf.HookMode {
  146. gormLogger = &dbutil.Logger{Writer: fileWriter}
  147. } else {
  148. gormLogger, err = newLogWriter()
  149. if err != nil {
  150. return nil, errors.Wrap(err, "new log writer")
  151. }
  152. }
  153. return NewConnection(gormLogger)
  154. }
  155. func NewEngine() error {
  156. db, err := SetEngine()
  157. if err != nil {
  158. return err
  159. }
  160. if err = migrations.Migrate(db); err != nil {
  161. return errors.Newf("migrate: %v", err)
  162. }
  163. if err = x.StoreEngine("InnoDB").Sync2(legacyTables...); err != nil {
  164. return errors.Wrap(err, "sync tables")
  165. }
  166. return nil
  167. }
  168. type Statistic struct {
  169. Counter struct {
  170. User, Org, PublicKey,
  171. Repo, Watch, Star, Action, Access,
  172. Issue, Comment, Oauth, Follow,
  173. Mirror, Release, LoginSource, Webhook,
  174. Milestone, Label, HookTask,
  175. Team, UpdateTask, Attachment int64
  176. }
  177. }
  178. func GetStatistic(ctx context.Context) (stats Statistic) {
  179. stats.Counter.User = Handle.Users().Count(ctx)
  180. stats.Counter.Org = CountOrganizations()
  181. stats.Counter.PublicKey, _ = x.Count(new(PublicKey))
  182. stats.Counter.Repo = CountRepositories(true)
  183. stats.Counter.Watch, _ = x.Count(new(Watch))
  184. stats.Counter.Star, _ = x.Count(new(Star))
  185. stats.Counter.Action, _ = x.Count(new(Action))
  186. stats.Counter.Access, _ = x.Count(new(Access))
  187. stats.Counter.Issue, _ = x.Count(new(Issue))
  188. stats.Counter.Comment, _ = x.Count(new(Comment))
  189. stats.Counter.Oauth = 0
  190. stats.Counter.Follow, _ = x.Count(new(Follow))
  191. stats.Counter.Mirror, _ = x.Count(new(Mirror))
  192. stats.Counter.Release, _ = x.Count(new(Release))
  193. stats.Counter.LoginSource = Handle.LoginSources().Count(ctx)
  194. stats.Counter.Webhook, _ = x.Count(new(Webhook))
  195. stats.Counter.Milestone, _ = x.Count(new(Milestone))
  196. stats.Counter.Label, _ = x.Count(new(Label))
  197. stats.Counter.HookTask, _ = x.Count(new(HookTask))
  198. stats.Counter.Team, _ = x.Count(new(Team))
  199. stats.Counter.Attachment, _ = x.Count(new(Attachment))
  200. return stats
  201. }
  202. func Ping() error {
  203. if x == nil {
  204. return errors.New("database not available")
  205. }
  206. return x.Ping()
  207. }
  208. // The version table. Should have only one row with id==1
  209. type Version struct {
  210. ID int64
  211. Version int64
  212. }