github.com/jxgolibs/go-oauth2-server@v1.0.1/util/migrations/migrate.go (about)

     1  package migrations
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/RichardKnop/go-oauth2-server/log"
     7  	"github.com/jinzhu/gorm"
     8  )
     9  
    10  // MigrationStage ...
    11  type MigrationStage struct {
    12  	Name     string
    13  	Function func(db *gorm.DB, name string) error
    14  }
    15  
    16  // Migrate ...
    17  func Migrate(db *gorm.DB, migrations []MigrationStage) error {
    18  	for _, m := range migrations {
    19  		if MigrationExists(db, m.Name) {
    20  			continue
    21  		}
    22  
    23  		if err := m.Function(db, m.Name); err != nil {
    24  			return err
    25  		}
    26  
    27  		if err := SaveMigration(db, m.Name); err != nil {
    28  			return err
    29  		}
    30  	}
    31  
    32  	return nil
    33  }
    34  
    35  // MigrateAll runs bootstrap, then all migration functions listed against
    36  // the specified database and logs any errors
    37  func MigrateAll(db *gorm.DB, migrationFunctions []func(*gorm.DB) error) {
    38  	if err := Bootstrap(db); err != nil {
    39  		log.ERROR.Print(err)
    40  	}
    41  
    42  	for _, m := range migrationFunctions {
    43  		if err := m(db); err != nil {
    44  			log.ERROR.Print(err)
    45  		}
    46  	}
    47  }
    48  
    49  // MigrationExists checks if the migration called migrationName has been run already
    50  func MigrationExists(db *gorm.DB, migrationName string) bool {
    51  	migration := new(Migration)
    52  	found := !db.Where("name = ?", migrationName).First(migration).RecordNotFound()
    53  
    54  	if found {
    55  		log.INFO.Printf("Skipping %s migration", migrationName)
    56  	} else {
    57  		log.INFO.Printf("Running %s migration", migrationName)
    58  	}
    59  
    60  	return found
    61  }
    62  
    63  // SaveMigration saves a migration to the migration table
    64  func SaveMigration(db *gorm.DB, migrationName string) error {
    65  	migration := new(Migration)
    66  	migration.Name = migrationName
    67  
    68  	if err := db.Create(migration).Error; err != nil {
    69  		log.ERROR.Printf("Error saving record to migrations table: %s", err)
    70  		return fmt.Errorf("Error saving record to migrations table: %s", err)
    71  	}
    72  
    73  	return nil
    74  }