1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
|
package dbconf
import (
"encoding/json"
"errors"
"io/ioutil"
cferr "github.com/cloudflare/cfssl/errors"
"github.com/cloudflare/cfssl/log"
"github.com/jmoiron/sqlx"
)
// DBConfig contains the database driver name and configuration to be passed to Open
type DBConfig struct {
DriverName string `json:"driver"`
DataSourceName string `json:"data_source"`
}
// LoadFile attempts to load the db configuration file stored at the path
// and returns the configuration. On error, it returns nil.
func LoadFile(path string) (cfg *DBConfig, err error) {
log.Debugf("loading db configuration file from %s", path)
if path == "" {
return nil, cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy, errors.New("invalid path"))
}
var body []byte
body, err = ioutil.ReadFile(path)
if err != nil {
return nil, cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy, errors.New("could not read configuration file"))
}
cfg = &DBConfig{}
err = json.Unmarshal(body, &cfg)
if err != nil {
return nil, cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy,
errors.New("failed to unmarshal configuration: "+err.Error()))
}
if cfg.DataSourceName == "" || cfg.DriverName == "" {
return nil, cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy, errors.New("invalid db configuration"))
}
return
}
// DBFromConfig opens a sql.DB from settings in a db config file
func DBFromConfig(path string) (db *sqlx.DB, err error) {
var dbCfg *DBConfig
dbCfg, err = LoadFile(path)
if err != nil {
return nil, err
}
return sqlx.Open(dbCfg.DriverName, dbCfg.DataSourceName)
}
|