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.

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