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

219 lines
5.9 KiB

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