aboutsummaryrefslogtreecommitdiffstats
path: root/internal
diff options
context:
space:
mode:
authorEugene Triguba <eugenetriguba@gmail.com>2024-01-06 16:23:02 -0500
committerEugene Triguba <eugenetriguba@gmail.com>2024-01-06 16:23:02 -0500
commit263ce3e4b368a50efee1a53af11a76a12af0a119 (patch)
tree8917754f3b43830604f6ad4c7115934ed633f1d8 /internal
parentFix syntax (diff)
downloadcli-263ce3e4b368a50efee1a53af11a76a12af0a119.zip
Break up migration repo into fs and db with a service
Diffstat (limited to 'internal')
-rw-r--r--internal/commands/create.go12
-rw-r--r--internal/commands/list.go21
-rw-r--r--internal/commands/migrate.go29
-rw-r--r--internal/configloader/configloader.go10
-rw-r--r--internal/models/migration.go15
-rw-r--r--internal/models/migration_test.go75
-rw-r--r--internal/repositories/migration.go176
-rw-r--r--internal/repositories/migration_db_repo.go131
-rw-r--r--internal/repositories/migration_fs_repo.go114
-rw-r--r--internal/services/migration.go109
-rw-r--r--internal/storage/db.go (renamed from internal/storage/storage.go)0
-rw-r--r--internal/storage/db_test.go (renamed from internal/storage/storage_test.go)41
-rw-r--r--internal/storage/dbtest/dbtest.go (renamed from internal/dbtest/dbtest.go)0
13 files changed, 436 insertions, 297 deletions
diff --git a/internal/commands/create.go b/internal/commands/create.go
index 9372157..57f4c69 100644
--- a/internal/commands/create.go
+++ b/internal/commands/create.go
@@ -10,7 +10,7 @@ import (
"github.com/eugenetriguba/bolt/internal/configloader"
"github.com/eugenetriguba/bolt/internal/models"
"github.com/eugenetriguba/bolt/internal/repositories"
- "github.com/eugenetriguba/bolt/internal/storage"
+ "github.com/eugenetriguba/bolt/internal/services"
"github.com/google/subcommands"
)
@@ -48,24 +48,20 @@ func (cmd *CreateCmd) Execute(
return subcommands.ExitFailure
}
- db, err := storage.DBConnect(
- cfg.Connection.Driver,
- storage.DBConnectionString(&cfg.Connection),
- )
+ migrationFsRepo, err := repositories.NewMigrationFsRepo(cfg.MigrationsDir)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return subcommands.ExitFailure
}
- defer db.Close()
- migrationRepo, err := repositories.NewMigrationRepo(db, cfg)
+ migrationService := services.NewMigrationService(nil, migrationFsRepo)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return subcommands.ExitFailure
}
migration := models.NewMigration(time.Now(), cmd.message)
- err = migrationRepo.Create(migration)
+ err = migrationService.CreateMigration(migration)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return subcommands.ExitFailure
diff --git a/internal/commands/list.go b/internal/commands/list.go
index 0f03712..8224820 100644
--- a/internal/commands/list.go
+++ b/internal/commands/list.go
@@ -8,13 +8,15 @@ import (
"github.com/eugenetriguba/bolt/internal/configloader"
"github.com/eugenetriguba/bolt/internal/repositories"
+ "github.com/eugenetriguba/bolt/internal/services"
"github.com/eugenetriguba/bolt/internal/storage"
"github.com/google/subcommands"
)
type ListCmd struct{}
-func (*ListCmd) Name() string { return "list" }
+func (*ListCmd) Name() string { return "list" }
+
func (*ListCmd) Synopsis() string { return "List the database migrations and their statuses." }
func (*ListCmd) Usage() string {
return `list:
@@ -24,7 +26,11 @@ func (*ListCmd) Usage() string {
func (m *ListCmd) SetFlags(f *flag.FlagSet) {}
-func (m *ListCmd) Execute(_ context.Context, f *flag.FlagSet, _ ...interface{}) subcommands.ExitStatus {
+func (m *ListCmd) Execute(
+ _ context.Context,
+ f *flag.FlagSet,
+ _ ...interface{},
+) subcommands.ExitStatus {
cfg, err := configloader.NewConfig()
if err != nil {
fmt.Fprintln(os.Stderr, err)
@@ -41,13 +47,20 @@ func (m *ListCmd) Execute(_ context.Context, f *flag.FlagSet, _ ...interface{})
}
defer db.Close()
- migrationRepo, err := repositories.NewMigrationRepo(db, cfg)
+ migrationDBRepo, err := repositories.NewMigrationDBRepo(db)
+ if err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ return subcommands.ExitFailure
+ }
+
+ migrationFsRepo, err := repositories.NewMigrationFsRepo(cfg.MigrationsDir)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return subcommands.ExitFailure
}
- migrations, err := migrationRepo.List()
+ migrationService := services.NewMigrationService(migrationDBRepo, migrationFsRepo)
+ migrations, err := migrationService.ListMigrations(services.SortOrderAsc)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return subcommands.ExitFailure
diff --git a/internal/commands/migrate.go b/internal/commands/migrate.go
index df1377a..7c7a228 100644
--- a/internal/commands/migrate.go
+++ b/internal/commands/migrate.go
@@ -8,13 +8,15 @@ import (
"github.com/eugenetriguba/bolt/internal/configloader"
"github.com/eugenetriguba/bolt/internal/repositories"
+ "github.com/eugenetriguba/bolt/internal/services"
"github.com/eugenetriguba/bolt/internal/storage"
"github.com/google/subcommands"
)
type MigrateCmd struct{}
-func (*MigrateCmd) Name() string { return "migrate" }
+func (*MigrateCmd) Name() string { return "migrate" }
+
func (*MigrateCmd) Synopsis() string { return "Migrate the database to the latest migration." }
func (*MigrateCmd) Usage() string {
return `migrate:
@@ -24,7 +26,11 @@ func (*MigrateCmd) Usage() string {
func (m *MigrateCmd) SetFlags(f *flag.FlagSet) {}
-func (m *MigrateCmd) Execute(_ context.Context, f *flag.FlagSet, _ ...interface{}) subcommands.ExitStatus {
+func (m *MigrateCmd) Execute(
+ _ context.Context,
+ f *flag.FlagSet,
+ _ ...interface{},
+) subcommands.ExitStatus {
cfg, err := configloader.NewConfig()
if err != nil {
fmt.Fprintln(os.Stderr, err)
@@ -41,28 +47,23 @@ func (m *MigrateCmd) Execute(_ context.Context, f *flag.FlagSet, _ ...interface{
}
defer db.Close()
- migrationRepo, err := repositories.NewMigrationRepo(db, cfg)
+ migrationDBRepo, err := repositories.NewMigrationDBRepo(db)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return subcommands.ExitFailure
}
- migrations, err := migrationRepo.List()
+ migrationFsRepo, err := repositories.NewMigrationFsRepo(cfg.MigrationsDir)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return subcommands.ExitFailure
}
- for _, migration := range migrations {
- if !migration.Applied {
- fmt.Printf("Applying migration for %s..\n", migration.Dirname())
- err = migrationRepo.Apply(migration)
- if err != nil {
- fmt.Fprintln(os.Stderr, err)
- return subcommands.ExitFailure
- }
- fmt.Printf("%s [x]\n", migration.Dirname())
- }
+ migrationService := services.NewMigrationService(migrationDBRepo, migrationFsRepo)
+ err = migrationService.ApplyAllMigrations()
+ if err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ return subcommands.ExitFailure
}
return subcommands.ExitSuccess
diff --git a/internal/configloader/configloader.go b/internal/configloader/configloader.go
index 4ef542d..b97e1bc 100644
--- a/internal/configloader/configloader.go
+++ b/internal/configloader/configloader.go
@@ -38,12 +38,12 @@ type Config struct {
}
type ConnectionConfig struct {
- Host string `toml:"host" envconfig:"BOLT_CONNECTION_HOST"`
- Port int `toml:"port" envconfig:"BOLT_CONNECTION_PORT"`
- User string `toml:"user" envconfig:"BOLT_CONNECTION_USER"`
+ Host string `toml:"host" envconfig:"BOLT_CONNECTION_HOST"`
+ Port int `toml:"port" envconfig:"BOLT_CONNECTION_PORT"`
+ User string `toml:"user" envconfig:"BOLT_CONNECTION_USER"`
Password string `toml:"password" envconfig:"BOLT_CONNECTION_PASSWORD"`
- DBName string `toml:"dbname" envconfig:"BOLT_CONNECTION_DBNAME"`
- Driver string `toml:"driver" envconfig:"BOLT_CONNECTION_DRIVER"`
+ DBName string `toml:"dbname" envconfig:"BOLT_CONNECTION_DBNAME"`
+ Driver string `toml:"driver" envconfig:"BOLT_CONNECTION_DRIVER"`
}
func NewConfig() (*Config, error) {
diff --git a/internal/models/migration.go b/internal/models/migration.go
index a4b694c..a449c44 100644
--- a/internal/models/migration.go
+++ b/internal/models/migration.go
@@ -12,19 +12,16 @@ type Migration struct {
Applied bool
}
-func NewMigration(ts time.Time, message string) *Migration {
+func NewMigration(timestamp time.Time, message string) *Migration {
version := fmt.Sprintf(
- "%d%02d%02d%02d%02d%02d", ts.Year(), ts.Month(), ts.Day(),
- ts.Hour(), ts.Minute(), ts.Second(),
+ "%d%02d%02d%02d%02d%02d",
+ timestamp.Year(), timestamp.Month(), timestamp.Day(),
+ timestamp.Hour(), timestamp.Minute(), timestamp.Second(),
)
return &Migration{Version: version, Message: message, Applied: false}
}
-func (m *Migration) Dirname() string {
- return fmt.Sprintf("%s_%s", m.Version, m.normalizedMessage())
-}
-
-func (m *Migration) normalizedMessage() string {
+func (m *Migration) NormalizedMessage() string {
lowercaseMessage := strings.ToLower(m.Message)
trimmedMessage := strings.TrimSpace(lowercaseMessage)
return strings.ReplaceAll(trimmedMessage, " ", "_")
@@ -36,7 +33,7 @@ func (m *Migration) String() string {
checked = "x"
}
- message := m.normalizedMessage()
+ message := m.NormalizedMessage()
if len(message) > 0 {
message = fmt.Sprintf("- %s ", message)
}
diff --git a/internal/models/migration_test.go b/internal/models/migration_test.go
index 166f264..b25f137 100644
--- a/internal/models/migration_test.go
+++ b/internal/models/migration_test.go
@@ -4,66 +4,37 @@ import (
"testing"
"time"
+ "gotest.tools/v3/assert"
+
"github.com/eugenetriguba/bolt/internal/models"
)
-var ts = time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC)
+var timestamp = time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC)
-func TestMigration(t *testing.T) {
- type test struct {
- inputTs time.Time
- inputMessage string
- expectedVersion string
- expectedDirname string
- expectedString string
- }
- tests := []test{
- // Ensure message is trimmed of spaces, lowercased, and
- // using underscores for spaces in normalized version.
- {
- inputTs: ts,
- inputMessage: " test MESSAGE ",
- expectedVersion: "20200101000000",
- expectedDirname: "20200101000000_test_message",
- expectedString: "20200101000000 - test_message - [ ]",
- },
- // Ensure an empty message means there is no message shown for
- // dirname and string.
- {
- inputTs: ts,
- inputMessage: "",
- expectedVersion: "20200101000000",
- expectedDirname: "20200101000000_",
- expectedString: "20200101000000 - [ ]",
- },
- }
+func TestNewMigrationInit(t *testing.T) {
+ m := models.NewMigration(timestamp, "test message")
- for _, tc := range tests {
- m := models.NewMigration(tc.inputTs, tc.inputMessage)
- if m.Version != tc.expectedVersion {
- t.Fatalf("got: %v, expected: %v", m.Version, tc.expectedVersion)
- }
- if m.Message != tc.inputMessage {
- t.Fatalf("got: %v, expected: %v", m.Message, tc.inputMessage)
- }
- if m.Applied != false {
- t.Fatalf("got: %v, expected: %v", m.Applied, false)
- }
- if m.Dirname() != tc.expectedDirname {
- t.Fatalf("got: %v, expected: %v", m.Dirname(), tc.expectedDirname)
- }
- if m.String() != tc.expectedString {
- t.Fatalf("got: %v, expected: %v", m.String(), tc.expectedString)
- }
- }
+ assert.Equal(t, m.Version, "20200101000000")
+ assert.Equal(t, m.Message, "test message")
+ assert.Equal(t, m.Applied, false)
}
func TestAppliedNewMigration(t *testing.T) {
- m := models.NewMigration(ts, "test message")
+ m := models.NewMigration(timestamp, "test_message")
+
+ assert.Equal(t, m.String(), "20200101000000 - test_message - [ ]")
m.Applied = true
+ assert.Equal(t, m.String(), "20200101000000 - test_message - [x]")
+}
+
+func TestNewMigrationMessageIsNormalized(t *testing.T) {
+ m := models.NewMigration(timestamp, " test MESSAGE ")
+ assert.Equal(t, m.NormalizedMessage(), "test_message")
+}
+
+func TestEmptyMessageMigration(t *testing.T) {
+ m := models.NewMigration(timestamp, "")
- expectedString := "20200101000000 - test_message - [x]"
- if m.String() != expectedString {
- t.Fatalf("got: %v, expected: %v", m.String(), expectedString)
- }
+ assert.Equal(t, "", m.NormalizedMessage())
+ assert.Equal(t, "20200101000000 - [ ]", m.String())
}
diff --git a/internal/repositories/migration.go b/internal/repositories/migration.go
deleted file mode 100644
index e7d1f73..0000000
--- a/internal/repositories/migration.go
+++ /dev/null
@@ -1,176 +0,0 @@
-package repositories
-
-import (
- "database/sql"
- "errors"
- "fmt"
- "os"
- "path/filepath"
- "sort"
- "strings"
-
- "github.com/eugenetriguba/bolt/internal/configloader"
- "github.com/eugenetriguba/bolt/internal/models"
-)
-
-type ErrIsNotDir struct {
- path string
-}
-
-func (e *ErrIsNotDir) Error() string {
- return fmt.Sprintf(
- "The specified migrations directory path '%s' is not a directory.",
- e.path,
- )
-}
-
-type MigrationRepo struct {
- // The database connection that will be used
- // to look up migrations that have already been
- // applied.
- db *sql.DB
- cfg *configloader.Config
-}
-
-// Create a new Migration Repo.
-//
-// This handles the interactions with applying
-// and reverting migrations.
-func NewMigrationRepo(db *sql.DB, cfg *configloader.Config) (*MigrationRepo, error) {
- _, err := db.Exec(`
- CREATE TABLE IF NOT EXISTS bolt_migrations(
- version CHARACTER(14) PRIMARY KEY NOT NULL
- );
- `)
- if err != nil {
- return nil, err
- }
-
- fileInfo, err := os.Stat(cfg.MigrationsDir)
- if errors.Is(err, os.ErrNotExist) {
- err = os.MkdirAll(cfg.MigrationsDir, 0755)
- if err != nil {
- return nil, err
- }
- } else if err != nil {
- return nil, err
- } else if err == nil && !fileInfo.IsDir() {
- return nil, &ErrIsNotDir{path: cfg.MigrationsDir}
- }
-
- return &MigrationRepo{db: db, cfg: cfg}, nil
-}
-
-func (mr *MigrationRepo) Create(m *models.Migration) error {
- path := filepath.Join(mr.cfg.MigrationsDir, m.Dirname())
- err := os.Mkdir(path, 0755)
- if err != nil {
- return err
- }
-
- _, err = os.Create(filepath.Join(path, "upgrade.sql"))
- if err != nil {
- return err
- }
-
- return nil
-}
-
-func (mr *MigrationRepo) List() ([]*models.Migration, error) {
- rows, err := mr.db.Query(`SELECT version FROM bolt_migrations;`)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
-
- migrations := make(map[string]*models.Migration)
- for rows.Next() {
- var version string
- err := rows.Scan(&version)
- if err != nil {
- return nil, err
- }
- version = strings.TrimSpace(version)
- migrations[version] = &models.Migration{
- Version: version,
- Message: "",
- Applied: true,
- }
- }
-
- entries, err := os.ReadDir(mr.cfg.MigrationsDir)
- if err != nil {
- return nil, err
- }
- for _, entry := range entries {
- parts := strings.SplitN(entry.Name(), "_", 2)
- if len(parts) != 2 {
- return nil, errors.New(
- fmt.Sprintf(
- "%s is an invalid migration name. Expected a "+
- "migration directory of the format <version>_<message>.",
- entry.Name(),
- ),
- )
- }
- version := parts[0]
- message := parts[1]
- val, ok := migrations[version]
- if ok {
- val.Message = message
- } else {
- migrations[version] = &models.Migration{
- Version: version,
- Message: message,
- Applied: false,
- }
- }
- }
-
- values := make([]*models.Migration, 0, len(migrations))
- for _, value := range migrations {
- values = append(values, value)
- }
-
- sort.Slice(values, func(i, j int) bool {
- return values[i].Dirname() < values[j].Dirname()
- })
-
- return values, nil
-}
-
-func (mr *MigrationRepo) Apply(migration *models.Migration) error {
- tx, err := mr.db.Begin()
- if err != nil {
- return err
- }
- defer tx.Rollback()
-
- upgradeScriptPath := filepath.Join(
- mr.cfg.MigrationsDir, migration.Dirname(), "upgrade.sql",
- )
- contents, err := os.ReadFile(upgradeScriptPath)
- if err != nil {
- return err
- }
-
- _, err = tx.Exec(string(contents))
- if err != nil {
- return err
- }
-
- _, err = tx.Exec(
- `INSERT INTO bolt_migrations(version) VALUES ($1);`,
- migration.Version,
- )
- if err != nil {
- return err
- }
- migration.Applied = true
- err = tx.Commit()
- if err != nil {
- return err
- }
-
- return nil
-}
diff --git a/internal/repositories/migration_db_repo.go b/internal/repositories/migration_db_repo.go
new file mode 100644
index 0000000..378fa02
--- /dev/null
+++ b/internal/repositories/migration_db_repo.go
@@ -0,0 +1,131 @@
+package repositories
+
+import (
+ "database/sql"
+ "errors"
+ "strings"
+
+ "github.com/eugenetriguba/bolt/internal/models"
+)
+
+type MigrationDBRepo struct {
+ db *sql.DB
+}
+
+// NewMigrationDBRepo initializes the MigrationRepo with a
+// database and ensures the bolt_migration table exists.
+func NewMigrationDBRepo(db *sql.DB) (*MigrationDBRepo, error) {
+ _, err := db.Exec(`
+ CREATE TABLE IF NOT EXISTS bolt_migrations(
+ version CHARACTER(14) PRIMARY KEY NOT NULL
+ );
+ `)
+ if err != nil {
+ return nil, err
+ }
+
+ return &MigrationDBRepo{db: db}, nil
+}
+
+func (mr *MigrationDBRepo) List() (map[string]*models.Migration, error) {
+ rows, err := mr.db.Query(`SELECT version FROM bolt_migrations;`)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ var migrations = make(map[string]*models.Migration)
+ for rows.Next() {
+ var version string
+ err := rows.Scan(&version)
+ if err != nil {
+ return nil, err
+ }
+ migrations[version] = &models.Migration{
+ Version: strings.TrimSpace(version),
+ Message: "",
+ Applied: true,
+ }
+ }
+
+ return migrations, nil
+}
+
+// IsApplied checks if the given version has been applied.
+//
+// Note that applied will be false when the version isn't
+// applied and when the version might be applied, but there
+// was an error. Check err first before looking at whether the
+// version is applied.
+func (mr *MigrationDBRepo) IsApplied(version string) (applied bool, err error) {
+ row := mr.db.QueryRow(`SELECT 1 FROM bolt_migrations WHERE version = $1`, version)
+ err = row.Scan()
+ if errors.Is(err, sql.ErrNoRows) {
+ return false, nil
+ }
+ if err != nil {
+ return false, err
+ }
+ return true, nil
+}
+
+// Apply applies a migration by executing the corresponding upgrade script
+// and added the applied migration version into the bolt_migrations table.
+func (mr *MigrationDBRepo) Apply(upgradeScript string, migration *models.Migration) error {
+ tx, err := mr.db.Begin()
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback()
+
+ _, err = tx.Exec(upgradeScript)
+ if err != nil {
+ return err
+ }
+
+ _, err = tx.Exec(
+ `INSERT INTO bolt_migrations(version) VALUES ($1);`,
+ migration.Version,
+ )
+ if err != nil {
+ return err
+ }
+ err = tx.Commit()
+ if err != nil {
+ return err
+ }
+
+ migration.Applied = true
+ return nil
+}
+
+// Revert reverts a migration by executing the corresponding downgrade script
+// and deleting the migration version into the bolt_migrations table.
+func (mr *MigrationDBRepo) Revert(downgradeScript string, migration *models.Migration) error {
+ tx, err := mr.db.Begin()
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback()
+
+ _, err = tx.Exec(downgradeScript)
+ if err != nil {
+ return err
+ }
+
+ _, err = tx.Exec(
+ `DELETE FROM bolt_migrations WHERE version = $1;`,
+ migration.Version,
+ )
+ if err != nil {
+ return err
+ }
+
+ err = tx.Commit()
+ if err != nil {
+ return err
+ }
+
+ migration.Applied = false
+ return nil
+}
diff --git a/internal/repositories/migration_fs_repo.go b/internal/repositories/migration_fs_repo.go
new file mode 100644
index 0000000..e064c72
--- /dev/null
+++ b/internal/repositories/migration_fs_repo.go
@@ -0,0 +1,114 @@
+package repositories
+
+import (
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/eugenetriguba/bolt/internal/models"
+)
+
+type ErrIsNotDir struct {
+ path string
+}
+
+func (e *ErrIsNotDir) Error() string {
+ return fmt.Sprintf(
+ "The specified migrations directory path '%s' is not a directory.",
+ e.path,
+ )
+}
+
+type MigrationFsRepo struct {
+ migrationsDirPath string
+}
+
+func NewMigrationFsRepo(migrationsDirPath string) (*MigrationFsRepo, error) {
+ fileInfo, err := os.Stat(migrationsDirPath)
+ if errors.Is(err, os.ErrNotExist) {
+ err = os.MkdirAll(migrationsDirPath, 0755)
+ if err != nil {
+ return nil, err
+ }
+ } else if err != nil {
+ return nil, err
+ } else if err == nil && !fileInfo.IsDir() {
+ return nil, &ErrIsNotDir{path: migrationsDirPath}
+ }
+
+ return &MigrationFsRepo{migrationsDirPath: migrationsDirPath}, nil
+}
+
+func (mr *MigrationFsRepo) Create(m *models.Migration) error {
+ path := filepath.Join(
+ mr.migrationsDirPath,
+ fmt.Sprintf("%s_%s", m.Version, m.NormalizedMessage()),
+ )
+
+ _, err := os.Create(filepath.Join(path, "upgrade.sql"))
+ if err != nil {
+ return err
+ }
+
+ _, err = os.Create(filepath.Join(path, "downgrade.sql"))
+ if err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func (mr *MigrationFsRepo) List() (map[string]*models.Migration, error) {
+ entries, err := os.ReadDir(mr.migrationsDirPath)
+ if err != nil {
+ return nil, err
+ }
+
+ var migrations = make(map[string]*models.Migration)
+ for _, entry := range entries {
+ parts := strings.SplitN(entry.Name(), "_", 2)
+ if len(parts) != 2 {
+ return nil, fmt.Errorf(
+ "%s is an invalid migration name: expected a "+
+ "migration directory of the format <version>_<message>",
+ entry.Name(),
+ )
+ }
+ migrations[parts[0]] = &models.Migration{
+ Version: parts[0],
+ Message: parts[1],
+ Applied: false,
+ }
+ }
+
+ return migrations, nil
+}
+
+func (mr *MigrationFsRepo) ReadUpgradeScript(migration *models.Migration) (string, error) {
+ upgradeScriptPath := filepath.Join(
+ mr.migrationsDirPath,
+ fmt.Sprintf("%s_%s", migration.Version, migration.NormalizedMessage()),
+ "upgrade.sql",
+ )
+ return mr.readScriptContents(upgradeScriptPath)
+}
+
+func (mr *MigrationFsRepo) ReadDowngradeScript(migration *models.Migration) (string, error) {
+ downgradeScriptPath := filepath.Join(
+ mr.migrationsDirPath,
+ fmt.Sprintf("%s_%s", migration.Version, migration.NormalizedMessage()),
+ "downgrade.sql",
+ )
+ return mr.readScriptContents(downgradeScriptPath)
+}
+
+func (mr *MigrationFsRepo) readScriptContents(scriptPath string) (string, error) {
+ contents, err := os.ReadFile(scriptPath)
+ if err != nil {
+ return "", err
+ }
+
+ return string(contents), nil
+}
diff --git a/internal/services/migration.go b/internal/services/migration.go
new file mode 100644
index 0000000..622ffc3
--- /dev/null
+++ b/internal/services/migration.go
@@ -0,0 +1,109 @@
+package services
+
+import (
+ "sort"
+
+ "github.com/eugenetriguba/bolt/internal/models"
+ "github.com/eugenetriguba/bolt/internal/repositories"
+)
+
+type MigrationService struct {
+ dbRepo *repositories.MigrationDBRepo
+ fsRepo *repositories.MigrationFsRepo
+}
+
+func NewMigrationService(
+ dbRepo *repositories.MigrationDBRepo,
+ fsRepo *repositories.MigrationFsRepo,
+) *MigrationService {
+ return &MigrationService{dbRepo: dbRepo, fsRepo: fsRepo}
+}
+
+type sortOrder int
+
+const (
+ SortOrderDesc sortOrder = iota
+ SortOrderAsc
+)
+
+func (ms *MigrationService) ApplyAllMigrations() error {
+ migrations, err := ms.ListMigrations(SortOrderAsc)
+ if err != nil {
+ return err
+ }
+
+ for _, migration := range migrations {
+ if !migration.Applied {
+ ms.ApplyMigration(migration)
+ }
+ }
+
+ return nil
+}
+
+func (ms *MigrationService) ApplyMigration(migration *models.Migration) error {
+ scriptContents, err := ms.fsRepo.ReadUpgradeScript(migration)
+ if err != nil {
+ return err
+ }
+
+ err = ms.dbRepo.Apply(scriptContents, migration)
+ if err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func (ms *MigrationService) RevertMigration(migration *models.Migration) error {
+ scriptContents, err := ms.fsRepo.ReadDowngradeScript(migration)
+ if err != nil {
+ return err
+ }
+
+ err = ms.dbRepo.Revert(scriptContents, migration)
+ if err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func (ms *MigrationService) CreateMigration(migration *models.Migration) error {
+ return ms.fsRepo.Create(migration)
+}
+
+func (ms *MigrationService) ListMigrations(order sortOrder) ([]*models.Migration, error) {
+ // Assumption: All migration versions that have been applied
+ // to the database exist locally in the list of filesystem migrations.
+ // This would hold true unless someone decided to apply a migration and,
+ // for whatever reason, delete it later from their filesystem.
+ migrations, err := ms.fsRepo.List()
+ if err != nil {
+ return nil, err
+ }
+
+ appliedMigrations, err := ms.dbRepo.List()
+ if err != nil {
+ return nil, err
+ }
+
+ var flatMigrations []*models.Migration
+ for _, migration := range migrations {
+ _, ok := appliedMigrations[migration.Version]
+ if ok {
+ migration.Applied = true
+ }
+ flatMigrations = append(flatMigrations, migration)
+ }
+
+ sort.Slice(flatMigrations, func(i, j int) bool {
+ if order == SortOrderAsc {
+ return flatMigrations[i].Version < flatMigrations[j].Version
+ } else {
+ return flatMigrations[i].Version > flatMigrations[j].Version
+ }
+ })
+
+ return flatMigrations, nil
+}
diff --git a/internal/storage/storage.go b/internal/storage/db.go
index 25db283..25db283 100644
--- a/internal/storage/storage.go
+++ b/internal/storage/db.go
diff --git a/internal/storage/storage_test.go b/internal/storage/db_test.go
index 3b36a34..2583cfd 100644
--- a/internal/storage/storage_test.go
+++ b/internal/storage/db_test.go
@@ -2,52 +2,37 @@ package storage_test
import (
"fmt"
- "strings"
"testing"
"github.com/eugenetriguba/bolt/internal/configloader"
- "github.com/eugenetriguba/bolt/internal/dbtest"
"github.com/eugenetriguba/bolt/internal/storage"
+ "github.com/eugenetriguba/bolt/internal/storage/dbtest"
+ "gotest.tools/v3/assert"
)
func TestDBConnectWithPostgres(t *testing.T) {
cfg, err := dbtest.NewTestConnectionConfig("postgres")
- if err != nil {
- t.Fatal(err)
- }
+ assert.NilError(t, err)
conn, err := storage.DBConnect(cfg.Driver, storage.DBConnectionString(cfg))
- if err != nil {
- t.Fatalf("could not connect to postgres db using %s: %s",
- storage.DBConnectionString(cfg),
- err,
- )
- }
+ assert.NilError(t, err)
defer conn.Close()
_, err = conn.Exec("SELECT 1;")
- if err != nil {
- t.Fatalf("could not execute query against postgres db: %s", err)
- }
+ assert.NilError(t, err)
}
func TestDBConnectMalformedConnectionString(t *testing.T) {
_, err := storage.DBConnect("postgres", "pizza=123")
- if err == nil || (err != nil && !strings.Contains(err.Error(), "connection refused")) {
- t.Fatalf("expected connection error, got %s", err)
- }
+ assert.ErrorContains(t, err, "connection refused")
}
func TestDBConnectUnsupportedDriver(t *testing.T) {
cfg, err := dbtest.NewTestConnectionConfig("redis")
- if err != nil {
- t.Fatal(err)
- }
+ assert.NilError(t, err)
_, err = storage.DBConnect(cfg.Driver, storage.DBConnectionString(cfg))
- if err == nil || (err != nil && !strings.Contains(err.Error(), `unknown driver "redis"`)) {
- t.Fatalf("expected bad driver, got %s", err)
- }
+ assert.ErrorContains(t, err, `unknown driver "redis"`)
}
func TestDBConnectionString(t *testing.T) {
@@ -59,14 +44,12 @@ func TestDBConnectionString(t *testing.T) {
Password: "supersecretpassword",
DBName: "testdb",
}
+
+ cs := storage.DBConnectionString(&cfg)
+
expectedConnectionString := fmt.Sprintf(
"host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
cfg.Host, cfg.Port, cfg.User, cfg.Password, cfg.DBName,
)
-
- cs := storage.DBConnectionString(&cfg)
-
- if cs != expectedConnectionString {
- t.Fatalf("Expected %s, got %s", expectedConnectionString, cs)
- }
+ assert.Equal(t, cs, expectedConnectionString)
}
diff --git a/internal/dbtest/dbtest.go b/internal/storage/dbtest/dbtest.go
index c53c04a..c53c04a 100644
--- a/internal/dbtest/dbtest.go
+++ b/internal/storage/dbtest/dbtest.go