clickhouse/settings/settings.go

87 lines
2.3 KiB
Go
Raw Permalink Normal View History

2022-10-26 14:26:49 +03:00
package settings
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/url"
"strconv"
"git.bit5.ru/backend/errors"
)
// username/password - auth credentials
// database - select the current default database
// read_timeout/write_timeout - timeout in second
// no_delay - disable/enable the Nagle Algorithm for tcp socket (default is 'true' - disable)
// alt_hosts - comma separated list of single address host for load-balancing
// connection_open_strategy - random/in_order (default random).
// random - choose random server from set
// in_order - first live server is chosen in specified order
// block_size - maximum rows in block (default is 1000000). If the rows are larger then the data will be split into several blocks to send them to the server
// pool size - maximum amount of preallocated byte chunks used in queries (default is 100). Decrease this if you experience memory problems at the expense of more GC pressure and vice versa.
// debug - enable debug output (boolean value)
// Load
func Load(path string) (ClickhouseSettings, error) {
bytes, err := ioutil.ReadFile(path)
if err != nil {
return ClickhouseSettings{}, errors.WithStack(err)
}
settings := ClickhouseSettings{}
if err := json.Unmarshal(bytes, &settings); err != nil {
return ClickhouseSettings{}, errors.WithStack(err)
}
return settings, nil
}
// ClickhouseSettings
type ClickhouseSettings struct {
Host string `json:"host"`
Port int `json:"port"`
Database string `json:"database"`
Username string `json:"username"`
Password string `json:"password"`
Options map[string]json.RawMessage `json:"opts"`
}
func (s ClickhouseSettings) DSN() string {
options := url.Values{
"database": []string{s.Database},
}
if len(s.Username) > 0 {
options.Set("username", s.Username)
}
if len(s.Password) > 0 {
options.Set("password", s.Password)
}
for name, value := range s.Options {
var valueString string
if value[0] == '"' {
if err := json.Unmarshal(value, &valueString); err != nil {
panic(err)
}
} else {
var valueInt int
if err := json.Unmarshal(value, &valueInt); err != nil {
panic(err)
}
valueString = strconv.Itoa(valueInt)
}
options.Set(name, valueString)
}
uri := url.URL{
Scheme: "tcp",
Host: fmt.Sprintf("%s:%d", s.Host, s.Port),
RawQuery: options.Encode(),
}
return uri.String()
}