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 10KB

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