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.

models.go 6.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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. "github.com/go-xorm/xorm"
  14. "xorm.io/core"
  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. )
  107. gonicNames := []string{"SSL", "UID"}
  108. for _, name := range gonicNames {
  109. core.LintGonicMapper[name] = true
  110. }
  111. }
  112. func getEngine() (*xorm.Engine, error) {
  113. connStr, err := setting.DBConnStr()
  114. if err != nil {
  115. return nil, err
  116. }
  117. return xorm.NewEngine(setting.Database.Type, connStr)
  118. }
  119. // NewTestEngine sets a new test xorm.Engine
  120. func NewTestEngine(x *xorm.Engine) (err error) {
  121. x, err = getEngine()
  122. if err != nil {
  123. return fmt.Errorf("Connect to database: %v", err)
  124. }
  125. x.ShowExecTime(true)
  126. x.SetMapper(core.GonicMapper{})
  127. x.SetLogger(NewXORMLogger(!setting.ProdMode))
  128. x.ShowSQL(!setting.ProdMode)
  129. return x.StoreEngine("InnoDB").Sync2(tables...)
  130. }
  131. // SetEngine sets the xorm.Engine
  132. func SetEngine() (err error) {
  133. x, err = getEngine()
  134. if err != nil {
  135. return fmt.Errorf("Failed to connect to database: %v", err)
  136. }
  137. x.ShowExecTime(true)
  138. x.SetMapper(core.GonicMapper{})
  139. // WARNING: for serv command, MUST remove the output to os.stdout,
  140. // so use log file to instead print to stdout.
  141. x.SetLogger(NewXORMLogger(setting.Database.LogSQL))
  142. x.ShowSQL(setting.Database.LogSQL)
  143. if setting.Database.UseMySQL {
  144. x.SetMaxIdleConns(setting.Database.MaxIdleConns)
  145. x.SetConnMaxLifetime(setting.Database.ConnMaxLifetime)
  146. }
  147. return nil
  148. }
  149. // NewEngine initializes a new xorm.Engine
  150. func NewEngine(migrateFunc func(*xorm.Engine) error) (err error) {
  151. if err = SetEngine(); err != nil {
  152. return err
  153. }
  154. if err = x.Ping(); err != nil {
  155. return err
  156. }
  157. if err = migrateFunc(x); err != nil {
  158. return fmt.Errorf("migrate: %v", err)
  159. }
  160. if err = x.StoreEngine("InnoDB").Sync2(tables...); err != nil {
  161. return fmt.Errorf("sync database struct error: %v", err)
  162. }
  163. return nil
  164. }
  165. // Statistic contains the database statistics
  166. type Statistic struct {
  167. Counter struct {
  168. User, Org, PublicKey,
  169. Repo, Watch, Star, Action, Access,
  170. Issue, Comment, Oauth, Follow,
  171. Mirror, Release, LoginSource, Webhook,
  172. Milestone, Label, HookTask,
  173. Team, UpdateTask, Attachment int64
  174. }
  175. }
  176. // GetStatistic returns the database statistics
  177. func GetStatistic() (stats Statistic) {
  178. stats.Counter.User = CountUsers()
  179. stats.Counter.Org = CountOrganizations()
  180. stats.Counter.PublicKey, _ = x.Count(new(PublicKey))
  181. stats.Counter.Repo = CountRepositories(true)
  182. stats.Counter.Watch, _ = x.Count(new(Watch))
  183. stats.Counter.Star, _ = x.Count(new(Star))
  184. stats.Counter.Action, _ = x.Count(new(Action))
  185. stats.Counter.Access, _ = x.Count(new(Access))
  186. stats.Counter.Issue, _ = x.Count(new(Issue))
  187. stats.Counter.Comment, _ = x.Count(new(Comment))
  188. stats.Counter.Oauth = 0
  189. stats.Counter.Follow, _ = x.Count(new(Follow))
  190. stats.Counter.Mirror, _ = x.Count(new(Mirror))
  191. stats.Counter.Release, _ = x.Count(new(Release))
  192. stats.Counter.LoginSource = CountLoginSources()
  193. stats.Counter.Webhook, _ = x.Count(new(Webhook))
  194. stats.Counter.Milestone, _ = x.Count(new(Milestone))
  195. stats.Counter.Label, _ = x.Count(new(Label))
  196. stats.Counter.HookTask, _ = x.Count(new(HookTask))
  197. stats.Counter.Team, _ = x.Count(new(Team))
  198. stats.Counter.Attachment, _ = x.Count(new(Attachment))
  199. return
  200. }
  201. // Ping tests if database is alive
  202. func Ping() error {
  203. if x != nil {
  204. return x.Ping()
  205. }
  206. return errors.New("database not configured")
  207. }
  208. // DumpDatabase dumps all data from database according the special database SQL syntax to file system.
  209. func DumpDatabase(filePath string, dbType string) error {
  210. var tbs []*core.Table
  211. for _, t := range tables {
  212. t := x.TableInfo(t)
  213. t.Table.Name = t.Name
  214. tbs = append(tbs, t.Table)
  215. }
  216. if len(dbType) > 0 {
  217. return x.DumpTablesToFile(tbs, filePath, core.DbType(dbType))
  218. }
  219. return x.DumpTablesToFile(tbs, filePath)
  220. }
  221. // MaxBatchInsertSize returns the table's max batch insert size
  222. func MaxBatchInsertSize(bean interface{}) int {
  223. t := x.TableInfo(bean)
  224. return 999 / len(t.ColumnsSeq())
  225. }
  226. // Count returns records number according struct's fields as database query conditions
  227. func Count(bean interface{}) (int64, error) {
  228. return x.Count(bean)
  229. }