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.

258 lines
7.3 KiB

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