models.go 6.5 KB

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