ch-go – github.com/ClickHouse/ch-go Index | Examples | Files | Directories

package ch

import "github.com/ClickHouse/ch-go"

Package ch implements ClickHouse client.

Index

Examples

Constants

const (
	DefaultDatabase         = "default"
	DefaultUser             = "default"
	DefaultHost             = "127.0.0.1"
	DefaultPort             = 9000
	DefaultDialTimeout      = 1 * time.Second
	DefaultHandshakeTimeout = 300 * time.Second
)

Defaults for connection.

Variables

var ErrClosed = errors.New("client is closed")

ErrClosed means that client was already closed.

Functions

func CompressionStrings

func CompressionStrings() []string

CompressionStrings returns a slice of all String values of the enum

func IsErr

func IsErr(err error, codes ...proto.Error) bool

IsErr reports whether err is error with provided exception codes.

func IsException

func IsException(err error) bool

IsException reports whether err is Exception.

func Parameters

func Parameters(m map[string]any) []proto.Parameter

Parameters is helper for building Query.Parameters.

EXPERIMENTAL.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client implements ClickHouse binary protocol client on top of single TCP connection.

func Connect

func Connect(ctx context.Context, conn net.Conn, opt Options) (*Client, error)

Connect performs handshake with ClickHouse server and initializes application level connection.

func Dial

func Dial(ctx context.Context, opt Options) (c *Client, err error)

Dial dials requested address and establishes TCP connection to ClickHouse server, performing handshake.

func (*Client) Close

func (c *Client) Close() error

Close closes underlying connection and frees all resources, rendering Client to unusable state.

func (*Client) Do

func (c *Client) Do(ctx context.Context, q Query) (err error)

Do performs Query on ClickHouse server.

func (*Client) IsClosed

func (c *Client) IsClosed() bool

IsClosed indicates that connection is closed.

func (*Client) Ping

func (c *Client) Ping(ctx context.Context) (err error)

Ping server.

Do not call concurrently with Do.

func (*Client) ServerInfo

func (c *Client) ServerInfo() proto.ServerHello

ServerInfo returns server information.

type Compression

type Compression byte

Compression setting.

Trade bandwidth for CPU.

const (
	// CompressionDisabled disables compression. Lowest CPU overhead.
	CompressionDisabled Compression = iota
	// CompressionLZ4 enables LZ4 compression for data. Medium CPU overhead.
	CompressionLZ4
	// CompressionZSTD enables ZStandard compression. High CPU overhead.
	CompressionZSTD
	// CompressionNone uses no compression but data has checksums.
	CompressionNone
)

func CompressionString

func CompressionString(s string) (Compression, error)

CompressionString retrieves an enum value from the enum constants string name. Throws an error if the param is not part of the enum.

func CompressionValues

func CompressionValues() []Compression

CompressionValues returns all values of the enum

func (Compression) IsACompression

func (i Compression) IsACompression() bool

IsACompression returns "true" if the value is listed in the enum definition. "false" otherwise

func (Compression) String

func (i Compression) String() string

type CorruptedDataErr

type CorruptedDataErr struct {
	Actual    city.U128
	Reference city.U128
	RawSize   int
	DataSize  int
}

CorruptedDataErr means that provided hash mismatch with calculated.

func (*CorruptedDataErr) Error

func (c *CorruptedDataErr) Error() string

type Dialer

type Dialer interface {
	DialContext(ctx context.Context, network, address string) (net.Conn, error)
}

A Dialer dials using a context.

type Exception

type Exception struct {
	Code    proto.Error
	Name    string
	Message string
	Stack   string
	Next    []Exception // non-nil only for top exception
}

Exception is server-side error.

func AsException

func AsException(err error) (*Exception, bool)

AsException finds first *Exception in err chain.

func (*Exception) Error

func (e *Exception) Error() string

func (*Exception) IsCode

func (e *Exception) IsCode(codes ...proto.Error) bool

type Log

type Log = proto.Log

type Options

type Options struct {
	Logger      *zap.Logger // defaults to Nop.
	Address     string      // 127.0.0.1:9000
	Database    string      // "default"
	User        string      // "default"
	Password    string      // blank string by default
	QuotaKey    string      // blank string by default
	Compression Compression // disabled by default
	Settings    []Setting   // none by default

	Dialer      Dialer        // defaults to net.Dialer
	DialTimeout time.Duration // defaults to 1s
	TLS         *tls.Config   // no TLS is used by default

	ProtocolVersion  int           // force protocol version, optional
	HandshakeTimeout time.Duration // longer lasting handshake is a case for ClickHouse cloud idle instances, defaults to 5m

	// Additional OpenTelemetry instrumentation that will capture query body
	// and other parameters.
	//
	// Note: OpenTelemetry context propagation works without this option too.
	OpenTelemetryInstrumentation bool
	TracerProvider               trace.TracerProvider
	MeterProvider                metric.MeterProvider
	// contains filtered or unexported fields
}

Options for Client. Zero value is valid.

type ProfileEvent

type ProfileEvent = proto.ProfileEvent

type ProfileEventType

type ProfileEventType = proto.ProfileEventType

type Query

type Query struct {
	// Body of query, like "SELECT 1".
	Body string
	// QueryID is ID of query, defaults to new UUIDv4.
	QueryID string
	// QuotaKey of query, optional.
	QuotaKey string

	// Input columns for INSERT operations.
	Input proto.Input
	// OnInput is called to allow ingesting more data to Input.
	//
	// The io.EOF reports that no more input should be ingested.
	//
	// Optional, single block is ingested from Input if not provided,
	// but query will fail if Input is set but has zero rows.
	OnInput func(ctx context.Context) error

	// Result columns for SELECT operations.
	Result proto.Result
	// OnResult is called when Result is filled with result block.
	//
	// Optional, but query will fail of more than one block is received
	// and no OnResult is provided.
	OnResult func(ctx context.Context, block proto.Block) error

	// OnProgress is optional progress handler. The progress value contain
	// difference, so progress should be accumulated if needed.
	OnProgress func(ctx context.Context, p proto.Progress) error
	// OnProfile is optional handler for profiling data.
	OnProfile func(ctx context.Context, p proto.Profile) error
	// OnProfileEvent is optional handler for profiling event stream data.
	OnProfileEvent func(ctx context.Context, e ProfileEvent) error
	// OnLog is optional handler for server log entry.
	OnLog func(ctx context.Context, l Log) error

	// Settings are optional query-scoped settings. Can override client settings.
	Settings []Setting

	// EXPERIMENTAL: parameters for query.
	Parameters []proto.Parameter

	// Secret is optional inter-server per-cluster secret for Distributed queries.
	//
	// See https://clickhouse.com/docs/en/engines/table-engines/special/distributed/#distributed-clusters
	Secret string

	// InitialUser is optional initial user for Distributed queries.
	InitialUser string

	// ExternalData is optional data for server to load.
	//
	// https://clickhouse.com/docs/en/engines/table-engines/special/external-data/
	ExternalData []proto.InputColumn
	// ExternalTable name. Defaults to _data.
	ExternalTable string
}

Query to ClickHouse.

Example (MultipleInputColumns)

Code:

{
	var (
		body      proto.ColStr
		name      proto.ColStr
		sevText   proto.ColEnum
		sevNumber proto.ColUInt8

		ts  = new(proto.ColDateTime64).WithPrecision(proto.PrecisionNano)
		arr = new(proto.ColStr).Array() // Array(String)
		now = time.Date(2010, 1, 1, 10, 22, 33, 345678, time.UTC)
	)
	// Append 10 rows.
	for i := 0; i < 10; i++ {
		body.AppendBytes([]byte("Hello"))
		ts.Append(now)
		name.Append("name")
		sevText.Values = append(sevText.Values, "INFO")
		sevNumber = append(sevNumber, 10)
		arr.Append([]string{"foo", "bar", "baz"})
	}
	input := proto.Input{
		{Name: "ts", Data: ts},
		{Name: "severity_text", Data: &sevText},
		{Name: "severity_number", Data: sevNumber},
		{Name: "body", Data: body},
		{Name: "name", Data: name},
		{Name: "arr", Data: arr},
	}
	fmt.Println(input.Into("logs"))

	// Output:
	// INSERT INTO "logs" ("ts","severity_text","severity_number","body","name","arr") VALUES
}

Output:

INSERT INTO "logs" ("ts","severity_text","severity_number","body","name","arr") VALUES

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server is basic ClickHouse server.

func NewServer

func NewServer(opt ServerOptions) *Server

NewServer returns new ClickHouse Server.

func (*Server) Serve

func (s *Server) Serve(ln net.Listener) error

Serve connections on net.Listener.

type ServerConn

type ServerConn struct {
	// contains filtered or unexported fields
}

ServerConn wraps Server connection.

func (*ServerConn) Handle

func (c *ServerConn) Handle() error

Handle connection.

type ServerOptions

type ServerOptions struct {
	Logger   *zap.Logger
	Timezone *time.Location
	OnError  func(err error)
}

ServerOptions wraps possible Server configuration.

type Setting

type Setting struct {
	Key, Value string
	Important  bool
}

Setting to send to server.

func SettingInt

func SettingInt(k string, v int) Setting

SettingInt returns Setting with integer value v.

Source Files

ch.go client.go compression_enum.go handshake.go ping.go query.go query_metrics.go query_params.go server.go

Directories

PathSynopsis
chpoolPackage chpool is a connection pool for ch.
chtPackage cht implements ClickHouse testing utilities, primarily end to end.
compressPackage compress implements compression support.
examples
examples/insert
internal
otelchPackage otelch provide OpenTelemetry instrumentation for go-faster/ch.
protoPackage proto implements ClickHouse wire protocol.
proto/cmd
proto/cmd/ch-gen-col
Version
v0.51.2
Published
Jan 26, 2023
Platform
js/wasm
Imports
26 packages
Last checked
now

Tools for package owners.