2024-01-14 15:53:37 +00:00
|
|
|
package migrator
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
|
|
|
"fmt"
|
2024-01-15 10:33:24 +00:00
|
|
|
|
2024-01-14 15:53:37 +00:00
|
|
|
"git.gocasts.ir/ebhomengo/niki/repository/mysql"
|
|
|
|
migrate "github.com/rubenv/sql-migrate"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Migrator struct {
|
|
|
|
dialect string
|
|
|
|
dbConfig mysql.Config
|
|
|
|
migrations *migrate.FileMigrationSource
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO - set migration table name
|
|
|
|
// TODO - add limit to Up and Down method
|
|
|
|
|
|
|
|
func New(dbConfig mysql.Config) Migrator {
|
|
|
|
// OR: Read migrations from a folder:
|
|
|
|
migrations := &migrate.FileMigrationSource{
|
2024-01-15 10:33:24 +00:00
|
|
|
Dir: "./repository/mysql/migration",
|
2024-01-14 15:53:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return Migrator{dbConfig: dbConfig, dialect: "mysql", migrations: migrations}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m Migrator) Up() {
|
|
|
|
fmt.Println("mysql add= ", fmt.Sprintf("%s:%s@(%s:%d)/%s?parseTime=true",
|
|
|
|
m.dbConfig.Username, m.dbConfig.Password, m.dbConfig.Host, m.dbConfig.Port, m.dbConfig.DBName))
|
|
|
|
db, err := sql.Open(m.dialect, fmt.Sprintf("%s:%s@(%s:%d)/%s?parseTime=true",
|
|
|
|
m.dbConfig.Username, m.dbConfig.Password, m.dbConfig.Host, m.dbConfig.Port, m.dbConfig.DBName))
|
|
|
|
if err != nil {
|
2024-01-15 10:33:24 +00:00
|
|
|
panic(fmt.Errorf("can't open mysql db: %w", err))
|
2024-01-14 15:53:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
n, err := migrate.Exec(db, m.dialect, m.migrations, migrate.Up)
|
|
|
|
if err != nil {
|
2024-01-15 10:33:24 +00:00
|
|
|
panic(fmt.Errorf("can't apply migrations: %w", err))
|
2024-01-14 15:53:37 +00:00
|
|
|
}
|
|
|
|
fmt.Printf("Applied %d migrations!\n", n)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m Migrator) Down() {
|
|
|
|
db, err := sql.Open(m.dialect, fmt.Sprintf("%s:%s@(%s:%d)/%s?parseTime=true",
|
|
|
|
m.dbConfig.Username, m.dbConfig.Password, m.dbConfig.Host, m.dbConfig.Port, m.dbConfig.DBName))
|
|
|
|
if err != nil {
|
2024-01-15 10:33:24 +00:00
|
|
|
panic(fmt.Errorf("can't open mysql db: %w", err))
|
2024-01-14 15:53:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
n, err := migrate.Exec(db, m.dialect, m.migrations, migrate.Down)
|
|
|
|
if err != nil {
|
2024-01-15 10:33:24 +00:00
|
|
|
panic(fmt.Errorf("can't rollback migrations: %w", err))
|
2024-01-14 15:53:37 +00:00
|
|
|
}
|
|
|
|
fmt.Printf("Rollbacked %d migrations!\n", n)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m Migrator) Status() {
|
|
|
|
// TODO - add status
|
|
|
|
}
|