clickhouse.go 2.0 KB

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