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.

334 lines
9.3 KiB

10 years ago
10 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
8 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. // Needed for the MySQL driver
  14. _ "github.com/go-sql-driver/mysql"
  15. "github.com/go-xorm/core"
  16. "github.com/go-xorm/xorm"
  17. // Needed for the Postgresql driver
  18. _ "github.com/lib/pq"
  19. // Needed for the MSSSQL driver
  20. _ "github.com/denisenkom/go-mssqldb"
  21. "code.gitea.io/gitea/modules/log"
  22. "code.gitea.io/gitea/modules/setting"
  23. )
  24. // Engine represents a xorm engine or session.
  25. type Engine interface {
  26. Table(tableNameOrBean interface{}) *xorm.Session
  27. Count(interface{}) (int64, error)
  28. Decr(column string, arg ...interface{}) *xorm.Session
  29. Delete(interface{}) (int64, error)
  30. Exec(string, ...interface{}) (sql.Result, error)
  31. Find(interface{}, ...interface{}) error
  32. Get(interface{}) (bool, error)
  33. Id(interface{}) *xorm.Session
  34. In(string, ...interface{}) *xorm.Session
  35. Incr(column string, arg ...interface{}) *xorm.Session
  36. Insert(...interface{}) (int64, error)
  37. InsertOne(interface{}) (int64, error)
  38. Iterate(interface{}, xorm.IterFunc) error
  39. Join(joinOperator string, tablename interface{}, condition string, args ...interface{}) *xorm.Session
  40. SQL(interface{}, ...interface{}) *xorm.Session
  41. Where(interface{}, ...interface{}) *xorm.Session
  42. }
  43. var (
  44. x *xorm.Engine
  45. tables []interface{}
  46. // HasEngine specifies if we have a xorm.Engine
  47. HasEngine bool
  48. // DbCfg holds the database settings
  49. DbCfg struct {
  50. Type, Host, Name, User, Passwd, Path, SSLMode string
  51. Timeout int
  52. }
  53. // EnableSQLite3 use SQLite3
  54. EnableSQLite3 bool
  55. // EnableTiDB enable TiDB
  56. EnableTiDB bool
  57. )
  58. func init() {
  59. tables = append(tables,
  60. new(User),
  61. new(PublicKey),
  62. new(AccessToken),
  63. new(Repository),
  64. new(DeployKey),
  65. new(Collaboration),
  66. new(Access),
  67. new(Upload),
  68. new(Watch),
  69. new(Star),
  70. new(Follow),
  71. new(Action),
  72. new(Issue),
  73. new(PullRequest),
  74. new(Comment),
  75. new(Attachment),
  76. new(Label),
  77. new(IssueLabel),
  78. new(Milestone),
  79. new(Mirror),
  80. new(Release),
  81. new(LoginSource),
  82. new(Webhook),
  83. new(HookTask),
  84. new(Team),
  85. new(OrgUser),
  86. new(TeamUser),
  87. new(TeamRepo),
  88. new(Notice),
  89. new(EmailAddress),
  90. new(Notification),
  91. new(IssueUser),
  92. new(LFSMetaObject),
  93. new(TwoFactor),
  94. new(GPGKey),
  95. new(RepoUnit),
  96. new(RepoRedirect),
  97. new(ExternalLoginUser),
  98. new(ProtectedBranch),
  99. new(UserOpenID),
  100. new(IssueWatch),
  101. new(CommitStatus),
  102. )
  103. gonicNames := []string{"SSL", "UID"}
  104. for _, name := range gonicNames {
  105. core.LintGonicMapper[name] = true
  106. }
  107. }
  108. // LoadConfigs loads the database settings
  109. func LoadConfigs() {
  110. sec := setting.Cfg.Section("database")
  111. DbCfg.Type = sec.Key("DB_TYPE").String()
  112. switch DbCfg.Type {
  113. case "sqlite3":
  114. setting.UseSQLite3 = true
  115. case "mysql":
  116. setting.UseMySQL = true
  117. case "postgres":
  118. setting.UsePostgreSQL = true
  119. case "tidb":
  120. setting.UseTiDB = true
  121. case "mssql":
  122. setting.UseMSSQL = true
  123. }
  124. DbCfg.Host = sec.Key("HOST").String()
  125. DbCfg.Name = sec.Key("NAME").String()
  126. DbCfg.User = sec.Key("USER").String()
  127. if len(DbCfg.Passwd) == 0 {
  128. DbCfg.Passwd = sec.Key("PASSWD").String()
  129. }
  130. DbCfg.SSLMode = sec.Key("SSL_MODE").String()
  131. DbCfg.Path = sec.Key("PATH").MustString("data/gitea.db")
  132. DbCfg.Timeout = sec.Key("SQLITE_TIMEOUT").MustInt(500)
  133. sec = setting.Cfg.Section("indexer")
  134. setting.Indexer.IssuePath = sec.Key("ISSUE_INDEXER_PATH").MustString("indexers/issues.bleve")
  135. setting.Indexer.UpdateQueueLength = sec.Key("UPDATE_BUFFER_LEN").MustInt(20)
  136. }
  137. // parsePostgreSQLHostPort parses given input in various forms defined in
  138. // https://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING
  139. // and returns proper host and port number.
  140. func parsePostgreSQLHostPort(info string) (string, string) {
  141. host, port := "127.0.0.1", "5432"
  142. if strings.Contains(info, ":") && !strings.HasSuffix(info, "]") {
  143. idx := strings.LastIndex(info, ":")
  144. host = info[:idx]
  145. port = info[idx+1:]
  146. } else if len(info) > 0 {
  147. host = info
  148. }
  149. return host, port
  150. }
  151. func parseMSSQLHostPort(info string) (string, string) {
  152. host, port := "127.0.0.1", "1433"
  153. if strings.Contains(info, ":") {
  154. host = strings.Split(info, ":")[0]
  155. port = strings.Split(info, ":")[1]
  156. } else if strings.Contains(info, ",") {
  157. host = strings.Split(info, ",")[0]
  158. port = strings.TrimSpace(strings.Split(info, ",")[1])
  159. } else if len(info) > 0 {
  160. host = info
  161. }
  162. return host, port
  163. }
  164. func getEngine() (*xorm.Engine, error) {
  165. connStr := ""
  166. var Param = "?"
  167. if strings.Contains(DbCfg.Name, Param) {
  168. Param = "&"
  169. }
  170. switch DbCfg.Type {
  171. case "mysql":
  172. if DbCfg.Host[0] == '/' { // looks like a unix socket
  173. connStr = fmt.Sprintf("%s:%s@unix(%s)/%s%scharset=utf8&parseTime=true",
  174. DbCfg.User, DbCfg.Passwd, DbCfg.Host, DbCfg.Name, Param)
  175. } else {
  176. connStr = fmt.Sprintf("%s:%s@tcp(%s)/%s%scharset=utf8&parseTime=true",
  177. DbCfg.User, DbCfg.Passwd, DbCfg.Host, DbCfg.Name, Param)
  178. }
  179. case "postgres":
  180. host, port := parsePostgreSQLHostPort(DbCfg.Host)
  181. if host[0] == '/' { // looks like a unix socket
  182. connStr = fmt.Sprintf("postgres://%s:%s@:%s/%s%ssslmode=%s&host=%s",
  183. url.QueryEscape(DbCfg.User), url.QueryEscape(DbCfg.Passwd), port, DbCfg.Name, Param, DbCfg.SSLMode, host)
  184. } else {
  185. connStr = fmt.Sprintf("postgres://%s:%s@%s:%s/%s%ssslmode=%s",
  186. url.QueryEscape(DbCfg.User), url.QueryEscape(DbCfg.Passwd), host, port, DbCfg.Name, Param, DbCfg.SSLMode)
  187. }
  188. case "mssql":
  189. host, port := parseMSSQLHostPort(DbCfg.Host)
  190. connStr = fmt.Sprintf("server=%s; port=%s; database=%s; user id=%s; password=%s;", host, port, DbCfg.Name, DbCfg.User, DbCfg.Passwd)
  191. case "sqlite3":
  192. if !EnableSQLite3 {
  193. return nil, errors.New("this binary version does not build support for SQLite3")
  194. }
  195. if err := os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm); err != nil {
  196. return nil, fmt.Errorf("Failed to create directories: %v", err)
  197. }
  198. connStr = fmt.Sprintf("file:%s?cache=shared&mode=rwc&_busy_timeout=%d", DbCfg.Path, DbCfg.Timeout)
  199. case "tidb":
  200. if !EnableTiDB {
  201. return nil, errors.New("this binary version does not build support for TiDB")
  202. }
  203. if err := os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm); err != nil {
  204. return nil, fmt.Errorf("Failed to create directories: %v", err)
  205. }
  206. connStr = "goleveldb://" + DbCfg.Path
  207. default:
  208. return nil, fmt.Errorf("Unknown database type: %s", DbCfg.Type)
  209. }
  210. return xorm.NewEngine(DbCfg.Type, connStr)
  211. }
  212. // NewTestEngine sets a new test xorm.Engine
  213. func NewTestEngine(x *xorm.Engine) (err error) {
  214. x, err = getEngine()
  215. if err != nil {
  216. return fmt.Errorf("Connect to database: %v", err)
  217. }
  218. x.SetMapper(core.GonicMapper{})
  219. x.SetLogger(log.XORMLogger)
  220. return x.StoreEngine("InnoDB").Sync2(tables...)
  221. }
  222. // SetEngine sets the xorm.Engine
  223. func SetEngine() (err error) {
  224. x, err = getEngine()
  225. if err != nil {
  226. return fmt.Errorf("Failed to connect to database: %v", err)
  227. }
  228. x.SetMapper(core.GonicMapper{})
  229. // WARNING: for serv command, MUST remove the output to os.stdout,
  230. // so use log file to instead print to stdout.
  231. x.SetLogger(log.XORMLogger)
  232. x.ShowSQL(true)
  233. return nil
  234. }
  235. // NewEngine initializes a new xorm.Engine
  236. func NewEngine(migrateFunc func(*xorm.Engine) error) (err error) {
  237. if err = SetEngine(); err != nil {
  238. return err
  239. }
  240. if err = x.Ping(); err != nil {
  241. return err
  242. }
  243. if err = migrateFunc(x); err != nil {
  244. return fmt.Errorf("migrate: %v", err)
  245. }
  246. if err = x.StoreEngine("InnoDB").Sync2(tables...); err != nil {
  247. return fmt.Errorf("sync database struct error: %v", err)
  248. }
  249. return nil
  250. }
  251. // Statistic contains the database statistics
  252. type Statistic struct {
  253. Counter struct {
  254. User, Org, PublicKey,
  255. Repo, Watch, Star, Action, Access,
  256. Issue, Comment, Oauth, Follow,
  257. Mirror, Release, LoginSource, Webhook,
  258. Milestone, Label, HookTask,
  259. Team, UpdateTask, Attachment int64
  260. }
  261. }
  262. // GetStatistic returns the database statistics
  263. func GetStatistic() (stats Statistic) {
  264. stats.Counter.User = CountUsers()
  265. stats.Counter.Org = CountOrganizations()
  266. stats.Counter.PublicKey, _ = x.Count(new(PublicKey))
  267. stats.Counter.Repo = CountRepositories(true)
  268. stats.Counter.Watch, _ = x.Count(new(Watch))
  269. stats.Counter.Star, _ = x.Count(new(Star))
  270. stats.Counter.Action, _ = x.Count(new(Action))
  271. stats.Counter.Access, _ = x.Count(new(Access))
  272. stats.Counter.Issue, _ = x.Count(new(Issue))
  273. stats.Counter.Comment, _ = x.Count(new(Comment))
  274. stats.Counter.Oauth = 0
  275. stats.Counter.Follow, _ = x.Count(new(Follow))
  276. stats.Counter.Mirror, _ = x.Count(new(Mirror))
  277. stats.Counter.Release, _ = x.Count(new(Release))
  278. stats.Counter.LoginSource = CountLoginSources()
  279. stats.Counter.Webhook, _ = x.Count(new(Webhook))
  280. stats.Counter.Milestone, _ = x.Count(new(Milestone))
  281. stats.Counter.Label, _ = x.Count(new(Label))
  282. stats.Counter.HookTask, _ = x.Count(new(HookTask))
  283. stats.Counter.Team, _ = x.Count(new(Team))
  284. stats.Counter.Attachment, _ = x.Count(new(Attachment))
  285. return
  286. }
  287. // Ping tests if database is alive
  288. func Ping() error {
  289. return x.Ping()
  290. }
  291. // DumpDatabase dumps all data from database according the special database SQL syntax to file system.
  292. func DumpDatabase(filePath string, dbType string) error {
  293. var tbs []*core.Table
  294. for _, t := range tables {
  295. tbs = append(tbs, x.TableInfo(t).Table)
  296. }
  297. if len(dbType) > 0 {
  298. return x.DumpTablesToFile(tbs, filePath, core.DbType(dbType))
  299. }
  300. return x.DumpTablesToFile(tbs, filePath)
  301. }