Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

models.go 9.2KB

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