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

259 lines
6.5KB

  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2018 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package models
  6. import (
  7. "database/sql"
  8. "errors"
  9. "fmt"
  10. "code.gitea.io/gitea/modules/setting"
  11. // Needed for the MySQL driver
  12. _ "github.com/go-sql-driver/mysql"
  13. "xorm.io/core"
  14. "xorm.io/xorm"
  15. // Needed for the Postgresql driver
  16. _ "github.com/lib/pq"
  17. // Needed for the MSSSQL driver
  18. _ "github.com/denisenkom/go-mssqldb"
  19. )
  20. // Engine represents a xorm engine or session.
  21. type Engine interface {
  22. Table(tableNameOrBean interface{}) *xorm.Session
  23. Count(...interface{}) (int64, error)
  24. Decr(column string, arg ...interface{}) *xorm.Session
  25. Delete(interface{}) (int64, error)
  26. Exec(...interface{}) (sql.Result, error)
  27. Find(interface{}, ...interface{}) error
  28. Get(interface{}) (bool, error)
  29. ID(interface{}) *xorm.Session
  30. In(string, ...interface{}) *xorm.Session
  31. Incr(column string, arg ...interface{}) *xorm.Session
  32. Insert(...interface{}) (int64, error)
  33. InsertOne(interface{}) (int64, error)
  34. Iterate(interface{}, xorm.IterFunc) error
  35. Join(joinOperator string, tablename interface{}, condition string, args ...interface{}) *xorm.Session
  36. SQL(interface{}, ...interface{}) *xorm.Session
  37. Where(interface{}, ...interface{}) *xorm.Session
  38. Asc(colNames ...string) *xorm.Session
  39. }
  40. var (
  41. x *xorm.Engine
  42. tables []interface{}
  43. // HasEngine specifies if we have a xorm.Engine
  44. HasEngine bool
  45. )
  46. func init() {
  47. tables = append(tables,
  48. new(User),
  49. new(PublicKey),
  50. new(AccessToken),
  51. new(Repository),
  52. new(DeployKey),
  53. new(Collaboration),
  54. new(Access),
  55. new(Upload),
  56. new(Watch),
  57. new(Star),
  58. new(Follow),
  59. new(Action),
  60. new(Issue),
  61. new(PullRequest),
  62. new(Comment),
  63. new(Attachment),
  64. new(Label),
  65. new(IssueLabel),
  66. new(Milestone),
  67. new(Mirror),
  68. new(Release),
  69. new(LoginSource),
  70. new(Webhook),
  71. new(HookTask),
  72. new(Team),
  73. new(OrgUser),
  74. new(TeamUser),
  75. new(TeamRepo),
  76. new(Notice),
  77. new(EmailAddress),
  78. new(Notification),
  79. new(IssueUser),
  80. new(LFSMetaObject),
  81. new(TwoFactor),
  82. new(GPGKey),
  83. new(GPGKeyImport),
  84. new(RepoUnit),
  85. new(RepoRedirect),
  86. new(ExternalLoginUser),
  87. new(ProtectedBranch),
  88. new(UserOpenID),
  89. new(IssueWatch),
  90. new(CommitStatus),
  91. new(Stopwatch),
  92. new(TrackedTime),
  93. new(DeletedBranch),
  94. new(RepoIndexerStatus),
  95. new(IssueDependency),
  96. new(LFSLock),
  97. new(Reaction),
  98. new(IssueAssignees),
  99. new(U2FRegistration),
  100. new(TeamUnit),
  101. new(Review),
  102. new(OAuth2Application),
  103. new(OAuth2AuthorizationCode),
  104. new(OAuth2Grant),
  105. new(Task),
  106. new(Transfer),
  107. new(Fund),
  108. )
  109. gonicNames := []string{"SSL", "UID"}
  110. for _, name := range gonicNames {
  111. core.LintGonicMapper[name] = true
  112. }
  113. }
  114. func getEngine() (*xorm.Engine, error) {
  115. connStr, err := setting.DBConnStr()
  116. if err != nil {
  117. return nil, err
  118. }
  119. return xorm.NewEngine(setting.Database.Type, connStr)
  120. }
  121. // NewTestEngine sets a new test xorm.Engine
  122. func NewTestEngine(x *xorm.Engine) (err error) {
  123. x, err = getEngine()
  124. if err != nil {
  125. return fmt.Errorf("Connect to database: %v", err)
  126. }
  127. x.ShowExecTime(true)
  128. x.SetMapper(core.GonicMapper{})
  129. x.SetLogger(NewXORMLogger(!setting.ProdMode))
  130. x.ShowSQL(!setting.ProdMode)
  131. return x.StoreEngine("InnoDB").Sync2(tables...)
  132. }
  133. // SetEngine sets the xorm.Engine
  134. func SetEngine() (err error) {
  135. x, err = getEngine()
  136. if err != nil {
  137. return fmt.Errorf("Failed to connect to database: %v", err)
  138. }
  139. x.ShowExecTime(true)
  140. x.SetMapper(core.GonicMapper{})
  141. // WARNING: for serv command, MUST remove the output to os.stdout,
  142. // so use log file to instead print to stdout.
  143. x.SetLogger(NewXORMLogger(setting.Database.LogSQL))
  144. x.ShowSQL(setting.Database.LogSQL)
  145. x.SetMaxOpenConns(setting.Database.MaxOpenConns)
  146. x.SetMaxIdleConns(setting.Database.MaxIdleConns)
  147. x.SetConnMaxLifetime(setting.Database.ConnMaxLifetime)
  148. return nil
  149. }
  150. // NewEngine initializes a new xorm.Engine
  151. func NewEngine(migrateFunc func(*xorm.Engine) error) (err error) {
  152. if err = SetEngine(); err != nil {
  153. return err
  154. }
  155. if err = x.Ping(); err != nil {
  156. return err
  157. }
  158. if err = migrateFunc(x); err != nil {
  159. return fmt.Errorf("migrate: %v", err)
  160. }
  161. if err = x.StoreEngine("InnoDB").Sync2(tables...); err != nil {
  162. return fmt.Errorf("sync database struct error: %v", err)
  163. }
  164. return nil
  165. }
  166. // Statistic contains the database statistics
  167. type Statistic struct {
  168. Counter struct {
  169. User, Org, PublicKey,
  170. Repo, Watch, Star, Action, Access,
  171. Issue, Comment, Oauth, Follow,
  172. Mirror, Release, LoginSource, Webhook,
  173. Milestone, Label, HookTask,
  174. Team, UpdateTask, Attachment int64
  175. }
  176. }
  177. // GetStatistic returns the database statistics
  178. func GetStatistic() (stats Statistic) {
  179. stats.Counter.User = CountUsers()
  180. stats.Counter.Org = CountOrganizations()
  181. stats.Counter.PublicKey, _ = x.Count(new(PublicKey))
  182. stats.Counter.Repo = CountRepositories(true)
  183. stats.Counter.Watch, _ = x.Count(new(Watch))
  184. stats.Counter.Star, _ = x.Count(new(Star))
  185. stats.Counter.Action, _ = x.Count(new(Action))
  186. stats.Counter.Access, _ = x.Count(new(Access))
  187. stats.Counter.Issue, _ = x.Count(new(Issue))
  188. stats.Counter.Comment, _ = x.Count(new(Comment))
  189. stats.Counter.Oauth = 0
  190. stats.Counter.Follow, _ = x.Count(new(Follow))
  191. stats.Counter.Mirror, _ = x.Count(new(Mirror))
  192. stats.Counter.Release, _ = x.Count(new(Release))
  193. stats.Counter.LoginSource = CountLoginSources()
  194. stats.Counter.Webhook, _ = x.Count(new(Webhook))
  195. stats.Counter.Milestone, _ = x.Count(new(Milestone))
  196. stats.Counter.Label, _ = x.Count(new(Label))
  197. stats.Counter.HookTask, _ = x.Count(new(HookTask))
  198. stats.Counter.Team, _ = x.Count(new(Team))
  199. stats.Counter.Attachment, _ = x.Count(new(Attachment))
  200. return
  201. }
  202. // Ping tests if database is alive
  203. func Ping() error {
  204. if x != nil {
  205. return x.Ping()
  206. }
  207. return errors.New("database not configured")
  208. }
  209. // DumpDatabase dumps all data from database according the special database SQL syntax to file system.
  210. func DumpDatabase(filePath string, dbType string) error {
  211. var tbs []*core.Table
  212. for _, t := range tables {
  213. t := x.TableInfo(t)
  214. t.Table.Name = t.Name
  215. tbs = append(tbs, t.Table)
  216. }
  217. if len(dbType) > 0 {
  218. return x.DumpTablesToFile(tbs, filePath, core.DbType(dbType))
  219. }
  220. return x.DumpTablesToFile(tbs, filePath)
  221. }
  222. // MaxBatchInsertSize returns the table's max batch insert size
  223. func MaxBatchInsertSize(bean interface{}) int {
  224. t := x.TableInfo(bean)
  225. return 999 / len(t.ColumnsSeq())
  226. }
  227. // Count returns records number according struct's fields as database query conditions
  228. func Count(bean interface{}) (int64, error) {
  229. return x.Count(bean)
  230. }
上海开阖软件有限公司 沪ICP备12045867号-1