cobble/migration.go
Marc Cataford 455054add2
All checks were successful
/ sast (push) Successful in 45s
/ tests (push) Successful in 48s
refactor: ApplyMigration > Apply, remove naming redundancy
2024-07-11 21:16:44 -04:00

66 lines
1.1 KiB
Go

package main
import (
"log"
"os"
)
type Migration struct {
Path string
Name string
Requires string
Run bool
}
func NewMigration(path string, name string, requires string) Migration {
return Migration{
Path: path,
Name: name,
Requires: requires,
Run: false,
}
}
func (m *Migration) Bytes() ([]byte, error) {
migrationPath := m.Path
migrationBytes, err := os.ReadFile(migrationPath)
if err != nil {
return []byte{}, err
}
return migrationBytes, nil
}
func (m *Migration) Text() (string, error) {
migrationBytes, err := m.Bytes()
return string(migrationBytes), err
}
func (m *Migration) Sql() (string, error) {
migrationBytes, err := m.Bytes()
return string(StripComments(migrationBytes)), err
}
// Applies a migration to the given database connection.
//
// If an error is returned while trying to read the migration file
// or execute the SQL it contains, the error is returned.
func (m *Migration) Apply(db DB) error {
migrationSql, err := m.Sql()
if err != nil {
return err
}
log.Printf("SQL: %s", migrationSql)
err = db.Execute(migrationSql)
if err != nil {
return err
}
return nil
}