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