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

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