models.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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.UseSQLite3 {
  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:4]).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(Oauth2), 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 LoadModelsConfig() {
  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. }
  93. DbCfg.Host = sec.Key("HOST").String()
  94. DbCfg.Name = sec.Key("NAME").String()
  95. DbCfg.User = sec.Key("USER").String()
  96. if len(DbCfg.Passwd) == 0 {
  97. DbCfg.Passwd = sec.Key("PASSWD").String()
  98. }
  99. DbCfg.SSLMode = sec.Key("SSL_MODE").String()
  100. DbCfg.Path = sec.Key("PATH").MustString("data/gogs.db")
  101. }
  102. func getEngine() (*xorm.Engine, error) {
  103. cnnstr := ""
  104. switch DbCfg.Type {
  105. case "mysql":
  106. if DbCfg.Host[0] == '/' { // looks like a unix socket
  107. cnnstr = fmt.Sprintf("%s:%s@unix(%s)/%s?charset=utf8&parseTime=true",
  108. DbCfg.User, DbCfg.Passwd, DbCfg.Host, DbCfg.Name)
  109. } else {
  110. cnnstr = fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=true",
  111. DbCfg.User, DbCfg.Passwd, DbCfg.Host, DbCfg.Name)
  112. }
  113. case "postgres":
  114. var host, port = "127.0.0.1", "5432"
  115. fields := strings.Split(DbCfg.Host, ":")
  116. if len(fields) > 0 && len(strings.TrimSpace(fields[0])) > 0 {
  117. host = fields[0]
  118. }
  119. if len(fields) > 1 && len(strings.TrimSpace(fields[1])) > 0 {
  120. port = fields[1]
  121. }
  122. cnnstr = fmt.Sprintf("postgres://%s:%s@%s:%s/%s?sslmode=%s",
  123. url.QueryEscape(DbCfg.User), url.QueryEscape(DbCfg.Passwd), host, port, DbCfg.Name, DbCfg.SSLMode)
  124. case "sqlite3":
  125. if !EnableSQLite3 {
  126. return nil, fmt.Errorf("Unknown database type: %s", DbCfg.Type)
  127. }
  128. if err := os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm); err != nil {
  129. return nil, fmt.Errorf("Fail to create directories: %v", err)
  130. }
  131. cnnstr = "file:" + DbCfg.Path + "?cache=shared&mode=rwc"
  132. case "tidb":
  133. if !EnableTidb {
  134. return nil, fmt.Errorf("Unknown database type: %s", DbCfg.Type)
  135. }
  136. if err := os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm); err != nil {
  137. return nil, fmt.Errorf("Fail to create directories: %v", err)
  138. }
  139. cnnstr = "goleveldb://" + DbCfg.Path
  140. default:
  141. return nil, fmt.Errorf("Unknown database type: %s", DbCfg.Type)
  142. }
  143. return xorm.NewEngine(DbCfg.Type, cnnstr)
  144. }
  145. func NewTestEngine(x *xorm.Engine) (err error) {
  146. x, err = getEngine()
  147. if err != nil {
  148. return fmt.Errorf("Connect to database: %v", err)
  149. }
  150. x.SetMapper(core.GonicMapper{})
  151. return x.StoreEngine("InnoDB").Sync2(tables...)
  152. }
  153. func SetEngine() (err error) {
  154. x, err = getEngine()
  155. if err != nil {
  156. return fmt.Errorf("Fail to connect to database: %v", err)
  157. }
  158. x.SetMapper(core.GonicMapper{})
  159. // WARNING: for serv command, MUST remove the output to os.stdout,
  160. // so use log file to instead print to stdout.
  161. logPath := path.Join(setting.LogRootPath, "xorm.log")
  162. os.MkdirAll(path.Dir(logPath), os.ModePerm)
  163. f, err := os.Create(logPath)
  164. if err != nil {
  165. return fmt.Errorf("Fail to create xorm.log: %v", err)
  166. }
  167. x.SetLogger(xorm.NewSimpleLogger(f))
  168. x.ShowSQL = true
  169. x.ShowInfo = true
  170. x.ShowDebug = true
  171. x.ShowErr = true
  172. x.ShowWarn = 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, _ = x.Count(new(Oauth2))
  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. }