From 0593f52c7b897873f016fdd82a8aa7d2ffa8e463 Mon Sep 17 00:00:00 2001 From: Eugene Triguba Date: Sat, 30 Dec 2023 17:32:25 -0500 Subject: Tweak migrations dir error handling --- internal/repositories/migration.go | 41 ++++++++++++++++++++++++++++++++------ 1 file changed, 35 insertions(+), 6 deletions(-) (limited to 'internal') diff --git a/internal/repositories/migration.go b/internal/repositories/migration.go index 488d838..efd29e3 100644 --- a/internal/repositories/migration.go +++ b/internal/repositories/migration.go @@ -2,20 +2,37 @@ package repositories import ( "database/sql" + "errors" + "fmt" + "os" + + "github.com/eugenetriguba/bolt/internal/config" ) +type IsNotDirError struct { + path string +} + +func (e *IsNotDirError) 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 + db *sql.DB + config *config.Config } // Create a new Migration Repo. // // This handles the interactions with applying // and reverting migrations. -func NewMigrationRepo(db *sql.DB) (*MigrationRepo, error) { +func NewMigrationRepo(db *sql.DB, c *config.Config) (*MigrationRepo, error) { _, err := db.Exec(` CREATE TABLE IF NOT EXISTS bolt_migrations( version CHARACTER(32) PRIMARY KEY NOT NULL @@ -25,18 +42,30 @@ func NewMigrationRepo(db *sql.DB) (*MigrationRepo, error) { return nil, err } - return &MigrationRepo{db: db}, nil + fileInfo, err := os.Stat(c.MigrationsDir) + if errors.Is(err, os.ErrNotExist) { + err = os.MkdirAll(c.MigrationsDir, 0755) + if err != nil { + return nil, err + } + } else if err != nil { + return nil, err + } else if err == nil && !fileInfo.IsDir() { + return nil, &IsNotDirError{path: c.MigrationsDir} + } + + return &MigrationRepo{db: db, config: c}, nil } -func (m *MigrationRepo) Apply() error { - tx, err := m.db.Begin() +func (mr *MigrationRepo) Create(message string) error { + tx, err := mr.db.Begin() if err != nil { return err } defer tx.Rollback() sqlStatement := `INSERT INTO applied_migration(version) VALUES ($1);` - _, err = m.db.Exec(sqlStatement) + _, err = mr.db.Exec(sqlStatement) if err != nil { return err } -- cgit v1.2.3