ooni-probe-cli/cmd/ooniprobe/internal/database/database.go
Simone Basso 6d3a4f1db8
refactor: merge dnsx and errorsx into netxlite (#517)
When preparing a tutorial for netxlite, I figured it is easier
to tell people "hey, this is the package you should use for all
low-level networking stuff" rather than introducing people to
a set of packages working together where some piece of functionality
is here and some other piece is there.

Part of https://github.com/ooni/probe/issues/1591
2021-09-28 12:42:01 +02:00

73 lines
1.5 KiB
Go

package database
import (
"context"
"database/sql"
"embed"
"github.com/apex/log"
"github.com/ooni/probe-cli/v3/internal/netxlite"
migrate "github.com/rubenv/sql-migrate"
"upper.io/db.v3/lib/sqlbuilder"
"upper.io/db.v3/sqlite"
)
//go:embed migrations/*.sql
var efs embed.FS
func readAsset(path string) ([]byte, error) {
filep, err := efs.Open(path)
if err != nil {
return nil, err
}
return netxlite.ReadAllContext(context.Background(), filep)
}
func readAssetDir(path string) ([]string, error) {
var out []string
lst, err := efs.ReadDir(path)
if err != nil {
return nil, err
}
for _, e := range lst {
out = append(out, e.Name())
}
return out, nil
}
// RunMigrations runs the database migrations
func RunMigrations(db *sql.DB) error {
log.Debugf("running migrations")
migrations := &migrate.AssetMigrationSource{
Asset: readAsset,
AssetDir: readAssetDir,
Dir: "migrations",
}
n, err := migrate.Exec(db, "sqlite3", migrations, migrate.Up)
if err != nil {
return err
}
log.Debugf("performed %d migrations", n)
return nil
}
// Connect to the database
func Connect(path string) (db sqlbuilder.Database, err error) {
settings := sqlite.ConnectionURL{
Database: path,
Options: map[string]string{"_foreign_keys": "1"},
}
sess, err := sqlite.Open(settings)
if err != nil {
log.WithError(err).Error("failed to open the DB")
return nil, err
}
err = RunMigrations(sess.Driver().(*sql.DB))
if err != nil {
log.WithError(err).Error("failed to run DB migration")
return nil, err
}
return sess, err
}