migrations_test.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package migrations
  2. import (
  3. "fmt"
  4. "strings"
  5. "testing"
  6. "github.com/go-xorm/xorm"
  7. "github.com/torkelo/grafana-pro/pkg/log"
  8. . "github.com/smartystreets/goconvey/convey"
  9. )
  10. func cleanDB(x *xorm.Engine) {
  11. tables, _ := x.DBMetas()
  12. sess := x.NewSession()
  13. defer sess.Close()
  14. for _, table := range tables {
  15. if _, err := sess.Exec("SET FOREIGN_KEY_CHECKS = 0"); err != nil {
  16. panic("Failed to disable foreign key checks")
  17. }
  18. if _, err := sess.Exec("DROP TABLE " + table.Name); err != nil {
  19. panic(fmt.Sprintf("Failed to delete table: %v, err: %v", table.Name, err))
  20. }
  21. if _, err := sess.Exec("SET FOREIGN_KEY_CHECKS = 1"); err != nil {
  22. panic("Failed to disable foreign key checks")
  23. }
  24. }
  25. }
  26. var indexTypes = []string{"Unknown", "", "UNIQUE"}
  27. func TestMigrations(t *testing.T) {
  28. log.NewLogger(0, "console", `{"level": 0}`)
  29. testDBs := [][]string{
  30. []string{"postgres", "user=grafanatest password=grafanatest host=localhost port=5432 dbname=grafanatest sslmode=disable"},
  31. []string{"mysql", "grafana:password@tcp(localhost:3306)/grafana_tests?charset=utf8"},
  32. []string{"sqlite3", ":memory:"},
  33. }
  34. for _, testDB := range testDBs {
  35. Convey("Initial "+testDB[0]+" migration", t, func() {
  36. x, err := xorm.NewEngine(testDB[0], testDB[1])
  37. So(err, ShouldBeNil)
  38. if testDB[0] == "mysql" {
  39. cleanDB(x)
  40. }
  41. mg := NewMigrator(x)
  42. mg.LogLevel = log.DEBUG
  43. AddMigrations(mg)
  44. err = mg.Start()
  45. So(err, ShouldBeNil)
  46. tables, err := x.DBMetas()
  47. So(err, ShouldBeNil)
  48. fmt.Printf("\nDB Schema after migration: table count: %v\n", len(tables))
  49. for _, table := range tables {
  50. fmt.Printf("\nTable: %v \n", table.Name)
  51. for _, column := range table.Columns() {
  52. fmt.Printf("\t %v \n", column.String(x.Dialect()))
  53. }
  54. if len(table.Indexes) > 0 {
  55. fmt.Printf("\n\tIndexes:\n")
  56. for _, index := range table.Indexes {
  57. fmt.Printf("\t %v (%v) %v \n", index.Name, strings.Join(index.Cols, ","), indexTypes[index.Type])
  58. }
  59. }
  60. }
  61. })
  62. }
  63. }