Skip to content

Commit

Permalink
Check during startup if the database schema is up to date
Browse files Browse the repository at this point in the history
  • Loading branch information
fguillot committed Mar 21, 2020
1 parent 05b88c8 commit e494d6e
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
4 changes: 4 additions & 0 deletions cli/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,10 @@ func Parse() {
return
}

if err := database.IsSchemaUpToDate(db); err != nil {
logger.Fatal(`You must run the SQL migrations, %v`, err)
}

store := storage.NewStorage(db)

if flagResetFeedErrors {
Expand Down
14 changes: 12 additions & 2 deletions database/migration.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ const schemaVersion = 28
// Migrate executes database migrations.
func Migrate(db *sql.DB) {
var currentVersion int
db.QueryRow(`select version from schema_version`).Scan(&currentVersion)
db.QueryRow(`SELECT version FROM schema_version`).Scan(&currentVersion)

fmt.Println("Current schema version:", currentVersion)
fmt.Println("Latest schema version:", schemaVersion)
Expand All @@ -43,7 +43,7 @@ func Migrate(db *sql.DB) {
logger.Fatal("[Migrate] %v", err)
}

if _, err := tx.Exec(`insert into schema_version (version) values($1)`, version); err != nil {
if _, err := tx.Exec(`INSERT INTO schema_version (version) VALUES ($1)`, version); err != nil {
tx.Rollback()
logger.Fatal("[Migrate] %v", err)
}
Expand All @@ -53,3 +53,13 @@ func Migrate(db *sql.DB) {
}
}
}

// IsSchemaUpToDate checks if the database schema is up to date.
func IsSchemaUpToDate(db *sql.DB) error {
var currentVersion int
db.QueryRow(`SELECT version FROM schema_version`).Scan(&currentVersion)
if currentVersion != schemaVersion {
return fmt.Errorf(`database schema is not up to date: current=v%d expected=v%d`, currentVersion, schemaVersion)
}
return nil
}

0 comments on commit e494d6e

Please sign in to comment.