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

models.go 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2018 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package models
  6. import (
  7. "database/sql"
  8. "errors"
  9. "fmt"
  10. "net/url"
  11. "os"
  12. "path"
  13. "path/filepath"
  14. "strings"
  15. "code.gitea.io/gitea/modules/log"
  16. "code.gitea.io/gitea/modules/setting"
  17. // Needed for the MySQL driver
  18. _ "github.com/go-sql-driver/mysql"
  19. "github.com/go-xorm/core"
  20. "github.com/go-xorm/xorm"
  21. // Needed for the Postgresql driver
  22. _ "github.com/lib/pq"
  23. // Needed for the MSSSQL driver
  24. _ "github.com/denisenkom/go-mssqldb"
  25. )
  26. // Engine represents a xorm engine or session.
  27. type Engine interface {
  28. Table(tableNameOrBean interface{}) *xorm.Session
  29. Count(...interface{}) (int64, error)
  30. Decr(column string, arg ...interface{}) *xorm.Session
  31. Delete(interface{}) (int64, error)
  32. Exec(...interface{}) (sql.Result, error)
  33. Find(interface{}, ...interface{}) error
  34. Get(interface{}) (bool, error)
  35. ID(interface{}) *xorm.Session
  36. In(string, ...interface{}) *xorm.Session
  37. Incr(column string, arg ...interface{}) *xorm.Session
  38. Insert(...interface{}) (int64, error)
  39. InsertOne(interface{}) (int64, error)
  40. Iterate(interface{}, xorm.IterFunc) error
  41. Join(joinOperator string, tablename interface{}, condition string, args ...interface{}) *xorm.Session
  42. SQL(interface{}, ...interface{}) *xorm.Session
  43. Where(interface{}, ...interface{}) *xorm.Session
  44. }
  45. var (
  46. x *xorm.Engine
  47. tables []interface{}
  48. // HasEngine specifies if we have a xorm.Engine
  49. HasEngine bool
  50. // DbCfg holds the database settings
  51. DbCfg struct {
  52. Type, Host, Name, User, Passwd, Path, SSLMode string
  53. Timeout int
  54. }
  55. // EnableSQLite3 use SQLite3
  56. EnableSQLite3 bool
  57. // EnableTiDB enable TiDB
  58. EnableTiDB bool
  59. )
  60. func init() {
  61. tables = append(tables,
  62. new(User),
  63. new(PublicKey),
  64. new(AccessToken),
  65. new(Repository),
  66. new(DeployKey),
  67. new(Collaboration),
  68. new(Access),
  69. new(Upload),
  70. new(Watch),
  71. new(Star),
  72. new(Follow),
  73. new(Action),
  74. new(Issue),
  75. new(PullRequest),
  76. new(Comment),
  77. new(Attachment),
  78. new(Label),
  79. new(IssueLabel),
  80. new(Milestone),
  81. new(Mirror),
  82. new(Release),
  83. new(LoginSource),
  84. new(Webhook),
  85. new(HookTask),
  86. new(Team),
  87. new(OrgUser),
  88. new(TeamUser),
  89. new(TeamRepo),
  90. new(Notice),
  91. new(EmailAddress),
  92. new(Notification),
  93. new(IssueUser),
  94. new(LFSMetaObject),
  95. new(TwoFactor),
  96. new(GPGKey),
  97. new(RepoUnit),
  98. new(RepoRedirect),
  99. new(ExternalLoginUser),
  100. new(ProtectedBranch),
  101. new(UserOpenID),
  102. new(IssueWatch),
  103. new(CommitStatus),
  104. new(Stopwatch),
  105. new(TrackedTime),
  106. new(DeletedBranch),
  107. new(RepoIndexerStatus),
  108. new(IssueDependency),
  109. new(LFSLock),
  110. new(Reaction),
  111. new(IssueAssignees),
  112. new(U2FRegistration),
  113. new(TeamUnit),
  114. new(Review),
  115. )
  116. gonicNames := []string{"SSL", "UID"}
  117. for _, name := range gonicNames {
  118. core.LintGonicMapper[name] = true
  119. }
  120. }
  121. // LoadConfigs loads the database settings
  122. func LoadConfigs() {
  123. sec := setting.Cfg.Section("database")
  124. DbCfg.Type = sec.Key("DB_TYPE").String()
  125. switch DbCfg.Type {
  126. case "sqlite3":
  127. setting.UseSQLite3 = true
  128. case "mysql":
  129. setting.UseMySQL = true
  130. case "postgres":
  131. setting.UsePostgreSQL = true
  132. case "tidb":
  133. setting.UseTiDB = true
  134. case "mssql":
  135. setting.UseMSSQL = true
  136. }
  137. DbCfg.Host = sec.Key("HOST").String()
  138. DbCfg.Name = sec.Key("NAME").String()
  139. DbCfg.User = sec.Key("USER").String()
  140. if len(DbCfg.Passwd) == 0 {
  141. DbCfg.Passwd = sec.Key("PASSWD").String()
  142. }
  143. DbCfg.SSLMode = sec.Key("SSL_MODE").MustString("disable")
  144. DbCfg.Path = sec.Key("PATH").MustString("data/gitea.db")
  145. DbCfg.Timeout = sec.Key("SQLITE_TIMEOUT").MustInt(500)
  146. sec = setting.Cfg.Section("indexer")
  147. setting.Indexer.IssuePath = sec.Key("ISSUE_INDEXER_PATH").MustString(path.Join(setting.AppDataPath, "indexers/issues.bleve"))
  148. if !filepath.IsAbs(setting.Indexer.IssuePath) {
  149. setting.Indexer.IssuePath = path.Join(setting.AppWorkPath, setting.Indexer.IssuePath)
  150. }
  151. setting.Indexer.RepoIndexerEnabled = sec.Key("REPO_INDEXER_ENABLED").MustBool(false)
  152. setting.Indexer.RepoPath = sec.Key("REPO_INDEXER_PATH").MustString(path.Join(setting.AppDataPath, "indexers/repos.bleve"))
  153. if !filepath.IsAbs(setting.Indexer.RepoPath) {
  154. setting.Indexer.RepoPath = path.Join(setting.AppWorkPath, setting.Indexer.RepoPath)
  155. }
  156. setting.Indexer.UpdateQueueLength = sec.Key("UPDATE_BUFFER_LEN").MustInt(20)
  157. setting.Indexer.MaxIndexerFileSize = sec.Key("MAX_FILE_SIZE").MustInt64(1024 * 1024)
  158. }
  159. // parsePostgreSQLHostPort parses given input in various forms defined in
  160. // https://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING
  161. // and returns proper host and port number.
  162. func parsePostgreSQLHostPort(info string) (string, string) {
  163. host, port := "127.0.0.1", "5432"
  164. if strings.Contains(info, ":") && !strings.HasSuffix(info, "]") {
  165. idx := strings.LastIndex(info, ":")
  166. host = info[:idx]
  167. port = info[idx+1:]
  168. } else if len(info) > 0 {
  169. host = info
  170. }
  171. return host, port
  172. }
  173. func getPostgreSQLConnectionString(DBHost, DBUser, DBPasswd, DBName, DBParam, DBSSLMode string) (connStr string) {
  174. host, port := parsePostgreSQLHostPort(DBHost)
  175. if host[0] == '/' { // looks like a unix socket
  176. connStr = fmt.Sprintf("postgres://%s:%s@:%s/%s%ssslmode=%s&host=%s",
  177. url.PathEscape(DBUser), url.PathEscape(DBPasswd), port, DBName, DBParam, DBSSLMode, host)
  178. } else {
  179. connStr = fmt.Sprintf("postgres://%s:%s@%s:%s/%s%ssslmode=%s",
  180. url.PathEscape(DBUser), url.PathEscape(DBPasswd), host, port, DBName, DBParam, DBSSLMode)
  181. }
  182. return
  183. }
  184. // ParseMSSQLHostPort splits the host into host and port
  185. func ParseMSSQLHostPort(info string) (string, string) {
  186. host, port := "127.0.0.1", "1433"
  187. if strings.Contains(info, ":") {
  188. host = strings.Split(info, ":")[0]
  189. port = strings.Split(info, ":")[1]
  190. } else if strings.Contains(info, ",") {
  191. host = strings.Split(info, ",")[0]
  192. port = strings.TrimSpace(strings.Split(info, ",")[1])
  193. } else if len(info) > 0 {
  194. host = info
  195. }
  196. return host, port
  197. }
  198. func getEngine() (*xorm.Engine, error) {
  199. connStr := ""
  200. var Param = "?"
  201. if strings.Contains(DbCfg.Name, Param) {
  202. Param = "&"
  203. }
  204. switch DbCfg.Type {
  205. case "mysql":
  206. connType := "tcp"
  207. if DbCfg.Host[0] == '/' { // looks like a unix socket
  208. connType = "unix"
  209. }
  210. tls := DbCfg.SSLMode
  211. if tls == "disable" { // allow (Postgres-inspired) default value to work in MySQL
  212. tls = "false"
  213. }
  214. connStr = fmt.Sprintf("%s:%s@%s(%s)/%s%scharset=utf8&parseTime=true&tls=%s",
  215. DbCfg.User, DbCfg.Passwd, connType, DbCfg.Host, DbCfg.Name, Param, tls)
  216. case "postgres":
  217. connStr = getPostgreSQLConnectionString(DbCfg.Host, DbCfg.User, DbCfg.Passwd, DbCfg.Name, Param, DbCfg.SSLMode)
  218. case "mssql":
  219. host, port := ParseMSSQLHostPort(DbCfg.Host)
  220. connStr = fmt.Sprintf("server=%s; port=%s; database=%s; user id=%s; password=%s;", host, port, DbCfg.Name, DbCfg.User, DbCfg.Passwd)
  221. case "sqlite3":
  222. if !EnableSQLite3 {
  223. return nil, errors.New("this binary version does not build support for SQLite3")
  224. }
  225. if err := os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm); err != nil {
  226. return nil, fmt.Errorf("Failed to create directories: %v", err)
  227. }
  228. connStr = fmt.Sprintf("file:%s?cache=shared&mode=rwc&_busy_timeout=%d", DbCfg.Path, DbCfg.Timeout)
  229. case "tidb":
  230. if !EnableTiDB {
  231. return nil, errors.New("this binary version does not build support for TiDB")
  232. }
  233. if err := os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm); err != nil {
  234. return nil, fmt.Errorf("Failed to create directories: %v", err)
  235. }
  236. connStr = "goleveldb://" + DbCfg.Path
  237. default:
  238. return nil, fmt.Errorf("Unknown database type: %s", DbCfg.Type)
  239. }
  240. return xorm.NewEngine(DbCfg.Type, connStr)
  241. }
  242. // NewTestEngine sets a new test xorm.Engine
  243. func NewTestEngine(x *xorm.Engine) (err error) {
  244. x, err = getEngine()
  245. if err != nil {
  246. return fmt.Errorf("Connect to database: %v", err)
  247. }
  248. x.SetMapper(core.GonicMapper{})
  249. x.SetLogger(log.XORMLogger)
  250. x.ShowSQL(!setting.ProdMode)
  251. return x.StoreEngine("InnoDB").Sync2(tables...)
  252. }
  253. // SetEngine sets the xorm.Engine
  254. func SetEngine() (err error) {
  255. x, err = getEngine()
  256. if err != nil {
  257. return fmt.Errorf("Failed to connect to database: %v", err)
  258. }
  259. x.SetMapper(core.GonicMapper{})
  260. // WARNING: for serv command, MUST remove the output to os.stdout,
  261. // so use log file to instead print to stdout.
  262. x.SetLogger(log.XORMLogger)
  263. x.ShowSQL(setting.LogSQL)
  264. return nil
  265. }
  266. // NewEngine initializes a new xorm.Engine
  267. func NewEngine(migrateFunc func(*xorm.Engine) error) (err error) {
  268. if err = SetEngine(); err != nil {
  269. return err
  270. }
  271. if err = x.Ping(); err != nil {
  272. return err
  273. }
  274. if err = migrateFunc(x); err != nil {
  275. return fmt.Errorf("migrate: %v", err)
  276. }
  277. if err = x.StoreEngine("InnoDB").Sync2(tables...); err != nil {
  278. return fmt.Errorf("sync database struct error: %v", err)
  279. }
  280. return nil
  281. }
  282. // Statistic contains the database statistics
  283. type Statistic struct {
  284. Counter struct {
  285. User, Org, PublicKey,
  286. Repo, Watch, Star, Action, Access,
  287. Issue, Comment, Oauth, Follow,
  288. Mirror, Release, LoginSource, Webhook,
  289. Milestone, Label, HookTask,
  290. Team, UpdateTask, Attachment int64
  291. }
  292. }
  293. // GetStatistic returns the database statistics
  294. func GetStatistic() (stats Statistic) {
  295. stats.Counter.User = CountUsers()
  296. stats.Counter.Org = CountOrganizations()
  297. stats.Counter.PublicKey, _ = x.Count(new(PublicKey))
  298. stats.Counter.Repo = CountRepositories(true)
  299. stats.Counter.Watch, _ = x.Count(new(Watch))
  300. stats.Counter.Star, _ = x.Count(new(Star))
  301. stats.Counter.Action, _ = x.Count(new(Action))
  302. stats.Counter.Access, _ = x.Count(new(Access))
  303. stats.Counter.Issue, _ = x.Count(new(Issue))
  304. stats.Counter.Comment, _ = x.Count(new(Comment))
  305. stats.Counter.Oauth = 0
  306. stats.Counter.Follow, _ = x.Count(new(Follow))
  307. stats.Counter.Mirror, _ = x.Count(new(Mirror))
  308. stats.Counter.Release, _ = x.Count(new(Release))
  309. stats.Counter.LoginSource = CountLoginSources()
  310. stats.Counter.Webhook, _ = x.Count(new(Webhook))
  311. stats.Counter.Milestone, _ = x.Count(new(Milestone))
  312. stats.Counter.Label, _ = x.Count(new(Label))
  313. stats.Counter.HookTask, _ = x.Count(new(HookTask))
  314. stats.Counter.Team, _ = x.Count(new(Team))
  315. stats.Counter.Attachment, _ = x.Count(new(Attachment))
  316. return
  317. }
  318. // Ping tests if database is alive
  319. func Ping() error {
  320. if x != nil {
  321. return x.Ping()
  322. }
  323. return errors.New("database not configured")
  324. }
  325. // DumpDatabase dumps all data from database according the special database SQL syntax to file system.
  326. func DumpDatabase(filePath string, dbType string) error {
  327. var tbs []*core.Table
  328. for _, t := range tables {
  329. tbs = append(tbs, x.TableInfo(t).Table)
  330. }
  331. if len(dbType) > 0 {
  332. return x.DumpTablesToFile(tbs, filePath, core.DbType(dbType))
  333. }
  334. return x.DumpTablesToFile(tbs, filePath)
  335. }