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

52 lines
1.2 KiB
Go
Raw Normal View History

package database
import (
"path/filepath"
"github.com/apex/log"
"github.com/jmoiron/sqlx"
2018-02-13 17:11:22 +01:00
_ "github.com/mattn/go-sqlite3" // this is needed to load the sqlite3 driver
2018-02-13 10:48:46 +01:00
ooni "github.com/openobservatory/gooni"
"github.com/openobservatory/gooni/internal/bindata"
"github.com/pkg/errors"
migrate "github.com/rubenv/sql-migrate"
)
// RunMigrations runs the database migrations
func RunMigrations(db *sqlx.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.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) (*sqlx.DB, error) {
db, err := sqlx.Connect("sqlite3", path)
if err != nil {
return nil, err
}
2018-02-13 17:11:22 +01:00
err = RunMigrations(db)
if err != nil {
return nil, err
}
return db, nil
}
2018-02-13 17:11:22 +01:00
// DefaultDatabasePath for the main database
func DefaultDatabasePath() (string, error) {
2018-02-13 10:48:46 +01:00
home, err := ooni.GetOONIHome()
if err != nil {
2018-02-13 10:48:46 +01:00
return "", errors.Wrap(err, "default database path")
}
2018-02-13 17:11:22 +01:00
return filepath.Join(home, "db", "main.sqlite3"), nil
}