config.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package services
  2. import (
  3. "flag"
  4. "github.com/pkg/errors"
  5. )
  6. type DbConfig struct {
  7. Host string `json:"host,omitempty" yaml:"host,omitempty"`
  8. Port int `json:"port,omitempty" yaml:"port,omitempty"`
  9. Schema string `json:"schema,omitempty" yaml:"schema,omitempty"`
  10. User string `json:"user,omitempty" yaml:"user,omitempty"`
  11. Pwd string `json:"pwd,omitempty" yaml:"pwd,omitempty"`
  12. Tables []string `json:"tables,omitempty" yaml:"tables,omitempty"`
  13. }
  14. var (
  15. dbConfigFlag *DbConfig
  16. cfgFilePathFlag string
  17. )
  18. func init() {
  19. dbConfigFlag = &DbConfig{}
  20. flag.StringVar(&dbConfigFlag.Host, "h", "", "database host")
  21. flag.IntVar(&dbConfigFlag.Port, "p", 0, "database port")
  22. flag.StringVar(&dbConfigFlag.Schema, "s", "", "database schema")
  23. flag.StringVar(&dbConfigFlag.User, "u", "", "database user")
  24. flag.StringVar(&dbConfigFlag.Pwd, "P", "", "database password")
  25. flag.StringVar(&cfgFilePathFlag, "c", "", "database config file path")
  26. }
  27. func (cfg *DbConfig) IsZero() bool {
  28. if cfg == nil {
  29. return true
  30. }
  31. if cfg.Host != "" ||
  32. cfg.Port != 0 ||
  33. cfg.Schema != "" ||
  34. cfg.User != "" ||
  35. cfg.Pwd != "" {
  36. return false
  37. }
  38. return true
  39. }
  40. func (cfg *DbConfig) FixDefaultValues() error {
  41. if cfg == nil {
  42. return errors.New("can not fix values of nil object")
  43. }
  44. if cfg.Schema == "" {
  45. return errors.New("can not fix default values with empty database schema")
  46. }
  47. if cfg.Pwd == "" {
  48. return errors.New("can not fix default values with empty database password")
  49. }
  50. if cfg.Host == "" {
  51. cfg.Host = "localhost"
  52. }
  53. if cfg.Port == 0 {
  54. cfg.Port = 3306
  55. } else if cfg.Port < 1 || cfg.Port > 65535 {
  56. return errors.Errorf("invalid database port %d", cfg.Port)
  57. }
  58. if cfg.User == "" {
  59. cfg.User = "root"
  60. }
  61. return nil
  62. }