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