fathom/pkg/datastore/datastore.go

53 lines
1.2 KiB
Go
Raw Normal View History

package datastore
import (
2018-04-25 11:45:21 +00:00
"errors"
2018-05-08 10:31:51 +00:00
_ "github.com/go-sql-driver/mysql" // mysql driver
"github.com/jmoiron/sqlx"
2018-05-08 10:31:51 +00:00
//_ "github.com/lib/pq" // postgresql driver
"github.com/gobuffalo/packr"
2018-05-08 10:31:51 +00:00
_ "github.com/mattn/go-sqlite3" //sqlite3 driver
migrate "github.com/rubenv/sql-migrate"
log "github.com/sirupsen/logrus"
)
var dbx *sqlx.DB
2018-04-25 11:45:21 +00:00
// ErrNoResults is returned when a query yielded 0 results
var ErrNoResults = errors.New("datastore: query returned 0 results")
2018-04-25 11:45:21 +00:00
// Init creates a database connection pool (using sqlx)
2018-05-08 10:31:51 +00:00
func Init(c *Config) *sqlx.DB {
dbx = New(c)
// run migrations
2018-05-08 10:31:51 +00:00
runMigrations(c.Driver)
return dbx
}
// New creates a new database pool
2018-05-08 10:31:51 +00:00
func New(c *Config) *sqlx.DB {
dbx := sqlx.MustConnect(c.Driver, c.DSN())
return dbx
}
// TODO: Move to command (but still auto-run on boot).
func runMigrations(driver string) {
migrations := &migrate.PackrMigrationSource{
Box: packr.NewBox("./migrations/" + driver),
}
migrate.SetTable("migrations")
n, err := migrate.Exec(dbx.DB, driver, migrations, migrate.Up)
if err != nil {
log.Fatal("Database migrations failed: ", err)
}
if n > 0 {
log.Printf("Applied %d database migrations!\n", n)
}
}