miniflux/database/migration.go

56 lines
1.3 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-02 05:28:45 +02:00
package 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
2017-12-16 03:55:57 +01:00
"github.com/miniflux/miniflux/logger"
2017-11-20 06:10:04 +01:00
)
const schemaVersion = 20
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
2018-08-02 05:28:45 +02:00
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 {
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
}
}
}