models.go 6.7 KB

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