Skip to content

Commit

Permalink
Option-ize mysql storage driver
Browse files Browse the repository at this point in the history
  • Loading branch information
jessepeterson committed Aug 7, 2021
1 parent 52dd9ae commit cb51bf0
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 10 deletions.
7 changes: 6 additions & 1 deletion cmd/cli/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import (
"github.com/micromdm/nanomdm/storage/allmulti"
"github.com/micromdm/nanomdm/storage/file"
"github.com/micromdm/nanomdm/storage/mysql"

_ "github.com/go-sql-driver/mysql"
)

type StringAccumulator []string
Expand Down Expand Up @@ -57,7 +59,10 @@ func (s *Storage) Parse(logger log.Logger) (storage.AllStorage, error) {
}
mdmStorage = append(mdmStorage, fileStorage)
case "mysql":
mysqlStorage, err := mysql.New(dsn, logger.With("storage", "mysql"))
mysqlStorage, err := mysql.New(
mysql.WithDSN(dsn),
mysql.WithLogger(logger.With("storage", "mysql")),
)
if err != nil {
return nil, err
}
Expand Down
55 changes: 46 additions & 9 deletions storage/mysql/mysql.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@ import (
"github.com/micromdm/nanomdm/cryptoutil"
"github.com/micromdm/nanomdm/log"
"github.com/micromdm/nanomdm/mdm"

_ "github.com/go-sql-driver/mysql"
)

var ErrNoCert = errors.New("no certificate in MDM Request")
Expand All @@ -20,16 +18,55 @@ type MySQLStorage struct {
db *sql.DB
}

func New(conn string, logger log.Logger) (*MySQLStorage, error) {
db, err := sql.Open("mysql", conn)
if err != nil {
return nil, err
type config struct {
driver string
dsn string
db *sql.DB
logger log.Logger
}

type Option func(*config)

func WithLogger(logger log.Logger) Option {
return func(c *config) {
c.logger = logger
}
err = db.Ping()
if err != nil {
}

func WithDSN(dsn string) Option {
return func(c *config) {
c.dsn = dsn
}
}

func WithDriver(driver string) Option {
return func(c *config) {
c.driver = driver
}
}

func WithDB(db *sql.DB) Option {
return func(c *config) {
c.db = db
}
}

func New(opts ...Option) (*MySQLStorage, error) {
cfg := &config{logger: log.NopLogger, driver: "mysql"}
for _, opt := range opts {
opt(cfg)
}
var err error
if cfg.db == nil {
cfg.db, err = sql.Open(cfg.driver, cfg.dsn)
if err != nil {
return nil, err
}
}
if err = cfg.db.Ping(); err != nil {
return nil, err
}
return &MySQLStorage{db: db, logger: logger}, nil
return &MySQLStorage{db: cfg.db, logger: cfg.logger}, nil
}

// nullEmptyString returns a NULL string if s is empty.
Expand Down

0 comments on commit cb51bf0

Please sign in to comment.