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

models.go 10KB

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