gitea源码

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. // Copyright 2023 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package db
  4. import (
  5. "errors"
  6. "fmt"
  7. "strings"
  8. "code.gitea.io/gitea/modules/container"
  9. "code.gitea.io/gitea/modules/log"
  10. "code.gitea.io/gitea/modules/setting"
  11. "xorm.io/xorm"
  12. "xorm.io/xorm/schemas"
  13. )
  14. type CheckCollationsResult struct {
  15. ExpectedCollation string
  16. AvailableCollation container.Set[string]
  17. DatabaseCollation string
  18. IsCollationCaseSensitive func(s string) bool
  19. CollationEquals func(a, b string) bool
  20. ExistingTableNumber int
  21. InconsistentCollationColumns []string
  22. }
  23. func findAvailableCollationsMySQL(x *xorm.Engine) (ret container.Set[string], err error) {
  24. var res []struct {
  25. Collation string
  26. }
  27. if err = x.SQL("SHOW COLLATION WHERE (Collation = 'utf8mb4_bin') OR (Collation LIKE '%\\_as\\_cs%')").Find(&res); err != nil {
  28. return nil, err
  29. }
  30. ret = make(container.Set[string], len(res))
  31. for _, r := range res {
  32. ret.Add(r.Collation)
  33. }
  34. return ret, nil
  35. }
  36. func findAvailableCollationsMSSQL(x *xorm.Engine) (ret container.Set[string], err error) {
  37. var res []struct {
  38. Name string
  39. }
  40. if err = x.SQL("SELECT * FROM sys.fn_helpcollations() WHERE name LIKE '%[_]CS[_]AS%'").Find(&res); err != nil {
  41. return nil, err
  42. }
  43. ret = make(container.Set[string], len(res))
  44. for _, r := range res {
  45. ret.Add(r.Name)
  46. }
  47. return ret, nil
  48. }
  49. func CheckCollations(x *xorm.Engine) (*CheckCollationsResult, error) {
  50. dbTables, err := x.DBMetas()
  51. if err != nil {
  52. return nil, err
  53. }
  54. res := &CheckCollationsResult{
  55. ExistingTableNumber: len(dbTables),
  56. CollationEquals: func(a, b string) bool { return a == b },
  57. }
  58. var candidateCollations []string
  59. if x.Dialect().URI().DBType == schemas.MYSQL {
  60. _, err = x.SQL("SELECT DEFAULT_COLLATION_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = ?", setting.Database.Name).Get(&res.DatabaseCollation)
  61. if err != nil {
  62. return nil, err
  63. }
  64. res.IsCollationCaseSensitive = func(s string) bool {
  65. return s == "utf8mb4_bin" || strings.HasSuffix(s, "_as_cs")
  66. }
  67. candidateCollations = []string{"utf8mb4_0900_as_cs", "uca1400_as_cs", "utf8mb4_bin"}
  68. res.AvailableCollation, err = findAvailableCollationsMySQL(x)
  69. if err != nil {
  70. return nil, err
  71. }
  72. res.CollationEquals = func(a, b string) bool {
  73. // MariaDB adds the "utf8mb4_" prefix, eg: "utf8mb4_uca1400_as_cs", but not the name "uca1400_as_cs" in "SHOW COLLATION"
  74. // At the moment, it's safe to ignore the database difference, just trim the prefix and compare. It could be fixed easily if there is any problem in the future.
  75. return a == b || strings.TrimPrefix(a, "utf8mb4_") == strings.TrimPrefix(b, "utf8mb4_")
  76. }
  77. } else if x.Dialect().URI().DBType == schemas.MSSQL {
  78. if _, err = x.SQL("SELECT DATABASEPROPERTYEX(DB_NAME(), 'Collation')").Get(&res.DatabaseCollation); err != nil {
  79. return nil, err
  80. }
  81. res.IsCollationCaseSensitive = func(s string) bool {
  82. return strings.HasSuffix(s, "_CS_AS")
  83. }
  84. candidateCollations = []string{"Latin1_General_CS_AS"}
  85. res.AvailableCollation, err = findAvailableCollationsMSSQL(x)
  86. if err != nil {
  87. return nil, err
  88. }
  89. } else {
  90. return nil, nil
  91. }
  92. if res.DatabaseCollation == "" {
  93. return nil, errors.New("unable to get collation for current database")
  94. }
  95. res.ExpectedCollation = setting.Database.CharsetCollation
  96. if res.ExpectedCollation == "" {
  97. for _, collation := range candidateCollations {
  98. if res.AvailableCollation.Contains(collation) {
  99. res.ExpectedCollation = collation
  100. break
  101. }
  102. }
  103. }
  104. if res.ExpectedCollation == "" {
  105. return nil, errors.New("unable to find a suitable collation for current database")
  106. }
  107. allColumnsMatchExpected := true
  108. allColumnsMatchDatabase := true
  109. for _, table := range dbTables {
  110. for _, col := range table.Columns() {
  111. if col.Collation != "" {
  112. allColumnsMatchExpected = allColumnsMatchExpected && res.CollationEquals(col.Collation, res.ExpectedCollation)
  113. allColumnsMatchDatabase = allColumnsMatchDatabase && res.CollationEquals(col.Collation, res.DatabaseCollation)
  114. if !res.IsCollationCaseSensitive(col.Collation) || !res.CollationEquals(col.Collation, res.DatabaseCollation) {
  115. res.InconsistentCollationColumns = append(res.InconsistentCollationColumns, fmt.Sprintf("%s.%s", table.Name, col.Name))
  116. }
  117. }
  118. }
  119. }
  120. // if all columns match expected collation or all match database collation, then it could also be considered as "consistent"
  121. if allColumnsMatchExpected || allColumnsMatchDatabase {
  122. res.InconsistentCollationColumns = nil
  123. }
  124. return res, nil
  125. }
  126. func CheckCollationsDefaultEngine() (*CheckCollationsResult, error) {
  127. return CheckCollations(xormEngine)
  128. }
  129. func alterDatabaseCollation(x *xorm.Engine, collation string) error {
  130. if x.Dialect().URI().DBType == schemas.MYSQL {
  131. _, err := x.Exec("ALTER DATABASE CHARACTER SET utf8mb4 COLLATE " + collation)
  132. return err
  133. } else if x.Dialect().URI().DBType == schemas.MSSQL {
  134. // TODO: MSSQL has many limitations on changing database collation, it could fail in many cases.
  135. _, err := x.Exec("ALTER DATABASE CURRENT COLLATE " + collation)
  136. return err
  137. }
  138. return errors.New("unsupported database type")
  139. }
  140. // preprocessDatabaseCollation checks database & table column collation, and alter the database collation if needed
  141. func preprocessDatabaseCollation(x *xorm.Engine) {
  142. r, err := CheckCollations(x)
  143. if err != nil {
  144. log.Error("Failed to check database collation: %v", err)
  145. }
  146. if r == nil {
  147. return // no check result means the database doesn't need to do such check/process (at the moment ....)
  148. }
  149. // try to alter database collation to expected if the database is empty, it might fail in some cases (and it isn't necessary to succeed)
  150. // at the moment, there is no "altering" solution for MSSQL, site admin should manually change the database collation
  151. if !r.CollationEquals(r.DatabaseCollation, r.ExpectedCollation) && r.ExistingTableNumber == 0 {
  152. if err = alterDatabaseCollation(x, r.ExpectedCollation); err != nil {
  153. log.Error("Failed to change database collation to %q: %v", r.ExpectedCollation, err)
  154. } else {
  155. _, _ = x.Exec("SELECT 1") // after "altering", MSSQL's session becomes invalid, so make a simple query to "refresh" the session
  156. if r, err = CheckCollations(x); err != nil {
  157. log.Error("Failed to check database collation again after altering: %v", err) // impossible case
  158. return
  159. }
  160. log.Warn("Current database has been altered to use collation %q", r.DatabaseCollation)
  161. }
  162. }
  163. // check column collation, and show warning/error to end users -- no need to fatal, do not block the startup
  164. if !r.IsCollationCaseSensitive(r.DatabaseCollation) {
  165. log.Warn("Current database is using a case-insensitive collation %q, although Gitea could work with it, there might be some rare cases which don't work as expected.", r.DatabaseCollation)
  166. }
  167. if len(r.InconsistentCollationColumns) > 0 {
  168. log.Error("There are %d table columns using inconsistent collation, they should use %q. Please go to admin panel Self Check page", len(r.InconsistentCollationColumns), r.DatabaseCollation)
  169. }
  170. }