models.go 6.0 KB

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