models.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  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. Get(interface{}) (bool, error)
  22. Insert(...interface{}) (int64, error)
  23. Id(interface{}) *xorm.Session
  24. Where(string, ...interface{}) *xorm.Session
  25. }
  26. var (
  27. x *xorm.Engine
  28. tables []interface{}
  29. HasEngine bool
  30. DbCfg struct {
  31. Type, Host, Name, User, Passwd, Path, SSLMode string
  32. }
  33. EnableSQLite3 bool
  34. UseSQLite3 bool
  35. )
  36. func init() {
  37. tables = append(tables,
  38. new(User), new(PublicKey), new(Follow), new(Oauth2), new(AccessToken),
  39. new(Repository), new(Watch), new(Star), new(Action), new(Access),
  40. new(Issue), new(Comment), new(Attachment), new(IssueUser), new(Label), new(Milestone),
  41. new(Mirror), new(Release), new(LoginSource), new(Webhook),
  42. new(UpdateTask), new(HookTask), new(Team), new(OrgUser), new(TeamUser),
  43. new(Notice), new(EmailAddress))
  44. }
  45. func LoadModelsConfig() {
  46. sec := setting.Cfg.Section("database")
  47. DbCfg.Type = sec.Key("DB_TYPE").String()
  48. if DbCfg.Type == "sqlite3" {
  49. UseSQLite3 = true
  50. }
  51. DbCfg.Host = sec.Key("HOST").String()
  52. DbCfg.Name = sec.Key("NAME").String()
  53. DbCfg.User = sec.Key("USER").String()
  54. if len(DbCfg.Passwd) == 0 {
  55. DbCfg.Passwd = sec.Key("PASSWD").String()
  56. }
  57. DbCfg.SSLMode = sec.Key("SSL_MODE").String()
  58. DbCfg.Path = sec.Key("PATH").MustString("data/gogs.db")
  59. }
  60. func getEngine() (*xorm.Engine, error) {
  61. cnnstr := ""
  62. switch DbCfg.Type {
  63. case "mysql":
  64. cnnstr = fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8",
  65. DbCfg.User, DbCfg.Passwd, DbCfg.Host, DbCfg.Name)
  66. case "postgres":
  67. var host, port = "127.0.0.1", "5432"
  68. fields := strings.Split(DbCfg.Host, ":")
  69. if len(fields) > 0 && len(strings.TrimSpace(fields[0])) > 0 {
  70. host = fields[0]
  71. }
  72. if len(fields) > 1 && len(strings.TrimSpace(fields[1])) > 0 {
  73. port = fields[1]
  74. }
  75. cnnstr = fmt.Sprintf("user=%s password=%s host=%s port=%s dbname=%s sslmode=%s",
  76. DbCfg.User, DbCfg.Passwd, host, port, DbCfg.Name, DbCfg.SSLMode)
  77. case "sqlite3":
  78. if !EnableSQLite3 {
  79. return nil, fmt.Errorf("Unknown database type: %s", DbCfg.Type)
  80. }
  81. os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm)
  82. cnnstr = "file:" + DbCfg.Path + "?cache=shared&mode=rwc"
  83. default:
  84. return nil, fmt.Errorf("Unknown database type: %s", DbCfg.Type)
  85. }
  86. return xorm.NewEngine(DbCfg.Type, cnnstr)
  87. }
  88. func NewTestEngine(x *xorm.Engine) (err error) {
  89. x, err = getEngine()
  90. if err != nil {
  91. return fmt.Errorf("connect to database: %v", err)
  92. }
  93. return x.Sync(tables...)
  94. }
  95. func SetEngine() (err error) {
  96. x, err = getEngine()
  97. if err != nil {
  98. return fmt.Errorf("connect to database: %v", err)
  99. }
  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.SetLogger(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. }