2024-07-12 00:16:17 +00:00
|
|
|
package main
|
|
|
|
|
2024-07-12 00:28:57 +00:00
|
|
|
import (
|
|
|
|
"log"
|
|
|
|
"os"
|
|
|
|
)
|
|
|
|
|
2024-07-12 00:16:17 +00:00
|
|
|
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,
|
|
|
|
}
|
|
|
|
}
|
2024-07-12 00:28:57 +00:00
|
|
|
|
2024-07-12 01:15:37 +00:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2024-07-12 00:28:57 +00:00
|
|
|
// 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.
|
2024-07-12 01:16:44 +00:00
|
|
|
func (m *Migration) Apply(db DB) error {
|
2024-07-12 01:15:37 +00:00
|
|
|
migrationSql, err := m.Sql()
|
2024-07-12 00:28:57 +00:00
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
log.Printf("SQL: %s", migrationSql)
|
|
|
|
|
|
|
|
err = db.Execute(migrationSql)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
|
|
|
|
}
|