Fork to maintain patches against the official gitea for https://code.ceondo.com https://github.com/go-gitea/gitea

models.go 9.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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/log"
  23. "code.gitea.io/gitea/modules/setting"
  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. func sessionRelease(sess *xorm.Session) {
  45. if !sess.IsCommitedOrRollbacked {
  46. sess.Rollback()
  47. }
  48. sess.Close()
  49. }
  50. var (
  51. x *xorm.Engine
  52. tables []interface{}
  53. // HasEngine specifies if we have a xorm.Engine
  54. HasEngine bool
  55. // DbCfg holds the database settings
  56. DbCfg struct {
  57. Type, Host, Name, User, Passwd, Path, SSLMode string
  58. }
  59. // EnableSQLite3 use SQLite3
  60. EnableSQLite3 bool
  61. // EnableTiDB enable TiDB
  62. EnableTiDB bool
  63. )
  64. func init() {
  65. tables = append(tables,
  66. new(User),
  67. new(PublicKey),
  68. new(AccessToken),
  69. new(Repository),
  70. new(DeployKey),
  71. new(Collaboration),
  72. new(Access),
  73. new(Upload),
  74. new(Watch),
  75. new(Star),
  76. new(Follow),
  77. new(Action),
  78. new(Issue),
  79. new(PullRequest),
  80. new(Comment),
  81. new(Attachment),
  82. new(Label),
  83. new(IssueLabel),
  84. new(Milestone),
  85. new(Mirror),
  86. new(Release),
  87. new(LoginSource),
  88. new(Webhook),
  89. new(UpdateTask),
  90. new(HookTask),
  91. new(Team),
  92. new(OrgUser),
  93. new(TeamUser),
  94. new(TeamRepo),
  95. new(Notice),
  96. new(EmailAddress),
  97. new(Notification),
  98. new(IssueUser),
  99. new(LFSMetaObject),
  100. new(TwoFactor),
  101. new(RepoUnit),
  102. new(RepoRedirect),
  103. new(ExternalLoginUser),
  104. new(ProtectedBranch),
  105. )
  106. gonicNames := []string{"SSL", "UID"}
  107. for _, name := range gonicNames {
  108. core.LintGonicMapper[name] = true
  109. }
  110. }
  111. // LoadConfigs loads the database settings
  112. func LoadConfigs() {
  113. sec := setting.Cfg.Section("database")
  114. DbCfg.Type = sec.Key("DB_TYPE").String()
  115. switch DbCfg.Type {
  116. case "sqlite3":
  117. setting.UseSQLite3 = true
  118. case "mysql":
  119. setting.UseMySQL = true
  120. case "postgres":
  121. setting.UsePostgreSQL = true
  122. case "tidb":
  123. setting.UseTiDB = true
  124. case "mssql":
  125. setting.UseMSSQL = true
  126. }
  127. DbCfg.Host = sec.Key("HOST").String()
  128. DbCfg.Name = sec.Key("NAME").String()
  129. DbCfg.User = sec.Key("USER").String()
  130. if len(DbCfg.Passwd) == 0 {
  131. DbCfg.Passwd = sec.Key("PASSWD").String()
  132. }
  133. DbCfg.SSLMode = sec.Key("SSL_MODE").String()
  134. DbCfg.Path = sec.Key("PATH").MustString("data/gitea.db")
  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 = "file:" + DbCfg.Path + "?cache=shared&mode=rwc"
  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. setting.NewXORMLogService(false)
  221. x.SetMapper(core.GonicMapper{})
  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() (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 = migrations.Migrate(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.UpdateTask, _ = x.Count(new(UpdateTask))
  287. stats.Counter.Attachment, _ = x.Count(new(Attachment))
  288. return
  289. }
  290. // Ping tests if database is alive
  291. func Ping() error {
  292. return x.Ping()
  293. }
  294. // DumpDatabase dumps all data from database according the special database SQL syntax to file system.
  295. func DumpDatabase(filePath string, dbType string) error {
  296. var tbs []*core.Table
  297. for _, t := range tables {
  298. tbs = append(tbs, x.TableInfo(t).Table)
  299. }
  300. if len(dbType) > 0 {
  301. return x.DumpTablesToFile(tbs, filePath, core.DbType(dbType))
  302. }
  303. return x.DumpTablesToFile(tbs, filePath)
  304. }