config.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package clickhouse
  2. import (
  3. "fmt"
  4. "git.beejay.kim/Craft/Api/config"
  5. "github.com/ClickHouse/clickhouse-go/v2"
  6. "strings"
  7. )
  8. var compressionMap = map[string]clickhouse.CompressionMethod{
  9. "none": clickhouse.CompressionNone,
  10. "zstd": clickhouse.CompressionZSTD,
  11. "lz4": clickhouse.CompressionLZ4,
  12. "gzip": clickhouse.CompressionGZIP,
  13. "deflate": clickhouse.CompressionDeflate,
  14. "br": clickhouse.CompressionBrotli,
  15. }
  16. type Config struct {
  17. Username string `json:"username" yaml:"username"`
  18. Password string `json:"password" yaml:"password"`
  19. Host string `json:"host" yaml:"host"`
  20. Port int `json:"port" yaml:"port"`
  21. Database string `json:"database" yaml:"database"`
  22. Params params `json:"params" yaml:"params"`
  23. }
  24. type params struct {
  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 *Config) 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 config.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 config.Invalidate(&p)
  62. }