models.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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. gonicNames := []string{"SSL"}
  75. for _, name := range gonicNames {
  76. core.LintGonicMapper[name] = true
  77. }
  78. }
  79. func LoadModelsConfig() {
  80. sec := setting.Cfg.Section("database")
  81. DbCfg.Type = sec.Key("DB_TYPE").String()
  82. switch DbCfg.Type {
  83. case "sqlite3":
  84. setting.UseSQLite3 = true
  85. case "mysql":
  86. setting.UseMySQL = true
  87. case "postgres":
  88. setting.UsePostgreSQL = true
  89. }
  90. DbCfg.Host = sec.Key("HOST").String()
  91. DbCfg.Name = sec.Key("NAME").String()
  92. DbCfg.User = sec.Key("USER").String()
  93. if len(DbCfg.Passwd) == 0 {
  94. DbCfg.Passwd = sec.Key("PASSWD").String()
  95. }
  96. DbCfg.SSLMode = sec.Key("SSL_MODE").String()
  97. DbCfg.Path = sec.Key("PATH").MustString("data/gogs.db")
  98. }
  99. func getEngine() (*xorm.Engine, error) {
  100. cnnstr := ""
  101. switch DbCfg.Type {
  102. case "mysql":
  103. if DbCfg.Host[0] == '/' { // looks like a unix socket
  104. cnnstr = fmt.Sprintf("%s:%s@unix(%s)/%s?charset=utf8&parseTime=true",
  105. DbCfg.User, DbCfg.Passwd, DbCfg.Host, DbCfg.Name)
  106. } else {
  107. cnnstr = fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=true",
  108. DbCfg.User, DbCfg.Passwd, DbCfg.Host, DbCfg.Name)
  109. }
  110. case "postgres":
  111. var host, port = "127.0.0.1", "5432"
  112. fields := strings.Split(DbCfg.Host, ":")
  113. if len(fields) > 0 && len(strings.TrimSpace(fields[0])) > 0 {
  114. host = fields[0]
  115. }
  116. if len(fields) > 1 && len(strings.TrimSpace(fields[1])) > 0 {
  117. port = fields[1]
  118. }
  119. cnnstr = fmt.Sprintf("postgres://%s:%s@%s:%s/%s?sslmode=%s",
  120. DbCfg.User, DbCfg.Passwd, host, port, DbCfg.Name, DbCfg.SSLMode)
  121. case "sqlite3":
  122. if !EnableSQLite3 {
  123. return nil, fmt.Errorf("Unknown database type: %s", DbCfg.Type)
  124. }
  125. if err := os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm); err != nil {
  126. return nil, fmt.Errorf("Fail to create directories: %v", err)
  127. }
  128. cnnstr = "file:" + DbCfg.Path + "?cache=shared&mode=rwc"
  129. default:
  130. return nil, fmt.Errorf("Unknown database type: %s", DbCfg.Type)
  131. }
  132. return xorm.NewEngine(DbCfg.Type, cnnstr)
  133. }
  134. func NewTestEngine(x *xorm.Engine) (err error) {
  135. x, err = getEngine()
  136. if err != nil {
  137. return fmt.Errorf("Connect to database: %v", err)
  138. }
  139. x.SetMapper(core.GonicMapper{})
  140. return x.Sync(tables...)
  141. }
  142. func SetEngine() (err error) {
  143. x, err = getEngine()
  144. if err != nil {
  145. return fmt.Errorf("Fail to connect to database: %v", err)
  146. }
  147. x.SetMapper(core.GonicMapper{})
  148. // WARNING: for serv command, MUST remove the output to os.stdout,
  149. // so use log file to instead print to stdout.
  150. logPath := path.Join(setting.LogRootPath, "xorm.log")
  151. os.MkdirAll(path.Dir(logPath), os.ModePerm)
  152. f, err := os.Create(logPath)
  153. if err != nil {
  154. return fmt.Errorf("Fail to create xorm.log: %v", err)
  155. }
  156. x.SetLogger(xorm.NewSimpleLogger(f))
  157. x.ShowSQL = true
  158. x.ShowInfo = true
  159. x.ShowDebug = true
  160. x.ShowErr = true
  161. x.ShowWarn = true
  162. return nil
  163. }
  164. func NewEngine() (err error) {
  165. if err = SetEngine(); err != nil {
  166. return err
  167. }
  168. if err = migrations.Migrate(x); err != nil {
  169. return fmt.Errorf("migrate: %v", err)
  170. }
  171. if err = x.StoreEngine("InnoDB").Sync2(tables...); err != nil {
  172. return fmt.Errorf("sync database struct error: %v\n", err)
  173. }
  174. return nil
  175. }
  176. type Statistic struct {
  177. Counter struct {
  178. User, Org, PublicKey,
  179. Repo, Watch, Star, Action, Access,
  180. Issue, Comment, Oauth, Follow,
  181. Mirror, Release, LoginSource, Webhook,
  182. Milestone, Label, HookTask,
  183. Team, UpdateTask, Attachment int64
  184. }
  185. }
  186. func GetStatistic() (stats Statistic) {
  187. stats.Counter.User = CountUsers()
  188. stats.Counter.Org = CountOrganizations()
  189. stats.Counter.PublicKey, _ = x.Count(new(PublicKey))
  190. stats.Counter.Repo = CountRepositories()
  191. stats.Counter.Watch, _ = x.Count(new(Watch))
  192. stats.Counter.Star, _ = x.Count(new(Star))
  193. stats.Counter.Action, _ = x.Count(new(Action))
  194. stats.Counter.Access, _ = x.Count(new(Access))
  195. stats.Counter.Issue, _ = x.Count(new(Issue))
  196. stats.Counter.Comment, _ = x.Count(new(Comment))
  197. stats.Counter.Oauth, _ = x.Count(new(Oauth2))
  198. stats.Counter.Follow, _ = x.Count(new(Follow))
  199. stats.Counter.Mirror, _ = x.Count(new(Mirror))
  200. stats.Counter.Release, _ = x.Count(new(Release))
  201. stats.Counter.LoginSource, _ = x.Count(new(LoginSource))
  202. stats.Counter.Webhook, _ = x.Count(new(Webhook))
  203. stats.Counter.Milestone, _ = x.Count(new(Milestone))
  204. stats.Counter.Label, _ = x.Count(new(Label))
  205. stats.Counter.HookTask, _ = x.Count(new(HookTask))
  206. stats.Counter.Team, _ = x.Count(new(Team))
  207. stats.Counter.UpdateTask, _ = x.Count(new(UpdateTask))
  208. stats.Counter.Attachment, _ = x.Count(new(Attachment))
  209. return
  210. }
  211. func Ping() error {
  212. return x.Ping()
  213. }
  214. // DumpDatabase dumps all data from database to file system.
  215. func DumpDatabase(filePath string) error {
  216. return x.DumpAllToFile(filePath)
  217. }