models.go 7.2 KB

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