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

253 lines
7.2 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  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. "errors"
  8. "fmt"
  9. "net/url"
  10. "os"
  11. "path"
  12. "strings"
  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. Id(interface{}) *xorm.Session
  27. Insert(...interface{}) (int64, error)
  28. InsertOne(interface{}) (int64, error)
  29. Iterate(interface{}, xorm.IterFunc) error
  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. var (
  40. x *xorm.Engine
  41. tables []interface{}
  42. HasEngine bool
  43. DbCfg struct {
  44. Type, Host, Name, User, Passwd, Path, SSLMode string
  45. }
  46. EnableSQLite3 bool
  47. EnableTiDB bool
  48. )
  49. func init() {
  50. tables = append(tables,
  51. new(User), new(PublicKey), new(AccessToken),
  52. new(Repository), new(DeployKey), new(Collaboration), new(Access),
  53. new(Watch), new(Star), new(Follow), new(Action),
  54. new(Issue), new(PullRequest), new(Comment), new(Attachment), new(IssueUser),
  55. new(Label), new(IssueLabel), new(Milestone),
  56. new(Mirror), new(Release), new(LoginSource), new(Webhook),
  57. new(UpdateTask), new(HookTask),
  58. new(Team), new(OrgUser), new(TeamUser), new(TeamRepo),
  59. new(Notice), new(EmailAddress))
  60. gonicNames := []string{"SSL"}
  61. for _, name := range gonicNames {
  62. core.LintGonicMapper[name] = true
  63. }
  64. }
  65. func LoadConfigs() {
  66. sec := setting.Cfg.Section("database")
  67. DbCfg.Type = sec.Key("DB_TYPE").String()
  68. switch DbCfg.Type {
  69. case "sqlite3":
  70. setting.UseSQLite3 = true
  71. case "mysql":
  72. setting.UseMySQL = true
  73. case "postgres":
  74. setting.UsePostgreSQL = true
  75. case "tidb":
  76. setting.UseTiDB = true
  77. }
  78. DbCfg.Host = sec.Key("HOST").String()
  79. DbCfg.Name = sec.Key("NAME").String()
  80. DbCfg.User = sec.Key("USER").String()
  81. if len(DbCfg.Passwd) == 0 {
  82. DbCfg.Passwd = sec.Key("PASSWD").String()
  83. }
  84. DbCfg.SSLMode = sec.Key("SSL_MODE").String()
  85. DbCfg.Path = sec.Key("PATH").MustString("data/gogs.db")
  86. }
  87. // parsePostgreSQLHostPort parses given input in various forms defined in
  88. // https://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING
  89. // and returns proper host and port number.
  90. func parsePostgreSQLHostPort(info string) (string, string) {
  91. host, port := "127.0.0.1", "5432"
  92. if strings.Contains(info, ":") && !strings.HasSuffix(info, "]") {
  93. idx := strings.LastIndex(info, ":")
  94. host = info[:idx]
  95. port = info[idx+1:]
  96. } else if len(info) > 0 {
  97. host = info
  98. }
  99. return host, port
  100. }
  101. func getEngine() (*xorm.Engine, error) {
  102. connStr := ""
  103. var Param string = "?"
  104. if strings.Contains(DbCfg.Name, Param) {
  105. Param = "&"
  106. }
  107. switch DbCfg.Type {
  108. case "mysql":
  109. if DbCfg.Host[0] == '/' { // looks like a unix socket
  110. connStr = fmt.Sprintf("%s:%s@unix(%s)/%s%scharset=utf8&parseTime=true",
  111. DbCfg.User, DbCfg.Passwd, DbCfg.Host, DbCfg.Name, Param)
  112. } else {
  113. connStr = fmt.Sprintf("%s:%s@tcp(%s)/%s%scharset=utf8&parseTime=true",
  114. DbCfg.User, DbCfg.Passwd, DbCfg.Host, DbCfg.Name, Param)
  115. }
  116. case "postgres":
  117. host, port := parsePostgreSQLHostPort(DbCfg.Host)
  118. if host[0] == '/' { // looks like a unix socket
  119. connStr = fmt.Sprintf("postgres://%s:%s@:%s/%s%ssslmode=%s&host=%s",
  120. url.QueryEscape(DbCfg.User), url.QueryEscape(DbCfg.Passwd), port, DbCfg.Name, Param, DbCfg.SSLMode, host)
  121. } else {
  122. connStr = fmt.Sprintf("postgres://%s:%s@%s:%s/%s%ssslmode=%s",
  123. url.QueryEscape(DbCfg.User), url.QueryEscape(DbCfg.Passwd), host, port, DbCfg.Name, Param, DbCfg.SSLMode)
  124. }
  125. case "sqlite3":
  126. if !EnableSQLite3 {
  127. return nil, errors.New("This binary version does not build support for SQLite3.")
  128. }
  129. if err := os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm); err != nil {
  130. return nil, fmt.Errorf("Fail to create directories: %v", err)
  131. }
  132. connStr = "file:" + DbCfg.Path + "?cache=shared&mode=rwc"
  133. case "tidb":
  134. if !EnableTiDB {
  135. return nil, errors.New("This binary version does not build support for TiDB.")
  136. }
  137. if err := os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm); err != nil {
  138. return nil, fmt.Errorf("Fail to create directories: %v", err)
  139. }
  140. connStr = "goleveldb://" + DbCfg.Path
  141. default:
  142. return nil, fmt.Errorf("Unknown database type: %s", DbCfg.Type)
  143. }
  144. return xorm.NewEngine(DbCfg.Type, connStr)
  145. }
  146. func NewTestEngine(x *xorm.Engine) (err error) {
  147. x, err = getEngine()
  148. if err != nil {
  149. return fmt.Errorf("Connect to database: %v", err)
  150. }
  151. x.SetMapper(core.GonicMapper{})
  152. return x.StoreEngine("InnoDB").Sync2(tables...)
  153. }
  154. func SetEngine() (err error) {
  155. x, err = getEngine()
  156. if err != nil {
  157. return fmt.Errorf("Fail to connect to database: %v", err)
  158. }
  159. x.SetMapper(core.GonicMapper{})
  160. // WARNING: for serv command, MUST remove the output to os.stdout,
  161. // so use log file to instead print to stdout.
  162. logPath := path.Join(setting.LogRootPath, "xorm.log")
  163. os.MkdirAll(path.Dir(logPath), os.ModePerm)
  164. f, err := os.Create(logPath)
  165. if err != nil {
  166. return fmt.Errorf("Fail to create xorm.log: %v", err)
  167. }
  168. x.SetLogger(xorm.NewSimpleLogger(f))
  169. x.ShowSQL(true)
  170. return nil
  171. }
  172. func NewEngine() (err error) {
  173. if err = SetEngine(); err != nil {
  174. return err
  175. }
  176. if err = migrations.Migrate(x); err != nil {
  177. return fmt.Errorf("migrate: %v", err)
  178. }
  179. if err = x.StoreEngine("InnoDB").Sync2(tables...); err != nil {
  180. return fmt.Errorf("sync database struct error: %v\n", err)
  181. }
  182. return nil
  183. }
  184. type Statistic struct {
  185. Counter struct {
  186. User, Org, PublicKey,
  187. Repo, Watch, Star, Action, Access,
  188. Issue, Comment, Oauth, Follow,
  189. Mirror, Release, LoginSource, Webhook,
  190. Milestone, Label, HookTask,
  191. Team, UpdateTask, Attachment int64
  192. }
  193. }
  194. func GetStatistic() (stats Statistic) {
  195. stats.Counter.User = CountUsers()
  196. stats.Counter.Org = CountOrganizations()
  197. stats.Counter.PublicKey, _ = x.Count(new(PublicKey))
  198. stats.Counter.Repo = CountRepositories(true)
  199. stats.Counter.Watch, _ = x.Count(new(Watch))
  200. stats.Counter.Star, _ = x.Count(new(Star))
  201. stats.Counter.Action, _ = x.Count(new(Action))
  202. stats.Counter.Access, _ = x.Count(new(Access))
  203. stats.Counter.Issue, _ = x.Count(new(Issue))
  204. stats.Counter.Comment, _ = x.Count(new(Comment))
  205. stats.Counter.Oauth = 0
  206. stats.Counter.Follow, _ = x.Count(new(Follow))
  207. stats.Counter.Mirror, _ = x.Count(new(Mirror))
  208. stats.Counter.Release, _ = x.Count(new(Release))
  209. stats.Counter.LoginSource = CountLoginSources()
  210. stats.Counter.Webhook, _ = x.Count(new(Webhook))
  211. stats.Counter.Milestone, _ = x.Count(new(Milestone))
  212. stats.Counter.Label, _ = x.Count(new(Label))
  213. stats.Counter.HookTask, _ = x.Count(new(HookTask))
  214. stats.Counter.Team, _ = x.Count(new(Team))
  215. stats.Counter.UpdateTask, _ = x.Count(new(UpdateTask))
  216. stats.Counter.Attachment, _ = x.Count(new(Attachment))
  217. return
  218. }
  219. func Ping() error {
  220. return x.Ping()
  221. }
  222. // DumpDatabase dumps all data from database to file system.
  223. func DumpDatabase(filePath string) error {
  224. return x.DumpAllToFile(filePath)
  225. }