Redmage/db/db.go

42 lines
1,017 B
Go
Raw Normal View History

package db
import (
"database/sql"
"io/fs"
_ "github.com/mattn/go-sqlite3"
"github.com/pressly/goose/v3"
2024-04-08 15:48:45 +07:00
sqldblogger "github.com/simukti/sqldb-logger"
"github.com/tigorlazuardi/redmage/config"
2024-04-07 23:41:00 +07:00
"github.com/tigorlazuardi/redmage/pkg/errs"
)
var Migrations fs.FS
func Open(cfg *config.Config) (*sql.DB, error) {
2024-04-07 23:41:00 +07:00
driver := cfg.String("db.driver")
2024-04-08 15:48:45 +07:00
dsn := cfg.String("db.string")
db, err := sql.Open(driver, dsn)
if err != nil {
2024-04-07 23:41:00 +07:00
return db, errs.Wrapw(err, "failed to open database", "driver", driver)
}
if cfg.Bool("db.automigrate") {
2024-04-07 23:41:00 +07:00
goose.SetLogger(&gooseLogger{})
goose.SetBaseFS(Migrations)
2024-04-07 23:41:00 +07:00
if err := goose.SetDialect(driver); err != nil {
return db, errs.Wrapw(err, "failed to set goose dialect", "dialect", driver)
}
if err := goose.Up(db, "db/migrations"); err != nil {
2024-04-07 23:41:00 +07:00
return db, errs.Wrapw(err, "failed to migrate database", "dialect", driver)
}
}
2024-04-08 15:48:45 +07:00
db = sqldblogger.OpenDriver(dsn, db.Driver(), sqlLogger{},
sqldblogger.WithSQLQueryAsMessage(true),
)
return db, err
}