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 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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. "context"
  8. "database/sql"
  9. "errors"
  10. "fmt"
  11. "reflect"
  12. "strings"
  13. "code.gitea.io/gitea/modules/setting"
  14. // Needed for the MySQL driver
  15. _ "github.com/go-sql-driver/mysql"
  16. lru "github.com/hashicorp/golang-lru"
  17. "xorm.io/xorm"
  18. "xorm.io/xorm/names"
  19. "xorm.io/xorm/schemas"
  20. // Needed for the Postgresql driver
  21. _ "github.com/lib/pq"
  22. // Needed for the MSSQL driver
  23. _ "github.com/denisenkom/go-mssqldb"
  24. )
  25. // Engine represents a xorm engine or session.
  26. type Engine interface {
  27. Table(tableNameOrBean interface{}) *xorm.Session
  28. Count(...interface{}) (int64, error)
  29. Decr(column string, arg ...interface{}) *xorm.Session
  30. Delete(...interface{}) (int64, error)
  31. Exec(...interface{}) (sql.Result, error)
  32. Find(interface{}, ...interface{}) error
  33. Get(interface{}) (bool, error)
  34. ID(interface{}) *xorm.Session
  35. In(string, ...interface{}) *xorm.Session
  36. Incr(column string, arg ...interface{}) *xorm.Session
  37. Insert(...interface{}) (int64, error)
  38. InsertOne(interface{}) (int64, error)
  39. Iterate(interface{}, xorm.IterFunc) error
  40. Join(joinOperator string, tablename interface{}, condition string, args ...interface{}) *xorm.Session
  41. SQL(interface{}, ...interface{}) *xorm.Session
  42. Where(interface{}, ...interface{}) *xorm.Session
  43. Asc(colNames ...string) *xorm.Session
  44. Desc(colNames ...string) *xorm.Session
  45. Limit(limit int, start ...int) *xorm.Session
  46. SumInt(bean interface{}, columnName string) (res int64, err error)
  47. }
  48. const (
  49. // When queries are broken down in parts because of the number
  50. // of parameters, attempt to break by this amount
  51. maxQueryParameters = 300
  52. )
  53. var (
  54. x *xorm.Engine
  55. tables []interface{}
  56. // HasEngine specifies if we have a xorm.Engine
  57. HasEngine bool
  58. )
  59. func init() {
  60. tables = append(tables,
  61. new(User),
  62. new(PublicKey),
  63. new(AccessToken),
  64. new(Repository),
  65. new(DeployKey),
  66. new(Collaboration),
  67. new(Access),
  68. new(Upload),
  69. new(Watch),
  70. new(Star),
  71. new(Follow),
  72. new(Action),
  73. new(Issue),
  74. new(PullRequest),
  75. new(Comment),
  76. new(Attachment),
  77. new(Label),
  78. new(IssueLabel),
  79. new(Milestone),
  80. new(Mirror),
  81. new(Release),
  82. new(LoginSource),
  83. new(Webhook),
  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. new(GPGKey),
  96. new(GPGKeyImport),
  97. new(RepoUnit),
  98. new(RepoRedirect),
  99. new(ExternalLoginUser),
  100. new(ProtectedBranch),
  101. new(UserOpenID),
  102. new(IssueWatch),
  103. new(CommitStatus),
  104. new(Stopwatch),
  105. new(TrackedTime),
  106. new(DeletedBranch),
  107. new(RepoIndexerStatus),
  108. new(IssueDependency),
  109. new(LFSLock),
  110. new(Reaction),
  111. new(IssueAssignees),
  112. new(U2FRegistration),
  113. new(TeamUnit),
  114. new(Review),
  115. new(OAuth2Application),
  116. new(OAuth2AuthorizationCode),
  117. new(OAuth2Grant),
  118. new(Task),
  119. new(LanguageStat),
  120. new(EmailHash),
  121. new(UserRedirect),
  122. new(Project),
  123. new(ProjectBoard),
  124. new(ProjectIssue),
  125. new(Session),
  126. new(RepoTransfer),
  127. new(IssueIndex),
  128. new(PushMirror),
  129. new(RepoArchiver),
  130. new(ProtectedTag),
  131. )
  132. gonicNames := []string{"SSL", "UID"}
  133. for _, name := range gonicNames {
  134. names.LintGonicMapper[name] = true
  135. }
  136. }
  137. // GetNewEngine returns a new xorm engine from the configuration
  138. func GetNewEngine() (*xorm.Engine, error) {
  139. connStr, err := setting.DBConnStr()
  140. if err != nil {
  141. return nil, err
  142. }
  143. var engine *xorm.Engine
  144. if setting.Database.UsePostgreSQL && len(setting.Database.Schema) > 0 {
  145. // OK whilst we sort out our schema issues - create a schema aware postgres
  146. registerPostgresSchemaDriver()
  147. engine, err = xorm.NewEngine("postgresschema", connStr)
  148. } else {
  149. engine, err = xorm.NewEngine(setting.Database.Type, connStr)
  150. }
  151. if err != nil {
  152. return nil, err
  153. }
  154. if setting.Database.Type == "mysql" {
  155. engine.Dialect().SetParams(map[string]string{"rowFormat": "DYNAMIC"})
  156. } else if setting.Database.Type == "mssql" {
  157. engine.Dialect().SetParams(map[string]string{"DEFAULT_VARCHAR": "nvarchar"})
  158. }
  159. engine.SetSchema(setting.Database.Schema)
  160. return engine, nil
  161. }
  162. func syncTables() error {
  163. return x.StoreEngine("InnoDB").Sync2(tables...)
  164. }
  165. // NewTestEngine sets a new test xorm.Engine
  166. func NewTestEngine() (err error) {
  167. x, err = GetNewEngine()
  168. if err != nil {
  169. return fmt.Errorf("Connect to database: %v", err)
  170. }
  171. x.SetMapper(names.GonicMapper{})
  172. x.SetLogger(NewXORMLogger(!setting.IsProd()))
  173. x.ShowSQL(!setting.IsProd())
  174. return syncTables()
  175. }
  176. // SetEngine sets the xorm.Engine
  177. func SetEngine() (err error) {
  178. x, err = GetNewEngine()
  179. if err != nil {
  180. return fmt.Errorf("Failed to connect to database: %v", err)
  181. }
  182. x.SetMapper(names.GonicMapper{})
  183. // WARNING: for serv command, MUST remove the output to os.stdout,
  184. // so use log file to instead print to stdout.
  185. x.SetLogger(NewXORMLogger(setting.Database.LogSQL))
  186. x.ShowSQL(setting.Database.LogSQL)
  187. x.SetMaxOpenConns(setting.Database.MaxOpenConns)
  188. x.SetMaxIdleConns(setting.Database.MaxIdleConns)
  189. x.SetConnMaxLifetime(setting.Database.ConnMaxLifetime)
  190. return nil
  191. }
  192. // NewEngine initializes a new xorm.Engine
  193. // This function must never call .Sync2() if the provided migration function fails.
  194. // When called from the "doctor" command, the migration function is a version check
  195. // that prevents the doctor from fixing anything in the database if the migration level
  196. // is different from the expected value.
  197. func NewEngine(ctx context.Context, migrateFunc func(*xorm.Engine) error) (err error) {
  198. if err = SetEngine(); err != nil {
  199. return err
  200. }
  201. x.SetDefaultContext(ctx)
  202. if err = x.Ping(); err != nil {
  203. return err
  204. }
  205. if err = migrateFunc(x); err != nil {
  206. return fmt.Errorf("migrate: %v", err)
  207. }
  208. if err = syncTables(); err != nil {
  209. return fmt.Errorf("sync database struct error: %v", err)
  210. }
  211. if setting.SuccessfulTokensCacheSize > 0 {
  212. successfulAccessTokenCache, err = lru.New(setting.SuccessfulTokensCacheSize)
  213. if err != nil {
  214. return fmt.Errorf("unable to allocate AccessToken cache: %v", err)
  215. }
  216. } else {
  217. successfulAccessTokenCache = nil
  218. }
  219. return nil
  220. }
  221. // NamesToBean return a list of beans or an error
  222. func NamesToBean(names ...string) ([]interface{}, error) {
  223. beans := []interface{}{}
  224. if len(names) == 0 {
  225. beans = append(beans, tables...)
  226. return beans, nil
  227. }
  228. // Need to map provided names to beans...
  229. beanMap := make(map[string]interface{})
  230. for _, bean := range tables {
  231. beanMap[strings.ToLower(reflect.Indirect(reflect.ValueOf(bean)).Type().Name())] = bean
  232. beanMap[strings.ToLower(x.TableName(bean))] = bean
  233. beanMap[strings.ToLower(x.TableName(bean, true))] = bean
  234. }
  235. gotBean := make(map[interface{}]bool)
  236. for _, name := range names {
  237. bean, ok := beanMap[strings.ToLower(strings.TrimSpace(name))]
  238. if !ok {
  239. return nil, fmt.Errorf("No table found that matches: %s", name)
  240. }
  241. if !gotBean[bean] {
  242. beans = append(beans, bean)
  243. gotBean[bean] = true
  244. }
  245. }
  246. return beans, nil
  247. }
  248. // Statistic contains the database statistics
  249. type Statistic struct {
  250. Counter struct {
  251. User, Org, PublicKey,
  252. Repo, Watch, Star, Action, Access,
  253. Issue, IssueClosed, IssueOpen,
  254. Comment, Oauth, Follow,
  255. Mirror, Release, LoginSource, Webhook,
  256. Milestone, Label, HookTask,
  257. Team, UpdateTask, Attachment int64
  258. }
  259. }
  260. // GetStatistic returns the database statistics
  261. func GetStatistic() (stats Statistic) {
  262. stats.Counter.User = CountUsers()
  263. stats.Counter.Org = CountOrganizations()
  264. stats.Counter.PublicKey, _ = x.Count(new(PublicKey))
  265. stats.Counter.Repo = CountRepositories(true)
  266. stats.Counter.Watch, _ = x.Count(new(Watch))
  267. stats.Counter.Star, _ = x.Count(new(Star))
  268. stats.Counter.Action, _ = x.Count(new(Action))
  269. stats.Counter.Access, _ = x.Count(new(Access))
  270. type IssueCount struct {
  271. Count int64
  272. IsClosed bool
  273. }
  274. issueCounts := []IssueCount{}
  275. _ = x.Select("COUNT(*) AS count, is_closed").Table("issue").GroupBy("is_closed").Find(&issueCounts)
  276. for _, c := range issueCounts {
  277. if c.IsClosed {
  278. stats.Counter.IssueClosed = c.Count
  279. } else {
  280. stats.Counter.IssueOpen = c.Count
  281. }
  282. }
  283. stats.Counter.Issue = stats.Counter.IssueClosed + stats.Counter.IssueOpen
  284. stats.Counter.Comment, _ = x.Count(new(Comment))
  285. stats.Counter.Oauth = 0
  286. stats.Counter.Follow, _ = x.Count(new(Follow))
  287. stats.Counter.Mirror, _ = x.Count(new(Mirror))
  288. stats.Counter.Release, _ = x.Count(new(Release))
  289. stats.Counter.LoginSource = CountLoginSources()
  290. stats.Counter.Webhook, _ = x.Count(new(Webhook))
  291. stats.Counter.Milestone, _ = x.Count(new(Milestone))
  292. stats.Counter.Label, _ = x.Count(new(Label))
  293. stats.Counter.HookTask, _ = x.Count(new(HookTask))
  294. stats.Counter.Team, _ = x.Count(new(Team))
  295. stats.Counter.Attachment, _ = x.Count(new(Attachment))
  296. return
  297. }
  298. // Ping tests if database is alive
  299. func Ping() error {
  300. if x != nil {
  301. return x.Ping()
  302. }
  303. return errors.New("database not configured")
  304. }
  305. // DumpDatabase dumps all data from database according the special database SQL syntax to file system.
  306. func DumpDatabase(filePath, dbType string) error {
  307. var tbs []*schemas.Table
  308. for _, t := range tables {
  309. t, err := x.TableInfo(t)
  310. if err != nil {
  311. return err
  312. }
  313. tbs = append(tbs, t)
  314. }
  315. type Version struct {
  316. ID int64 `xorm:"pk autoincr"`
  317. Version int64
  318. }
  319. t, err := x.TableInfo(&Version{})
  320. if err != nil {
  321. return err
  322. }
  323. tbs = append(tbs, t)
  324. if len(dbType) > 0 {
  325. return x.DumpTablesToFile(tbs, filePath, schemas.DBType(dbType))
  326. }
  327. return x.DumpTablesToFile(tbs, filePath)
  328. }
  329. // MaxBatchInsertSize returns the table's max batch insert size
  330. func MaxBatchInsertSize(bean interface{}) int {
  331. t, err := x.TableInfo(bean)
  332. if err != nil {
  333. return 50
  334. }
  335. return 999 / len(t.ColumnsSeq())
  336. }
  337. // Count returns records number according struct's fields as database query conditions
  338. func Count(bean interface{}) (int64, error) {
  339. return x.Count(bean)
  340. }
  341. // IsTableNotEmpty returns true if table has at least one record
  342. func IsTableNotEmpty(tableName string) (bool, error) {
  343. return x.Table(tableName).Exist()
  344. }
  345. // DeleteAllRecords will delete all the records of this table
  346. func DeleteAllRecords(tableName string) error {
  347. _, err := x.Exec(fmt.Sprintf("DELETE FROM %s", tableName))
  348. return err
  349. }
  350. // GetMaxID will return max id of the table
  351. func GetMaxID(beanOrTableName interface{}) (maxID int64, err error) {
  352. _, err = x.Select("MAX(id)").Table(beanOrTableName).Get(&maxID)
  353. return
  354. }
  355. // FindByMaxID filled results as the condition from database
  356. func FindByMaxID(maxID int64, limit int, results interface{}) error {
  357. return x.Where("id <= ?", maxID).
  358. OrderBy("id DESC").
  359. Limit(limit).
  360. Find(results)
  361. }