config.go 1.8 KB

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