miniflux/database/migration.go

66 lines
1.7 KiB
Go
Raw Normal View History

2018-08-02 05:28:45 +02:00
// Copyright 2018 Frédéric Guillot. All rights reserved.
2017-11-20 06:10:04 +01:00
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.
2018-08-25 06:51:50 +02:00
package database // import "miniflux.app/database"
2017-11-20 06:10:04 +01:00
import (
2018-08-02 05:28:45 +02:00
"database/sql"
2017-11-20 06:10:04 +01:00
"fmt"
"strconv"
2017-11-23 07:22:33 +01:00
2018-08-25 06:51:50 +02:00
"miniflux.app/logger"
2017-11-20 06:10:04 +01:00
)
const schemaVersion = 36
2017-11-20 06:10:04 +01:00
2018-08-02 05:28:45 +02:00
// Migrate executes database migrations.
func Migrate(db *sql.DB) {
2017-11-20 06:10:04 +01:00
var currentVersion int
db.QueryRow(`SELECT version FROM schema_version`).Scan(&currentVersion)
2017-11-20 06:10:04 +01:00
fmt.Println("Current schema version:", currentVersion)
fmt.Println("Latest schema version:", schemaVersion)
for version := currentVersion + 1; version <= schemaVersion; version++ {
fmt.Println("Migrating to version:", version)
2018-08-02 05:28:45 +02:00
tx, err := db.Begin()
2017-11-20 06:10:04 +01:00
if err != nil {
2018-08-02 05:28:45 +02:00
logger.Fatal("[Migrate] %v", err)
2017-11-20 06:10:04 +01:00
}
2018-08-02 05:28:45 +02:00
rawSQL := SqlMap["schema_version_"+strconv.Itoa(version)]
2017-11-20 06:10:04 +01:00
// fmt.Println(rawSQL)
_, err = tx.Exec(rawSQL)
if err != nil {
tx.Rollback()
2018-08-02 05:28:45 +02:00
logger.Fatal("[Migrate] %v", err)
2017-11-20 06:10:04 +01:00
}
if _, err := tx.Exec(`delete from schema_version`); err != nil {
tx.Rollback()
2018-08-02 05:28:45 +02:00
logger.Fatal("[Migrate] %v", err)
2017-11-20 06:10:04 +01:00
}
if _, err := tx.Exec(`INSERT INTO schema_version (version) VALUES ($1)`, version); err != nil {
2017-11-20 06:10:04 +01:00
tx.Rollback()
2018-08-02 05:28:45 +02:00
logger.Fatal("[Migrate] %v", err)
2017-11-20 06:10:04 +01:00
}
if err := tx.Commit(); err != nil {
2018-08-02 05:28:45 +02:00
logger.Fatal("[Migrate] %v", err)
2017-11-20 06:10:04 +01:00
}
}
}
// 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(`the database schema is not up to date: current=v%d expected=v%d`, currentVersion, schemaVersion)
}
return nil
}