db_config.go 1.5 KB

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