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

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