models.go 5.5 KB

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