models.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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/denisenkom/go-mssqldb"
  14. _ "github.com/go-sql-driver/mysql"
  15. "github.com/go-xorm/core"
  16. "github.com/go-xorm/xorm"
  17. _ "github.com/lib/pq"
  18. "github.com/gogits/gogs/models/migrations"
  19. "github.com/gogits/gogs/modules/setting"
  20. )
  21. // Engine represents a xorm engine or session.
  22. type Engine interface {
  23. Delete(interface{}) (int64, error)
  24. Exec(string, ...interface{}) (sql.Result, error)
  25. Find(interface{}, ...interface{}) error
  26. Get(interface{}) (bool, error)
  27. Id(interface{}) *xorm.Session
  28. In(string, ...interface{}) *xorm.Session
  29. Insert(...interface{}) (int64, error)
  30. InsertOne(interface{}) (int64, error)
  31. Iterate(interface{}, xorm.IterFunc) error
  32. Sql(string, ...interface{}) *xorm.Session
  33. Table(interface{}) *xorm.Session
  34. Where(interface{}, ...interface{}) *xorm.Session
  35. }
  36. func sessionRelease(sess *xorm.Session) {
  37. if !sess.IsCommitedOrRollbacked {
  38. sess.Rollback()
  39. }
  40. sess.Close()
  41. }
  42. var (
  43. x *xorm.Engine
  44. tables []interface{}
  45. HasEngine bool
  46. DbCfg struct {
  47. Type, Host, Name, User, Passwd, Path, SSLMode string
  48. }
  49. EnableSQLite3 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), new(HookTask),
  59. new(ProtectBranch), new(ProtectBranchWhitelist),
  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 "mssql":
  78. setting.UseMSSQL = 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 parseMSSQLHostPort(info string) (string, string) {
  104. host, port := "127.0.0.1", "1433"
  105. if strings.Contains(info, ":") {
  106. host = strings.Split(info, ":")[0]
  107. port = strings.Split(info, ":")[1]
  108. } else if strings.Contains(info, ",") {
  109. host = strings.Split(info, ",")[0]
  110. port = strings.TrimSpace(strings.Split(info, ",")[1])
  111. } else if len(info) > 0 {
  112. host = info
  113. }
  114. return host, port
  115. }
  116. func getEngine() (*xorm.Engine, error) {
  117. connStr := ""
  118. var Param string = "?"
  119. if strings.Contains(DbCfg.Name, Param) {
  120. Param = "&"
  121. }
  122. switch DbCfg.Type {
  123. case "mysql":
  124. if DbCfg.Host[0] == '/' { // looks like a unix socket
  125. connStr = fmt.Sprintf("%s:%s@unix(%s)/%s%scharset=utf8&parseTime=true",
  126. DbCfg.User, DbCfg.Passwd, DbCfg.Host, DbCfg.Name, Param)
  127. } else {
  128. connStr = fmt.Sprintf("%s:%s@tcp(%s)/%s%scharset=utf8&parseTime=true",
  129. DbCfg.User, DbCfg.Passwd, DbCfg.Host, DbCfg.Name, Param)
  130. }
  131. case "postgres":
  132. host, port := parsePostgreSQLHostPort(DbCfg.Host)
  133. if host[0] == '/' { // looks like a unix socket
  134. connStr = fmt.Sprintf("postgres://%s:%s@:%s/%s%ssslmode=%s&host=%s",
  135. url.QueryEscape(DbCfg.User), url.QueryEscape(DbCfg.Passwd), port, DbCfg.Name, Param, DbCfg.SSLMode, host)
  136. } else {
  137. connStr = fmt.Sprintf("postgres://%s:%s@%s:%s/%s%ssslmode=%s",
  138. url.QueryEscape(DbCfg.User), url.QueryEscape(DbCfg.Passwd), host, port, DbCfg.Name, Param, DbCfg.SSLMode)
  139. }
  140. case "mssql":
  141. host, port := parseMSSQLHostPort(DbCfg.Host)
  142. connStr = fmt.Sprintf("server=%s; port=%s; database=%s; user id=%s; password=%s;", host, port, DbCfg.Name, DbCfg.User, DbCfg.Passwd)
  143. case "sqlite3":
  144. if !EnableSQLite3 {
  145. return nil, errors.New("This binary version does not build support for SQLite3.")
  146. }
  147. if err := os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm); err != nil {
  148. return nil, fmt.Errorf("Fail to create directories: %v", err)
  149. }
  150. connStr = "file:" + DbCfg.Path + "?cache=shared&mode=rwc"
  151. default:
  152. return nil, fmt.Errorf("Unknown database type: %s", DbCfg.Type)
  153. }
  154. return xorm.NewEngine(DbCfg.Type, connStr)
  155. }
  156. func NewTestEngine(x *xorm.Engine) (err error) {
  157. x, err = getEngine()
  158. if err != nil {
  159. return fmt.Errorf("Connect to database: %v", err)
  160. }
  161. x.SetMapper(core.GonicMapper{})
  162. return x.StoreEngine("InnoDB").Sync2(tables...)
  163. }
  164. func SetEngine() (err error) {
  165. x, err = getEngine()
  166. if err != nil {
  167. return fmt.Errorf("Fail to connect to database: %v", err)
  168. }
  169. x.SetMapper(core.GonicMapper{})
  170. // WARNING: for serv command, MUST remove the output to os.stdout,
  171. // so use log file to instead print to stdout.
  172. logPath := path.Join(setting.LogRootPath, "xorm.log")
  173. os.MkdirAll(path.Dir(logPath), os.ModePerm)
  174. f, err := os.Create(logPath)
  175. if err != nil {
  176. return fmt.Errorf("Fail to create xorm.log: %v", err)
  177. }
  178. if setting.ProdMode {
  179. x.SetLogger(xorm.NewSimpleLogger3(f, xorm.DEFAULT_LOG_PREFIX, xorm.DEFAULT_LOG_FLAG, core.LOG_WARNING))
  180. } else {
  181. x.SetLogger(xorm.NewSimpleLogger(f))
  182. }
  183. x.ShowSQL(true)
  184. return nil
  185. }
  186. func NewEngine() (err error) {
  187. if err = SetEngine(); err != nil {
  188. return err
  189. }
  190. if err = migrations.Migrate(x); err != nil {
  191. return fmt.Errorf("migrate: %v", err)
  192. }
  193. if err = x.StoreEngine("InnoDB").Sync2(tables...); err != nil {
  194. return fmt.Errorf("sync database struct error: %v\n", err)
  195. }
  196. return nil
  197. }
  198. type Statistic struct {
  199. Counter struct {
  200. User, Org, PublicKey,
  201. Repo, Watch, Star, Action, Access,
  202. Issue, Comment, Oauth, Follow,
  203. Mirror, Release, LoginSource, Webhook,
  204. Milestone, Label, HookTask,
  205. Team, UpdateTask, Attachment int64
  206. }
  207. }
  208. func GetStatistic() (stats Statistic) {
  209. stats.Counter.User = CountUsers()
  210. stats.Counter.Org = CountOrganizations()
  211. stats.Counter.PublicKey, _ = x.Count(new(PublicKey))
  212. stats.Counter.Repo = CountRepositories(true)
  213. stats.Counter.Watch, _ = x.Count(new(Watch))
  214. stats.Counter.Star, _ = x.Count(new(Star))
  215. stats.Counter.Action, _ = x.Count(new(Action))
  216. stats.Counter.Access, _ = x.Count(new(Access))
  217. stats.Counter.Issue, _ = x.Count(new(Issue))
  218. stats.Counter.Comment, _ = x.Count(new(Comment))
  219. stats.Counter.Oauth = 0
  220. stats.Counter.Follow, _ = x.Count(new(Follow))
  221. stats.Counter.Mirror, _ = x.Count(new(Mirror))
  222. stats.Counter.Release, _ = x.Count(new(Release))
  223. stats.Counter.LoginSource = CountLoginSources()
  224. stats.Counter.Webhook, _ = x.Count(new(Webhook))
  225. stats.Counter.Milestone, _ = x.Count(new(Milestone))
  226. stats.Counter.Label, _ = x.Count(new(Label))
  227. stats.Counter.HookTask, _ = x.Count(new(HookTask))
  228. stats.Counter.Team, _ = x.Count(new(Team))
  229. stats.Counter.Attachment, _ = x.Count(new(Attachment))
  230. return
  231. }
  232. func Ping() error {
  233. return x.Ping()
  234. }
  235. // DumpDatabase dumps all data from database to file system.
  236. func DumpDatabase(filePath string) error {
  237. return x.DumpAllToFile(filePath)
  238. }