You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

models.go 9.4 kB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
9 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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. Delete(interface{}) (int64, error)
  27. Exec(string, ...interface{}) (sql.Result, error)
  28. Find(interface{}, ...interface{}) error
  29. Get(interface{}) (bool, error)
  30. Id(interface{}) *xorm.Session
  31. In(string, ...interface{}) *xorm.Session
  32. Insert(...interface{}) (int64, error)
  33. InsertOne(interface{}) (int64, error)
  34. Iterate(interface{}, xorm.IterFunc) error
  35. SQL(interface{}, ...interface{}) *xorm.Session
  36. Where(interface{}, ...interface{}) *xorm.Session
  37. }
  38. func sessionRelease(sess *xorm.Session) {
  39. if !sess.IsCommitedOrRollbacked {
  40. sess.Rollback()
  41. }
  42. sess.Close()
  43. }
  44. var (
  45. x *xorm.Engine
  46. tables []interface{}
  47. // HasEngine specifies if we have a xorm.Engine
  48. HasEngine bool
  49. // DbCfg holds the database settings
  50. DbCfg struct {
  51. Type, Host, Name, User, Passwd, Path, SSLMode string
  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(UpdateTask),
  84. new(HookTask),
  85. new(Team),
  86. new(OrgUser),
  87. new(TeamUser),
  88. new(TeamRepo),
  89. new(Notice),
  90. new(EmailAddress),
  91. new(Notification),
  92. new(IssueUser),
  93. new(LFSMetaObject),
  94. new(TwoFactor),
  95. new(RepoUnit),
  96. )
  97. gonicNames := []string{"SSL", "UID"}
  98. for _, name := range gonicNames {
  99. core.LintGonicMapper[name] = true
  100. }
  101. }
  102. // LoadConfigs loads the database settings
  103. func LoadConfigs() {
  104. sec := setting.Cfg.Section("database")
  105. DbCfg.Type = sec.Key("DB_TYPE").String()
  106. switch DbCfg.Type {
  107. case "sqlite3":
  108. setting.UseSQLite3 = true
  109. case "mysql":
  110. setting.UseMySQL = true
  111. case "postgres":
  112. setting.UsePostgreSQL = true
  113. case "tidb":
  114. setting.UseTiDB = true
  115. case "mssql":
  116. setting.UseMSSQL = true
  117. }
  118. DbCfg.Host = sec.Key("HOST").String()
  119. DbCfg.Name = sec.Key("NAME").String()
  120. DbCfg.User = sec.Key("USER").String()
  121. if len(DbCfg.Passwd) == 0 {
  122. DbCfg.Passwd = sec.Key("PASSWD").String()
  123. }
  124. DbCfg.SSLMode = sec.Key("SSL_MODE").String()
  125. DbCfg.Path = sec.Key("PATH").MustString("data/gitea.db")
  126. sec = setting.Cfg.Section("indexer")
  127. setting.Indexer.IssuePath = sec.Key("ISSUE_INDEXER_PATH").MustString("indexers/issues.bleve")
  128. setting.Indexer.UpdateQueueLength = sec.Key("UPDATE_BUFFER_LEN").MustInt(20)
  129. }
  130. // parsePostgreSQLHostPort parses given input in various forms defined in
  131. // https://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING
  132. // and returns proper host and port number.
  133. func parsePostgreSQLHostPort(info string) (string, string) {
  134. host, port := "127.0.0.1", "5432"
  135. if strings.Contains(info, ":") && !strings.HasSuffix(info, "]") {
  136. idx := strings.LastIndex(info, ":")
  137. host = info[:idx]
  138. port = info[idx+1:]
  139. } else if len(info) > 0 {
  140. host = info
  141. }
  142. return host, port
  143. }
  144. func parseMSSQLHostPort(info string) (string, string) {
  145. host, port := "127.0.0.1", "1433"
  146. if strings.Contains(info, ":") {
  147. host = strings.Split(info, ":")[0]
  148. port = strings.Split(info, ":")[1]
  149. } else if strings.Contains(info, ",") {
  150. host = strings.Split(info, ",")[0]
  151. port = strings.TrimSpace(strings.Split(info, ",")[1])
  152. } else if len(info) > 0 {
  153. host = info
  154. }
  155. return host, port
  156. }
  157. func getEngine() (*xorm.Engine, error) {
  158. connStr := ""
  159. var Param = "?"
  160. if strings.Contains(DbCfg.Name, Param) {
  161. Param = "&"
  162. }
  163. switch DbCfg.Type {
  164. case "mysql":
  165. if DbCfg.Host[0] == '/' { // looks like a unix socket
  166. connStr = fmt.Sprintf("%s:%s@unix(%s)/%s%scharset=utf8&parseTime=true",
  167. DbCfg.User, DbCfg.Passwd, DbCfg.Host, DbCfg.Name, Param)
  168. } else {
  169. connStr = fmt.Sprintf("%s:%s@tcp(%s)/%s%scharset=utf8&parseTime=true",
  170. DbCfg.User, DbCfg.Passwd, DbCfg.Host, DbCfg.Name, Param)
  171. }
  172. case "postgres":
  173. host, port := parsePostgreSQLHostPort(DbCfg.Host)
  174. if host[0] == '/' { // looks like a unix socket
  175. connStr = fmt.Sprintf("postgres://%s:%s@:%s/%s%ssslmode=%s&host=%s",
  176. url.QueryEscape(DbCfg.User), url.QueryEscape(DbCfg.Passwd), port, DbCfg.Name, Param, DbCfg.SSLMode, host)
  177. } else {
  178. connStr = fmt.Sprintf("postgres://%s:%s@%s:%s/%s%ssslmode=%s",
  179. url.QueryEscape(DbCfg.User), url.QueryEscape(DbCfg.Passwd), host, port, DbCfg.Name, Param, DbCfg.SSLMode)
  180. }
  181. case "mssql":
  182. host, port := parseMSSQLHostPort(DbCfg.Host)
  183. connStr = fmt.Sprintf("server=%s; port=%s; database=%s; user id=%s; password=%s;", host, port, DbCfg.Name, DbCfg.User, DbCfg.Passwd)
  184. case "sqlite3":
  185. if !EnableSQLite3 {
  186. return nil, errors.New("this binary version does not build support for SQLite3")
  187. }
  188. if err := os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm); err != nil {
  189. return nil, fmt.Errorf("Failed to create directories: %v", err)
  190. }
  191. connStr = "file:" + DbCfg.Path + "?cache=shared&mode=rwc"
  192. case "tidb":
  193. if !EnableTiDB {
  194. return nil, errors.New("this binary version does not build support for TiDB")
  195. }
  196. if err := os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm); err != nil {
  197. return nil, fmt.Errorf("Failed to create directories: %v", err)
  198. }
  199. connStr = "goleveldb://" + DbCfg.Path
  200. default:
  201. return nil, fmt.Errorf("Unknown database type: %s", DbCfg.Type)
  202. }
  203. return xorm.NewEngine(DbCfg.Type, connStr)
  204. }
  205. // NewTestEngine sets a new test xorm.Engine
  206. func NewTestEngine(x *xorm.Engine) (err error) {
  207. x, err = getEngine()
  208. if err != nil {
  209. return fmt.Errorf("Connect to database: %v", err)
  210. }
  211. x.SetMapper(core.GonicMapper{})
  212. return x.StoreEngine("InnoDB").Sync2(tables...)
  213. }
  214. // SetEngine sets the xorm.Engine
  215. func SetEngine() (err error) {
  216. x, err = getEngine()
  217. if err != nil {
  218. return fmt.Errorf("Failed to connect to database: %v", err)
  219. }
  220. x.SetMapper(core.GonicMapper{})
  221. // WARNING: for serv command, MUST remove the output to os.stdout,
  222. // so use log file to instead print to stdout.
  223. logPath := path.Join(setting.LogRootPath, "xorm.log")
  224. if err := os.MkdirAll(path.Dir(logPath), os.ModePerm); err != nil {
  225. return fmt.Errorf("Failed to create dir %s: %v", logPath, err)
  226. }
  227. f, err := os.Create(logPath)
  228. if err != nil {
  229. return fmt.Errorf("Failed to create xorm.log: %v", err)
  230. }
  231. x.SetLogger(xorm.NewSimpleLogger(f))
  232. x.ShowSQL(true)
  233. return nil
  234. }
  235. // NewEngine initializes a new xorm.Engine
  236. func NewEngine() (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 = migrations.Migrate(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.UpdateTask, _ = x.Count(new(UpdateTask))
  285. stats.Counter.Attachment, _ = x.Count(new(Attachment))
  286. return
  287. }
  288. // Ping tests if database is alive
  289. func Ping() error {
  290. return x.Ping()
  291. }
  292. // DumpDatabase dumps all data from database according the special database SQL syntax to file system.
  293. func DumpDatabase(filePath string, dbType string) error {
  294. var tbs []*core.Table
  295. for _, t := range tables {
  296. tbs = append(tbs, x.TableInfo(t).Table)
  297. }
  298. if len(dbType) > 0 {
  299. return x.DumpTablesToFile(tbs, filePath, core.DbType(dbType))
  300. }
  301. return x.DumpTablesToFile(tbs, filePath)
  302. }