models.go 5.2 KB

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