models.go 6.6 KB

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