Example #1
0
// Revert runs the down migration on the database. True will be returned if the migration was completed.
func (m Migration) Revert() (bool, error) {
	// Return early if the migration isn't active
	active, err := db.MigrationActive(m.ID)
	if err != nil {
		return false, err
	}
	if active == false {
		return false, nil
	}

	sql, err := FS.ReadFile(m.DownPath)
	if err != nil {
		return false, err
	}

	tx, err := db.Conn.Begin()
	if err != nil {
		return false, err
	}

	_, err = tx.Exec(string(sql))
	if err != nil {
		log.Printf("[Error] Unable to revert migration (%s): %v", m.ID, err)
		if err := tx.Rollback(); err != nil {
			log.Printf("[Error] Unable to roll back transaction: %v", err)
			return false, err
		}
		return false, err
	}

	err = tx.Commit()
	if err != nil {
		log.Printf("[Error] Unable to commit transaction: %v", err)
		return false, err
	}

	// Update the migration log
	err = db.DeleteMigration(m.ID)
	if err != nil {
		return false, err
	}

	fmt.Printf("Migration (%s) reverted\n", m.ID)

	return true, nil
}
Example #2
0
// Apply runs the up migration on the database.
func (m Migration) Apply() error {
	// Return early if the migration is already active
	active, err := db.MigrationActive(m.ID)
	if err != nil {
		return err
	}
	if active {
		return nil
	}

	sql, err := FS.ReadFile(m.UpPath)
	if err != nil {
		return err
	}

	tx, err := db.Conn.Begin()
	if err != nil {
		return err
	}

	_, err = tx.Exec(string(sql))
	if err != nil {
		log.Printf("[Error] Unable to apply migration (%s): %v", m.ID, err)
		if err := tx.Rollback(); err != nil {
			log.Printf("[Error] Unable to roll back transaction: %v", err)
			return err
		}
		return err
	}

	err = tx.Commit()
	if err != nil {
		log.Printf("[Error] Unable to commit transaction: %v", err)
		return err
	}

	// Update the migration log
	err = db.InsertMigration(m.ID)
	if err != nil {
		return err
	}

	fmt.Printf("Migration(%s) applied\n", m.ID)

	return nil
}