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.1KB

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