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

models.go 8.7KB

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