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.

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