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.

246 lines
6.7 KiB

  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package migrations
  5. import (
  6. "compress/gzip"
  7. "database/sql"
  8. "fmt"
  9. "io/ioutil"
  10. "os"
  11. "path"
  12. "regexp"
  13. "sort"
  14. "strings"
  15. "testing"
  16. "code.gitea.io/gitea/integrations"
  17. "code.gitea.io/gitea/models"
  18. "code.gitea.io/gitea/models/migrations"
  19. "code.gitea.io/gitea/modules/base"
  20. "code.gitea.io/gitea/modules/charset"
  21. "code.gitea.io/gitea/modules/setting"
  22. "github.com/stretchr/testify/assert"
  23. "xorm.io/xorm"
  24. )
  25. var currentEngine *xorm.Engine
  26. func initMigrationTest(t *testing.T) {
  27. integrations.PrintCurrentTest(t, 2)
  28. giteaRoot := base.SetupGiteaRoot()
  29. if giteaRoot == "" {
  30. integrations.Printf("Environment variable $GITEA_ROOT not set\n")
  31. os.Exit(1)
  32. }
  33. setting.AppPath = path.Join(giteaRoot, "gitea")
  34. if _, err := os.Stat(setting.AppPath); err != nil {
  35. integrations.Printf("Could not find gitea binary at %s\n", setting.AppPath)
  36. os.Exit(1)
  37. }
  38. giteaConf := os.Getenv("GITEA_CONF")
  39. if giteaConf == "" {
  40. integrations.Printf("Environment variable $GITEA_CONF not set\n")
  41. os.Exit(1)
  42. } else if !path.IsAbs(giteaConf) {
  43. setting.CustomConf = path.Join(giteaRoot, giteaConf)
  44. } else {
  45. setting.CustomConf = giteaConf
  46. }
  47. setting.NewContext()
  48. setting.CheckLFSVersion()
  49. setting.InitDBConfig()
  50. setting.NewLogServices(true)
  51. }
  52. func availableVersions() ([]string, error) {
  53. migrationsDir, err := os.Open("integrations/migration-test")
  54. if err != nil {
  55. return nil, err
  56. }
  57. defer migrationsDir.Close()
  58. versionRE, err := regexp.Compile("gitea-v(?P<version>.+)\\." + regexp.QuoteMeta(setting.Database.Type) + "\\.sql.gz")
  59. if err != nil {
  60. return nil, err
  61. }
  62. filenames, err := migrationsDir.Readdirnames(-1)
  63. if err != nil {
  64. return nil, err
  65. }
  66. versions := []string{}
  67. for _, filename := range filenames {
  68. if versionRE.MatchString(filename) {
  69. substrings := versionRE.FindStringSubmatch(filename)
  70. versions = append(versions, substrings[1])
  71. }
  72. }
  73. sort.Strings(versions)
  74. return versions, nil
  75. }
  76. func readSQLFromFile(version string) (string, error) {
  77. filename := fmt.Sprintf("integrations/migration-test/gitea-v%s.%s.sql.gz", version, setting.Database.Type)
  78. if _, err := os.Stat(filename); os.IsNotExist(err) {
  79. return "", nil
  80. }
  81. file, err := os.Open(filename)
  82. if err != nil {
  83. return "", err
  84. }
  85. defer file.Close()
  86. gr, err := gzip.NewReader(file)
  87. if err != nil {
  88. return "", err
  89. }
  90. defer gr.Close()
  91. bytes, err := ioutil.ReadAll(gr)
  92. if err != nil {
  93. return "", err
  94. }
  95. return string(charset.RemoveBOMIfPresent(bytes)), nil
  96. }
  97. func restoreOldDB(t *testing.T, version string) bool {
  98. data, err := readSQLFromFile(version)
  99. assert.NoError(t, err)
  100. if len(data) == 0 {
  101. integrations.Printf("No db found to restore for %s version: %s\n", setting.Database.Type, version)
  102. return false
  103. }
  104. switch {
  105. case setting.Database.UseSQLite3:
  106. os.Remove(setting.Database.Path)
  107. err := os.MkdirAll(path.Dir(setting.Database.Path), os.ModePerm)
  108. assert.NoError(t, err)
  109. db, err := sql.Open("sqlite3", fmt.Sprintf("file:%s?cache=shared&mode=rwc&_busy_timeout=%d", setting.Database.Path, setting.Database.Timeout))
  110. assert.NoError(t, err)
  111. defer db.Close()
  112. _, err = db.Exec(data)
  113. assert.NoError(t, err)
  114. db.Close()
  115. case setting.Database.UseMySQL:
  116. db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s)/",
  117. setting.Database.User, setting.Database.Passwd, setting.Database.Host))
  118. assert.NoError(t, err)
  119. defer db.Close()
  120. _, err = db.Exec(fmt.Sprintf("DROP DATABASE IF EXISTS %s", setting.Database.Name))
  121. assert.NoError(t, err)
  122. _, err = db.Exec(fmt.Sprintf("CREATE DATABASE IF NOT EXISTS %s", setting.Database.Name))
  123. assert.NoError(t, err)
  124. db, err = sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s)/%s?multiStatements=true",
  125. setting.Database.User, setting.Database.Passwd, setting.Database.Host, setting.Database.Name))
  126. assert.NoError(t, err)
  127. defer db.Close()
  128. _, err = db.Exec(data)
  129. assert.NoError(t, err)
  130. db.Close()
  131. case setting.Database.UsePostgreSQL:
  132. db, err := sql.Open("postgres", fmt.Sprintf("postgres://%s:%s@%s/?sslmode=%s",
  133. setting.Database.User, setting.Database.Passwd, setting.Database.Host, setting.Database.SSLMode))
  134. assert.NoError(t, err)
  135. defer db.Close()
  136. _, err = db.Exec(fmt.Sprintf("DROP DATABASE IF EXISTS %s", setting.Database.Name))
  137. assert.NoError(t, err)
  138. _, err = db.Exec(fmt.Sprintf("CREATE DATABASE %s", setting.Database.Name))
  139. assert.NoError(t, err)
  140. db.Close()
  141. db, err = sql.Open("postgres", fmt.Sprintf("postgres://%s:%s@%s/%s?sslmode=%s",
  142. setting.Database.User, setting.Database.Passwd, setting.Database.Host, setting.Database.Name, setting.Database.SSLMode))
  143. assert.NoError(t, err)
  144. defer db.Close()
  145. _, err = db.Exec(data)
  146. assert.NoError(t, err)
  147. db.Close()
  148. case setting.Database.UseMSSQL:
  149. host, port := setting.ParseMSSQLHostPort(setting.Database.Host)
  150. db, err := sql.Open("mssql", fmt.Sprintf("server=%s; port=%s; database=%s; user id=%s; password=%s;",
  151. host, port, "master", setting.Database.User, setting.Database.Passwd))
  152. assert.NoError(t, err)
  153. defer db.Close()
  154. _, err = db.Exec("DROP DATABASE IF EXISTS [gitea]")
  155. assert.NoError(t, err)
  156. statements := strings.Split(data, "\nGO\n")
  157. for _, statement := range statements {
  158. if len(statement) > 5 && statement[:5] == "USE [" {
  159. dbname := statement[5 : len(statement)-1]
  160. db.Close()
  161. db, err = sql.Open("mssql", fmt.Sprintf("server=%s; port=%s; database=%s; user id=%s; password=%s;",
  162. host, port, dbname, setting.Database.User, setting.Database.Passwd))
  163. assert.NoError(t, err)
  164. defer db.Close()
  165. }
  166. _, err = db.Exec(statement)
  167. assert.NoError(t, err, "Failure whilst running: %s\nError: %v", statement, err)
  168. }
  169. db.Close()
  170. }
  171. return true
  172. }
  173. func wrappedMigrate(x *xorm.Engine) error {
  174. currentEngine = x
  175. return migrations.Migrate(x)
  176. }
  177. func doMigrationTest(t *testing.T, version string) {
  178. integrations.PrintCurrentTest(t)
  179. integrations.Printf("Performing migration test for %s version: %s\n", setting.Database.Type, version)
  180. if !restoreOldDB(t, version) {
  181. return
  182. }
  183. setting.NewXORMLogService(false)
  184. err := models.SetEngine()
  185. assert.NoError(t, err)
  186. err = models.NewEngine(wrappedMigrate)
  187. assert.NoError(t, err)
  188. currentEngine.Close()
  189. }
  190. func TestMigrations(t *testing.T) {
  191. initMigrationTest(t)
  192. dialect := setting.Database.Type
  193. versions, err := availableVersions()
  194. assert.NoError(t, err)
  195. if len(versions) == 0 {
  196. integrations.Printf("No old database versions available to migration test for %s\n", dialect)
  197. return
  198. }
  199. integrations.Printf("Preparing to test %d migrations for %s\n", len(versions), dialect)
  200. for _, version := range versions {
  201. t.Run(fmt.Sprintf("Migrate-%s-%s", dialect, version), func(t *testing.T) {
  202. doMigrationTest(t, version)
  203. })
  204. }
  205. }