config.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package database
  2. import (
  3. "fmt"
  4. "github.com/ClickHouse/clickhouse-go/v2"
  5. "strings"
  6. )
  7. type Config struct {
  8. Clickhouse configCH `yaml:"clickhouse"`
  9. }
  10. func (cfg Config) Invalidate() error {
  11. var err error
  12. if err = cfg.Clickhouse.Invalidate(); err != nil {
  13. return err
  14. }
  15. return nil
  16. }
  17. type configCH struct {
  18. Username string `json:"username" yaml:"username"`
  19. Password string `json:"password" yaml:"password"`
  20. Host string `json:"host" yaml:"host"`
  21. Port int `json:"port" yaml:"port"`
  22. Database string `json:"database" yaml:"database"`
  23. Params params `json:"params" yaml:"params"`
  24. }
  25. type params struct {
  26. Secure bool `json:"secure" yaml:"secure"`
  27. Compress string `json:"compress" yaml:"compress"`
  28. Timeout int `json:"timeout" yaml:"timeout"`
  29. ReadTimeout int `json:"read_timeout" yaml:"read-timeout"`
  30. WriteTimeout int `json:"write_timeout" yaml:"write-timeout"`
  31. }
  32. func (c configCH) Invalidate() error {
  33. if strings.TrimSpace(c.Username) == "" {
  34. c.Username = "default"
  35. }
  36. if strings.TrimSpace(c.Host) == "" {
  37. c.Host = "localhost"
  38. }
  39. if c.Port < 1 {
  40. c.Port = 9000
  41. }
  42. if strings.TrimSpace(c.Database) == "" {
  43. return fmt.Errorf("`clickhouse.database` must not be an empty string")
  44. }
  45. return c.Params.Invalidate()
  46. }
  47. func (p params) Invalidate() error {
  48. if p.Compress == "" {
  49. p.Compress = "lz4"
  50. }
  51. if _, ok := compressionCH[p.Compress]; !ok {
  52. return fmt.Errorf("illegal `clickhouse.params.compress`")
  53. }
  54. if p.Timeout < 1 {
  55. return fmt.Errorf("`clickhouse.params.timeout` must not be at least 1")
  56. }
  57. if p.ReadTimeout < 1 {
  58. return fmt.Errorf("`clickhouse.params.read-timeout` must not be at least 1")
  59. }
  60. if p.WriteTimeout < 1 {
  61. return fmt.Errorf("`clickhouse.params.write-timeout` must not be at least 1")
  62. }
  63. return nil
  64. }
  65. func (p params) CompressionMethod() clickhouse.CompressionMethod {
  66. return compressionCH[p.Compress]
  67. }