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

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