common.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package migrations
  2. import (
  3. "fmt"
  4. . "github.com/grafana/grafana/pkg/services/sqlstore/migrator"
  5. )
  6. func addDropAllIndicesMigrations(mg *Migrator, versionSuffix string, table Table) {
  7. for _, index := range table.Indices {
  8. migrationId := fmt.Sprintf("drop index %s - %s", index.XName(table.Name), versionSuffix)
  9. mg.AddMigration(migrationId, NewDropIndexMigration(table, index))
  10. }
  11. }
  12. func addTableIndicesMigrations(mg *Migrator, versionSuffix string, table Table) {
  13. for _, index := range table.Indices {
  14. migrationId := fmt.Sprintf("create index %s - %s", index.XName(table.Name), versionSuffix)
  15. mg.AddMigration(migrationId, NewAddIndexMigration(table, index))
  16. }
  17. }
  18. func addTableRenameMigration(mg *Migrator, oldName string, newName string, versionSuffix string) {
  19. migrationId := fmt.Sprintf("Rename table %s to %s - %s", oldName, newName, versionSuffix)
  20. mg.AddMigration(migrationId, NewRenameTableMigration(oldName, newName))
  21. }
  22. func addTableReplaceMigrations(mg *Migrator, from Table, to Table, migrationVersion int64, tableDataMigration map[string]string) {
  23. fromV := version(migrationVersion - 1)
  24. toV := version(migrationVersion)
  25. tmpTableName := to.Name + "_tmp_qwerty"
  26. createTable := fmt.Sprintf("create %v %v", to.Name, toV)
  27. copyTableData := fmt.Sprintf("copy %v %v to %v", to.Name, fromV, toV)
  28. dropTable := fmt.Sprintf("drop %v", tmpTableName)
  29. addDropAllIndicesMigrations(mg, fromV, from)
  30. addTableRenameMigration(mg, from.Name, tmpTableName, fromV)
  31. mg.AddMigration(createTable, NewAddTableMigration(to))
  32. addTableIndicesMigrations(mg, toV, to)
  33. mg.AddMigration(copyTableData, NewCopyTableDataMigration(to.Name, tmpTableName, tableDataMigration))
  34. mg.AddMigration(dropTable, NewDropTableMigration(tmpTableName))
  35. }
  36. func version(v int64) string {
  37. return fmt.Sprintf("v%v", v)
  38. }