You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

models.go 7.2 kB

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