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