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