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