dex/db/migrate.go

72 lines
1.6 KiB
Go
Raw Normal View History

2015-08-20 04:10:36 +05:30
package db
import (
2016-02-09 05:31:16 +05:30
"errors"
2015-08-20 04:10:36 +05:30
"fmt"
"github.com/go-gorp/gorp"
2016-02-09 05:31:16 +05:30
"github.com/rubenv/sql-migrate"
2015-08-20 04:10:36 +05:30
"github.com/coreos/dex/db/migrations"
)
const (
2016-02-09 05:31:16 +05:30
migrationTable = "dex_migrations"
migrationDir = "db/migrations"
2015-08-20 04:10:36 +05:30
)
func init() {
migrate.SetTable(migrationTable)
}
func MigrateToLatest(dbMap *gorp.DbMap) (int, error) {
2016-02-09 05:31:16 +05:30
source, dialect, err := migrationSource(dbMap)
if err != nil {
return 0, err
}
return migrate.Exec(dbMap.Db, dialect, source, migrate.Up)
2015-08-20 04:10:36 +05:30
}
func MigrateMaxMigrations(dbMap *gorp.DbMap, max int) (int, error) {
2016-02-09 05:31:16 +05:30
source, dialect, err := migrationSource(dbMap)
if err != nil {
return 0, err
}
return migrate.ExecMax(dbMap.Db, dialect, source, migrate.Up, max)
2015-08-20 04:10:36 +05:30
}
func GetPlannedMigrations(dbMap *gorp.DbMap) ([]*migrate.PlannedMigration, error) {
2016-02-09 05:31:16 +05:30
source, dialect, err := migrationSource(dbMap)
if err != nil {
return nil, err
}
migrations, _, err := migrate.PlanMigration(dbMap.Db, dialect, source, migrate.Up, 0)
2015-08-20 04:10:36 +05:30
return migrations, err
}
func DropMigrationsTable(dbMap *gorp.DbMap) error {
2016-02-09 05:31:16 +05:30
qt := fmt.Sprintf("DROP TABLE IF EXISTS %s;", dbMap.Dialect.QuotedTableForQuery("", migrationTable))
_, err := dbMap.Exec(qt)
2015-08-20 04:10:36 +05:30
return err
}
2016-02-09 05:31:16 +05:30
func migrationSource(dbMap *gorp.DbMap) (src migrate.MigrationSource, dialect string, err error) {
switch dbMap.Dialect.(type) {
case gorp.PostgresDialect:
return migrations.PostgresMigrations, "postgres", nil
2016-02-09 05:31:16 +05:30
case gorp.SqliteDialect:
src = &migrate.MemoryMigrationSource{
Migrations: []*migrate.Migration{
{
Id: "dex.sql",
Up: []string{sqlite3Migration},
},
},
}
return src, "sqlite3", nil
default:
return nil, "", errors.New("unsupported migration driver")
2015-08-20 04:10:36 +05:30
}
}