models.go 7.3 KB

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