models.go 7.2 KB

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