Fork to maintain patches against the official gitea for https://code.ceondo.com https://github.com/go-gitea/gitea

models.go 10KB

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