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

models.go 10.0KB

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