models.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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 := "127.0.0.1", "5432"
  118. if strings.Contains(DbCfg.Host, ":") && !strings.HasSuffix(DbCfg.Host, "]") {
  119. idx := strings.LastIndex(DbCfg.Host, ":")
  120. host = DbCfg.Host[:idx]
  121. port = DbCfg.Host[idx+1:]
  122. } else if len(DbCfg.Host) > 0 {
  123. host = DbCfg.Host
  124. }
  125. if host[0] == '/' { // looks like a unix socket
  126. connStr = fmt.Sprintf("postgres://%s:%s@:%s/%s%ssslmode=%s&host=%s",
  127. url.QueryEscape(DbCfg.User), url.QueryEscape(DbCfg.Passwd), port, DbCfg.Name, Param, DbCfg.SSLMode, host)
  128. } else {
  129. connStr = fmt.Sprintf("postgres://%s:%s@%s:%s/%s%ssslmode=%s",
  130. url.QueryEscape(DbCfg.User), url.QueryEscape(DbCfg.Passwd), host, port, DbCfg.Name, Param, DbCfg.SSLMode)
  131. }
  132. case "sqlite3":
  133. if !EnableSQLite3 {
  134. return nil, errors.New("This binary version does not build support for SQLite3.")
  135. }
  136. if err := os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm); err != nil {
  137. return nil, fmt.Errorf("Fail to create directories: %v", err)
  138. }
  139. connStr = "file:" + DbCfg.Path + "?cache=shared&mode=rwc"
  140. case "tidb":
  141. if !EnableTiDB {
  142. return nil, errors.New("This binary version does not build support for TiDB.")
  143. }
  144. if err := os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm); err != nil {
  145. return nil, fmt.Errorf("Fail to create directories: %v", err)
  146. }
  147. connStr = "goleveldb://" + DbCfg.Path
  148. default:
  149. return nil, fmt.Errorf("Unknown database type: %s", DbCfg.Type)
  150. }
  151. return xorm.NewEngine(DbCfg.Type, connStr)
  152. }
  153. func NewTestEngine(x *xorm.Engine) (err error) {
  154. x, err = getEngine()
  155. if err != nil {
  156. return fmt.Errorf("Connect to database: %v", err)
  157. }
  158. x.SetMapper(core.GonicMapper{})
  159. return x.StoreEngine("InnoDB").Sync2(tables...)
  160. }
  161. func SetEngine() (err error) {
  162. x, err = getEngine()
  163. if err != nil {
  164. return fmt.Errorf("Fail to connect to database: %v", err)
  165. }
  166. x.SetMapper(core.GonicMapper{})
  167. // WARNING: for serv command, MUST remove the output to os.stdout,
  168. // so use log file to instead print to stdout.
  169. logPath := path.Join(setting.LogRootPath, "xorm.log")
  170. os.MkdirAll(path.Dir(logPath), os.ModePerm)
  171. f, err := os.Create(logPath)
  172. if err != nil {
  173. return fmt.Errorf("Fail to create xorm.log: %v", err)
  174. }
  175. x.SetLogger(xorm.NewSimpleLogger(f))
  176. x.ShowSQL(true)
  177. return nil
  178. }
  179. func NewEngine() (err error) {
  180. if err = SetEngine(); err != nil {
  181. return err
  182. }
  183. if err = migrations.Migrate(x); err != nil {
  184. return fmt.Errorf("migrate: %v", err)
  185. }
  186. if err = x.StoreEngine("InnoDB").Sync2(tables...); err != nil {
  187. return fmt.Errorf("sync database struct error: %v\n", err)
  188. }
  189. return nil
  190. }
  191. type Statistic struct {
  192. Counter struct {
  193. User, Org, PublicKey,
  194. Repo, Watch, Star, Action, Access,
  195. Issue, Comment, Oauth, Follow,
  196. Mirror, Release, LoginSource, Webhook,
  197. Milestone, Label, HookTask,
  198. Team, UpdateTask, Attachment int64
  199. }
  200. }
  201. func GetStatistic() (stats Statistic) {
  202. stats.Counter.User = CountUsers()
  203. stats.Counter.Org = CountOrganizations()
  204. stats.Counter.PublicKey, _ = x.Count(new(PublicKey))
  205. stats.Counter.Repo = CountRepositories(true)
  206. stats.Counter.Watch, _ = x.Count(new(Watch))
  207. stats.Counter.Star, _ = x.Count(new(Star))
  208. stats.Counter.Action, _ = x.Count(new(Action))
  209. stats.Counter.Access, _ = x.Count(new(Access))
  210. stats.Counter.Issue, _ = x.Count(new(Issue))
  211. stats.Counter.Comment, _ = x.Count(new(Comment))
  212. stats.Counter.Oauth = 0
  213. stats.Counter.Follow, _ = x.Count(new(Follow))
  214. stats.Counter.Mirror, _ = x.Count(new(Mirror))
  215. stats.Counter.Release, _ = x.Count(new(Release))
  216. stats.Counter.LoginSource = CountLoginSources()
  217. stats.Counter.Webhook, _ = x.Count(new(Webhook))
  218. stats.Counter.Milestone, _ = x.Count(new(Milestone))
  219. stats.Counter.Label, _ = x.Count(new(Label))
  220. stats.Counter.HookTask, _ = x.Count(new(HookTask))
  221. stats.Counter.Team, _ = x.Count(new(Team))
  222. stats.Counter.UpdateTask, _ = x.Count(new(UpdateTask))
  223. stats.Counter.Attachment, _ = x.Count(new(Attachment))
  224. return
  225. }
  226. func Ping() error {
  227. return x.Ping()
  228. }
  229. // DumpDatabase dumps all data from database to file system.
  230. func DumpDatabase(filePath string) error {
  231. return x.DumpAllToFile(filePath)
  232. }