models.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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. Where(string, ...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/gogs.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 = migrations.Migrate(x); err != nil {
  178. return fmt.Errorf("migrate: %v", err)
  179. }
  180. if err = x.StoreEngine("InnoDB").Sync2(tables...); err != nil {
  181. return fmt.Errorf("sync database struct error: %v\n", err)
  182. }
  183. return nil
  184. }
  185. type Statistic struct {
  186. Counter struct {
  187. User, Org, PublicKey,
  188. Repo, Watch, Star, Action, Access,
  189. Issue, Comment, Oauth, Follow,
  190. Mirror, Release, LoginSource, Webhook,
  191. Milestone, Label, HookTask,
  192. Team, UpdateTask, Attachment int64
  193. }
  194. }
  195. func GetStatistic() (stats Statistic) {
  196. stats.Counter.User = CountUsers()
  197. stats.Counter.Org = CountOrganizations()
  198. stats.Counter.PublicKey, _ = x.Count(new(PublicKey))
  199. stats.Counter.Repo = CountRepositories(true)
  200. stats.Counter.Watch, _ = x.Count(new(Watch))
  201. stats.Counter.Star, _ = x.Count(new(Star))
  202. stats.Counter.Action, _ = x.Count(new(Action))
  203. stats.Counter.Access, _ = x.Count(new(Access))
  204. stats.Counter.Issue, _ = x.Count(new(Issue))
  205. stats.Counter.Comment, _ = x.Count(new(Comment))
  206. stats.Counter.Oauth = 0
  207. stats.Counter.Follow, _ = x.Count(new(Follow))
  208. stats.Counter.Mirror, _ = x.Count(new(Mirror))
  209. stats.Counter.Release, _ = x.Count(new(Release))
  210. stats.Counter.LoginSource = CountLoginSources()
  211. stats.Counter.Webhook, _ = x.Count(new(Webhook))
  212. stats.Counter.Milestone, _ = x.Count(new(Milestone))
  213. stats.Counter.Label, _ = x.Count(new(Label))
  214. stats.Counter.HookTask, _ = x.Count(new(HookTask))
  215. stats.Counter.Team, _ = x.Count(new(Team))
  216. stats.Counter.UpdateTask, _ = x.Count(new(UpdateTask))
  217. stats.Counter.Attachment, _ = x.Count(new(Attachment))
  218. return
  219. }
  220. func Ping() error {
  221. return x.Ping()
  222. }
  223. // DumpDatabase dumps all data from database to file system.
  224. func DumpDatabase(filePath string) error {
  225. return x.DumpAllToFile(filePath)
  226. }