models.go 5.1 KB

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