Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

models.go 6.6KB

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