You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

models.go 5.9 kB

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