diff --git a/documize/api/request/init.go b/documize/api/request/init.go index d3c61537..b62eef3c 100644 --- a/documize/api/request/init.go +++ b/documize/api/request/init.go @@ -1,6 +1,7 @@ package request import ( + "errors" "fmt" "os" "strings" @@ -35,6 +36,10 @@ func (dr *databaseRequest) MakeTx() (err error) { func init() { var err error + var upgrade = "false" + + environment.GetString(&upgrade, "upgrade", false, + "to upgrade the database set to 'true' (only this Documize binary must be running)", nil) environment.GetString(&connectionString, "db", true, `"username:password@protocol(hostname:port)/databasename" for example "fred:bloggs@tcp(localhost:3306)/documize"`, @@ -65,6 +70,24 @@ func init() { log.Info("database.Check(Db) !OK, going into setup mode") } + migrations, err := database.Migrations(ConfigString("DATABASE", "last_migration")) + if err != nil { + log.Error("Unable to find required database migrations: ", err) + os.Exit(2) + } + if len(migrations) > 0 { + if strings.ToLower(upgrade) != "true" { + log.Error("database migrations are required", + errors.New("the -upgrade flag is not 'true'")) + os.Exit(2) + + } + if err := migrations.Migrate(); err != nil { + log.Error("Unable to run database migration: ", err) + os.Exit(2) + } + } + return false // value not changed }) } diff --git a/documize/database/migrate.go b/documize/database/migrate.go index 636bab89..c7e83f2b 100644 --- a/documize/database/migrate.go +++ b/documize/database/migrate.go @@ -1 +1,54 @@ package database + +import ( + "fmt" + "sort" + "strings" + + "github.com/documize/community/documize/web" +) + +const migrationsDir = "bindata/scripts/migrate" + +// MigrationsT holds a list of migration sql files to run. +type MigrationsT []string + +// Migrations returns a list of the migrations to update the database as required for this version of the code. +func Migrations(last_migration string) (MigrationsT, error) { + + last_migration = strings.TrimPrefix(strings.TrimSuffix(last_migration, `"`), `"`) + + files, err := web.AssetDir(migrationsDir) + if err != nil { + return nil, err + } + sort.Strings(files) + + ret := make(MigrationsT, 0, len(files)) + + hadLast := false + + for _, v := range files { + if v == last_migration { + hadLast = true + } else { + if hadLast { + ret = append(ret, v) + } + } + } + + return ret, nil +} + +// Migrate the database as required. +func (m MigrationsT) Migrate() error { + for _, v := range m { + buf, err := web.Asset(migrationsDir + "/" + v) + if err != nil { + return err + } + fmt.Println("DEBUG database.Migrate() ", v, ":\n", string(buf)) // TODO actually run the SQL + } + return nil +}