You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

models.go 9.5 kB

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