models.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  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 models
  5. import (
  6. "database/sql"
  7. "fmt"
  8. "os"
  9. "path"
  10. "strings"
  11. _ "github.com/go-sql-driver/mysql"
  12. "github.com/go-xorm/xorm"
  13. _ "github.com/lib/pq"
  14. "github.com/gogits/gogs/modules/setting"
  15. )
  16. // Engine represents a xorm engine or session.
  17. type Engine interface {
  18. Delete(interface{}) (int64, error)
  19. Exec(string, ...interface{}) (sql.Result, error)
  20. Insert(...interface{}) (int64, error)
  21. }
  22. var (
  23. x *xorm.Engine
  24. tables []interface{}
  25. HasEngine bool
  26. DbCfg struct {
  27. Type, Host, Name, User, Pwd, Path, SslMode string
  28. }
  29. EnableSQLite3 bool
  30. UseSQLite3 bool
  31. )
  32. func init() {
  33. tables = append(tables,
  34. new(User), new(PublicKey), new(Follow), new(Oauth2), new(AccessToken),
  35. new(Repository), new(Watch), new(Star), new(Action), new(Access),
  36. new(Issue), new(Comment), new(Attachment), new(IssueUser), new(Label), new(Milestone),
  37. new(Mirror), new(Release), new(LoginSource), new(Webhook),
  38. new(UpdateTask), new(HookTask), new(Team), new(OrgUser), new(TeamUser),
  39. new(Notice))
  40. }
  41. func LoadModelsConfig() {
  42. DbCfg.Type = setting.Cfg.MustValue("database", "DB_TYPE")
  43. if DbCfg.Type == "sqlite3" {
  44. UseSQLite3 = true
  45. }
  46. DbCfg.Host = setting.Cfg.MustValue("database", "HOST")
  47. DbCfg.Name = setting.Cfg.MustValue("database", "NAME")
  48. DbCfg.User = setting.Cfg.MustValue("database", "USER")
  49. if len(DbCfg.Pwd) == 0 {
  50. DbCfg.Pwd = setting.Cfg.MustValue("database", "PASSWD")
  51. }
  52. DbCfg.SslMode = setting.Cfg.MustValue("database", "SSL_MODE")
  53. DbCfg.Path = setting.Cfg.MustValue("database", "PATH", "data/gogs.db")
  54. }
  55. func getEngine() (*xorm.Engine, error) {
  56. cnnstr := ""
  57. switch DbCfg.Type {
  58. case "mysql":
  59. cnnstr = fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8",
  60. DbCfg.User, DbCfg.Pwd, DbCfg.Host, DbCfg.Name)
  61. case "postgres":
  62. var host, port = "127.0.0.1", "5432"
  63. fields := strings.Split(DbCfg.Host, ":")
  64. if len(fields) > 0 && len(strings.TrimSpace(fields[0])) > 0 {
  65. host = fields[0]
  66. }
  67. if len(fields) > 1 && len(strings.TrimSpace(fields[1])) > 0 {
  68. port = fields[1]
  69. }
  70. cnnstr = fmt.Sprintf("user=%s password=%s host=%s port=%s dbname=%s sslmode=%s",
  71. DbCfg.User, DbCfg.Pwd, host, port, DbCfg.Name, DbCfg.SslMode)
  72. case "sqlite3":
  73. if !EnableSQLite3 {
  74. return nil, fmt.Errorf("Unknown database type: %s", DbCfg.Type)
  75. }
  76. os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm)
  77. cnnstr = "file:" + DbCfg.Path + "?cache=shared&mode=rwc"
  78. default:
  79. return nil, fmt.Errorf("Unknown database type: %s", DbCfg.Type)
  80. }
  81. return xorm.NewEngine(DbCfg.Type, cnnstr)
  82. }
  83. func NewTestEngine(x *xorm.Engine) (err error) {
  84. x, err = getEngine()
  85. if err != nil {
  86. return fmt.Errorf("models.init(fail to connect to database): %v", err)
  87. }
  88. return x.Sync(tables...)
  89. }
  90. func SetEngine() (err error) {
  91. x, err = getEngine()
  92. if err != nil {
  93. return fmt.Errorf("models.init(fail to connect to database): %v", err)
  94. }
  95. // WARNNING: for serv command, MUST remove the output to os.stdout,
  96. // so use log file to instead print to stdout.
  97. logPath := path.Join(setting.LogRootPath, "xorm.log")
  98. os.MkdirAll(path.Dir(logPath), os.ModePerm)
  99. f, err := os.Create(logPath)
  100. if err != nil {
  101. return fmt.Errorf("models.init(fail to create xorm.log): %v", err)
  102. }
  103. x.Logger = xorm.NewSimpleLogger(f)
  104. x.ShowSQL = true
  105. x.ShowInfo = true
  106. x.ShowDebug = true
  107. x.ShowErr = true
  108. x.ShowWarn = true
  109. return nil
  110. }
  111. func NewEngine() (err error) {
  112. if err = SetEngine(); err != nil {
  113. return err
  114. }
  115. if err = x.StoreEngine("InnoDB").Sync2(tables...); err != nil {
  116. return fmt.Errorf("sync database struct error: %v\n", err)
  117. }
  118. return nil
  119. }
  120. type Statistic struct {
  121. Counter struct {
  122. User, Org, PublicKey,
  123. Repo, Watch, Star, Action, Access,
  124. Issue, Comment, Oauth, Follow,
  125. Mirror, Release, LoginSource, Webhook,
  126. Milestone, Label, HookTask,
  127. Team, UpdateTask, Attachment int64
  128. }
  129. }
  130. func GetStatistic() (stats Statistic) {
  131. stats.Counter.User = CountUsers()
  132. stats.Counter.Org = CountOrganizations()
  133. stats.Counter.PublicKey, _ = x.Count(new(PublicKey))
  134. stats.Counter.Repo = CountRepositories()
  135. stats.Counter.Watch, _ = x.Count(new(Watch))
  136. stats.Counter.Star, _ = x.Count(new(Star))
  137. stats.Counter.Action, _ = x.Count(new(Action))
  138. stats.Counter.Access, _ = x.Count(new(Access))
  139. stats.Counter.Issue, _ = x.Count(new(Issue))
  140. stats.Counter.Comment, _ = x.Count(new(Comment))
  141. stats.Counter.Oauth, _ = x.Count(new(Oauth2))
  142. stats.Counter.Follow, _ = x.Count(new(Follow))
  143. stats.Counter.Mirror, _ = x.Count(new(Mirror))
  144. stats.Counter.Release, _ = x.Count(new(Release))
  145. stats.Counter.LoginSource, _ = x.Count(new(LoginSource))
  146. stats.Counter.Webhook, _ = x.Count(new(Webhook))
  147. stats.Counter.Milestone, _ = x.Count(new(Milestone))
  148. stats.Counter.Label, _ = x.Count(new(Label))
  149. stats.Counter.HookTask, _ = x.Count(new(HookTask))
  150. stats.Counter.Team, _ = x.Count(new(Team))
  151. stats.Counter.UpdateTask, _ = x.Count(new(UpdateTask))
  152. stats.Counter.Attachment, _ = x.Count(new(Attachment))
  153. return
  154. }
  155. func Ping() error {
  156. return x.Ping()
  157. }
  158. // DumpDatabase dumps all data from database to file system.
  159. func DumpDatabase(filePath string) error {
  160. return x.DumpAllToFile(filePath)
  161. }