Skip to content

Commit

Permalink
fix(be): migrations
Browse files Browse the repository at this point in the history
  • Loading branch information
fiftin committed Jan 23, 2022
1 parent ae0a471 commit 7737567
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 15 deletions.
2 changes: 1 addition & 1 deletion db/Migration.go
Expand Up @@ -19,7 +19,7 @@ func (m Migration) HumanoidVersion() string {

func GetMigrations() []Migration {
return []Migration{
{},
{Version: "0.0.0"},
{Version: "1.0.0"},
{Version: "1.2.0"},
{Version: "1.3.0"},
Expand Down
7 changes: 2 additions & 5 deletions db/sql/SqlDb.go
Expand Up @@ -343,9 +343,6 @@ func (d *SqlDb) Sql() *gorp.DbMap {
}

func (d *SqlDb) IsInitialized() (bool, error) {
exists, err := d.sql.SelectInt(d.prepareQuery("select count(1) from migrations"))
if err != nil {
return false, nil
}
return exists > 0, nil
_, err := d.sql.SelectInt(d.prepareQuery("select count(1) from migrations"))
return err == nil, nil
}
38 changes: 29 additions & 9 deletions db/sql/migration.go
Expand Up @@ -62,24 +62,44 @@ func (d *SqlDb) prepareMigration(query string) string {

// IsMigrationApplied queries the database to see if a migration table with this version id exists already
func (d *SqlDb) IsMigrationApplied(migration db.Migration) (bool, error) {
exists, err := d.sql.SelectInt(d.prepareQuery("select count(1) as ex from migrations where migration=?"), migration.Version)
initialized, err := d.IsInitialized()

if err == nil {
return exists > 0, nil
if err != nil {
return false, err
}

if !initialized {
return false, nil
}

fmt.Println("Creating migrations table")
query := d.prepareMigration(initialSQL)
_, err = d.exec(query)
exists, err := d.sql.SelectInt(
d.prepareQuery("select count(1) as ex from migrations where version = ?"),
migration.Version)

if err != nil {
panic(err)
return false, err
}

return d.IsMigrationApplied(migration)
return exists > 0, nil
}

// ApplyMigration runs executes a database migration
func (d *SqlDb) ApplyMigration(migration db.Migration) error {
initialized, err := d.IsInitialized()

if err != nil {
return err
}

if !initialized {
fmt.Println("Creating migrations table")
query := d.prepareMigration(initialSQL)
_, err = d.exec(query)
if err != nil {
return err
}
}

tx, err := d.sql.Begin()
if err != nil {
return err
Expand All @@ -103,7 +123,7 @@ func (d *SqlDb) ApplyMigration(migration db.Migration) error {
}
}

_, err = tx.Exec(d.prepareQuery("insert into migrations(migration, upgraded_date) values (?, ?)"), migration.Version, time.Now())
_, err = tx.Exec(d.prepareQuery("insert into migrations(version, upgraded_date) values (?, ?)"), migration.Version, time.Now())
if err != nil {
handleRollbackError(tx.Rollback())
return err
Expand Down

0 comments on commit 7737567

Please sign in to comment.