aboutsummaryrefslogtreecommitdiffstats
path: root/internal/repositories
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/repositories
parentFix syntax (diff)
downloadcli-263ce3e4b368a50efee1a53af11a76a12af0a119.zip
Break up migration repo into fs and db with a service
Diffstat (limited to 'internal/repositories')
-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
3 files changed, 245 insertions, 176 deletions
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
+}