gitea源码

engine.go 4.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2018 The Gitea Authors. All rights reserved.
  3. // SPDX-License-Identifier: MIT
  4. package db
  5. import (
  6. "context"
  7. "database/sql"
  8. "fmt"
  9. "reflect"
  10. "strings"
  11. "xorm.io/xorm"
  12. _ "github.com/go-sql-driver/mysql" // Needed for the MySQL driver
  13. _ "github.com/lib/pq" // Needed for the Postgresql driver
  14. _ "github.com/microsoft/go-mssqldb" // Needed for the MSSQL driver
  15. )
  16. var (
  17. xormEngine *xorm.Engine
  18. registeredModels []any
  19. registeredInitFuncs []func() error
  20. )
  21. // Engine represents a xorm engine or session.
  22. type Engine interface {
  23. Table(tableNameOrBean any) *xorm.Session
  24. Count(...any) (int64, error)
  25. Decr(column string, arg ...any) *xorm.Session
  26. Delete(...any) (int64, error)
  27. Truncate(...any) (int64, error)
  28. Exec(...any) (sql.Result, error)
  29. Find(any, ...any) error
  30. Get(beans ...any) (bool, error)
  31. ID(any) *xorm.Session
  32. In(string, ...any) *xorm.Session
  33. Incr(column string, arg ...any) *xorm.Session
  34. Insert(...any) (int64, error)
  35. Iterate(any, xorm.IterFunc) error
  36. Join(joinOperator string, tablename, condition any, args ...any) *xorm.Session
  37. SQL(any, ...any) *xorm.Session
  38. Where(any, ...any) *xorm.Session
  39. Asc(colNames ...string) *xorm.Session
  40. Desc(colNames ...string) *xorm.Session
  41. Limit(limit int, start ...int) *xorm.Session
  42. NoAutoTime() *xorm.Session
  43. SumInt(bean any, columnName string) (res int64, err error)
  44. Sync(...any) error
  45. Select(string) *xorm.Session
  46. SetExpr(string, any) *xorm.Session
  47. NotIn(string, ...any) *xorm.Session
  48. OrderBy(any, ...any) *xorm.Session
  49. Exist(...any) (bool, error)
  50. Distinct(...string) *xorm.Session
  51. Query(...any) ([]map[string][]byte, error)
  52. Cols(...string) *xorm.Session
  53. Context(ctx context.Context) *xorm.Session
  54. Ping() error
  55. IsTableExist(tableNameOrBean any) (bool, error)
  56. }
  57. var (
  58. _ Engine = (*xorm.Engine)(nil)
  59. _ Engine = (*xorm.Session)(nil)
  60. )
  61. // RegisterModel registers model, if initFuncs provided, it will be invoked after data model sync
  62. func RegisterModel(bean any, initFunc ...func() error) {
  63. registeredModels = append(registeredModels, bean)
  64. if len(registeredInitFuncs) > 0 && initFunc[0] != nil {
  65. registeredInitFuncs = append(registeredInitFuncs, initFunc[0])
  66. }
  67. }
  68. // SyncAllTables sync the schemas of all tables, is required by unit test code
  69. func SyncAllTables() error {
  70. _, err := xormEngine.StoreEngine("InnoDB").SyncWithOptions(xorm.SyncOptions{
  71. WarnIfDatabaseColumnMissed: true,
  72. }, registeredModels...)
  73. return err
  74. }
  75. // NamesToBean return a list of beans or an error
  76. func NamesToBean(names ...string) ([]any, error) {
  77. beans := []any{}
  78. if len(names) == 0 {
  79. beans = append(beans, registeredModels...)
  80. return beans, nil
  81. }
  82. // Need to map provided names to beans...
  83. beanMap := make(map[string]any)
  84. for _, bean := range registeredModels {
  85. beanMap[strings.ToLower(reflect.Indirect(reflect.ValueOf(bean)).Type().Name())] = bean
  86. beanMap[strings.ToLower(xormEngine.TableName(bean))] = bean
  87. beanMap[strings.ToLower(xormEngine.TableName(bean, true))] = bean
  88. }
  89. gotBean := make(map[any]bool)
  90. for _, name := range names {
  91. bean, ok := beanMap[strings.ToLower(strings.TrimSpace(name))]
  92. if !ok {
  93. return nil, fmt.Errorf("no table found that matches: %s", name)
  94. }
  95. if !gotBean[bean] {
  96. beans = append(beans, bean)
  97. gotBean[bean] = true
  98. }
  99. }
  100. return beans, nil
  101. }
  102. // MaxBatchInsertSize returns the table's max batch insert size
  103. func MaxBatchInsertSize(bean any) int {
  104. t, err := xormEngine.TableInfo(bean)
  105. if err != nil {
  106. return 50
  107. }
  108. return 999 / len(t.ColumnsSeq())
  109. }
  110. // IsTableNotEmpty returns true if table has at least one record
  111. func IsTableNotEmpty(beanOrTableName any) (bool, error) {
  112. return xormEngine.Table(beanOrTableName).Exist()
  113. }
  114. // DeleteAllRecords will delete all the records of this table
  115. func DeleteAllRecords(tableName string) error {
  116. _, err := xormEngine.Exec("DELETE FROM " + tableName)
  117. return err
  118. }
  119. // GetMaxID will return max id of the table
  120. func GetMaxID(beanOrTableName any) (maxID int64, err error) {
  121. _, err = xormEngine.Select("MAX(id)").Table(beanOrTableName).Get(&maxID)
  122. return maxID, err
  123. }
  124. func SetLogSQL(ctx context.Context, on bool) {
  125. e := GetEngine(ctx)
  126. if x, ok := e.(*xorm.Engine); ok {
  127. x.ShowSQL(on)
  128. } else if sess, ok := e.(*xorm.Session); ok {
  129. sess.Engine().ShowSQL(on)
  130. }
  131. }