models.go 5.3 KB

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