ooni-probe-cli/internal/database/database.go

48 lines
1.1 KiB
Go
Raw Normal View History

package database
import (
"database/sql"
"github.com/apex/log"
"github.com/ooni/probe-cli/internal/bindata"
migrate "github.com/rubenv/sql-migrate"
"upper.io/db.v3/lib/sqlbuilder"
"upper.io/db.v3/sqlite"
)
// RunMigrations runs the database migrations
func RunMigrations(db *sql.DB) error {
2018-02-13 17:11:22 +01:00
log.Debugf("running migrations")
migrations := &migrate.AssetMigrationSource{
Asset: bindata.Asset,
AssetDir: bindata.AssetDir,
Dir: "data/migrations",
}
n, err := migrate.Exec(db, "sqlite3", migrations, migrate.Up)
if err != nil {
return err
}
log.Debugf("performed %d migrations", n)
return nil
}
2018-02-13 17:11:22 +01:00
// Connect to the database
func Connect(path string) (db sqlbuilder.Database, err error) {
settings := sqlite.ConnectionURL{
Database: path,
2018-09-17 17:30:29 +02:00
Options: map[string]string{"_foreign_keys": "1"},
}
sess, err := sqlite.Open(settings)
2018-09-17 17:30:29 +02:00
if err != nil {
log.WithError(err).Error("failed to open the DB")
return nil, err
}
err = RunMigrations(sess.Driver().(*sql.DB))
2018-02-13 17:11:22 +01:00
if err != nil {
log.WithError(err).Error("failed to run DB migration")
return nil, err
2018-02-13 17:11:22 +01:00
}
return sess, err
}