chx

package
v0.16.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 4, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package chx is a thin ClickHouse client for analytics and long-term stores.

The write path uses the native clickhouse-go/v2 connection (driver.Conn), which speaks the columnar native protocol and supports PrepareBatch for large bulk inserts. Migrate applies the schema with skit/migrate (goose, ClickHouse dialect) from a migrations fs.FS the caller supplies, over a separate database/sql handle, because goose needs database/sql rather than the native conn.

ClickHouse suits analytics and long-term storage: finished, structured data in large batches, never a hot ingest path. Importing this package pulls in the clickhouse-go/v2 dependency; wire it in only when a ClickHouse endpoint is configured.

Usage

Apply the migrations once at startup, open the client, and write in batches:

//go:embed migrations/*.sql
var migrationsFS embed.FS

cfg := chx.Config{Addrs: []string{"clickhouse:9000"}, Database: "analytics"}
migrations, err := fs.Sub(migrationsFS, "migrations")
if err != nil { ... }
if err := chx.Migrate(ctx, cfg, migrations); err != nil { ... }

cl, err := chx.Open(ctx, cfg)
if err != nil { ... }
defer cl.Close()

batch, err := cl.PrepareBatch(ctx, "INSERT INTO events")
if err != nil { ... }
for _, e := range events {
    if err := batch.Append(e.ID, e.Name, e.At); err != nil { ... }
}
err = batch.Send()

Open does not migrate: schema changes stay an intentional step at startup, not a side effect of connecting. Conn exposes the native driver.Conn for anything the pass-throughs (Exec, Select, Query, PrepareBatch) do not cover.

Config

  • Addrs: native-protocol endpoints, host:port (ClickHouse listens on 9000).
  • Database, Username, Password: the database and the credentials.
  • DialTimeout: bound on dialing a connection (default 10s).
  • MaxOpenConns: pool size (0 = the driver default, 10).
  • Compression: LZ4 wire compression, worthwhile for large batches.
Example

Migrate once at startup, open the client, write a batch and read it back. The examples need a running ClickHouse, so go test builds them but does not run them.

package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"time"

	"github.com/assanoff/skit/chx"
)

// event is a row of the events table the migrations create.
type event struct {
	ID   string    `ch:"id"`
	Name string    `ch:"name"`
	At   time.Time `ch:"at"`
}

func main() {
	ctx := context.Background()
	cfg := chx.Config{
		Addrs:    []string{"localhost:9000"},
		Database: "analytics",
		Username: "default",
	}

	if err := chx.Migrate(ctx, cfg, os.DirFS("migrations")); err != nil {
		log.Fatal(err)
	}
	cl, err := chx.Open(ctx, cfg)
	if err != nil {
		log.Fatal(err)
	}

	batch, err := cl.PrepareBatch(ctx, "INSERT INTO events")
	if err != nil {
		log.Fatal(err)
	}
	if err := batch.Append("e-1", "signup", time.Now()); err != nil {
		log.Fatal(err)
	}
	if err := batch.Send(); err != nil {
		log.Fatal(err)
	}

	var events []event
	err = cl.Select(ctx, &events, "SELECT id, name, at FROM events")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(len(events))

	if err := cl.Close(); err != nil {
		log.Fatal(err)
	}
}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Migrate

func Migrate(ctx context.Context, cfg Config, fsys fs.FS) error

Migrate applies the pending DDL migrations in fsys (goose SQL files, rooted at the directory that holds them) using goose's ClickHouse dialect over a dedicated database/sql handle. It is idempotent. The caller supplies its own migrations FS, e.g. fs.Sub(embedded, "migrations"). goose needs a database/sql connection (clickhouse.OpenDB), separate from the native conn.

Types

type Client

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

Client is a ClickHouse connection. It wraps the native driver.Conn; use Conn for direct access or the thin pass-throughs below.

func Open

func Open(ctx context.Context, cfg Config) (*Client, error)

Open dials ClickHouse and verifies connectivity with a ping. It does NOT apply migrations — call Migrate explicitly (usually once at startup) so schema changes stay an intentional operational step, not a side effect of connecting.

func (*Client) Close

func (c *Client) Close() error

Close releases the connection.

func (*Client) Conn

func (c *Client) Conn() driver.Conn

Conn returns the underlying native connection for direct use (e.g. PrepareBatch with column-level control, or Select into structs).

func (*Client) Exec

func (c *Client) Exec(ctx context.Context, query string, args ...any) error

Exec runs a statement with no result set (DDL/DML).

func (*Client) Name

func (c *Client) Name() string

Name identifies this store for lifecycle logging.

func (*Client) Ping

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

Ping verifies the connection is alive.

func (*Client) PrepareBatch

func (c *Client) PrepareBatch(ctx context.Context, query string) (driver.Batch, error)

PrepareBatch opens a client-side batch for a bulk INSERT — the primary write path (CH loves large batches).

func (*Client) Query

func (c *Client) Query(ctx context.Context, query string, args ...any) (driver.Rows, error)

Query runs a query returning rows for manual iteration.

Example

Query streams the rows of a result for manual iteration; Exec runs a statement without one.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/assanoff/skit/chx"
)

func main() {
	ctx := context.Background()
	cl, err := chx.Open(ctx, chx.Config{Addrs: []string{"localhost:9000"}, Database: "analytics"})
	if err != nil {
		log.Print(err)
		return
	}
	defer func() { _ = cl.Close() }()

	err = cl.Exec(ctx, "ALTER TABLE events DELETE WHERE at < now() - INTERVAL 1 YEAR")
	if err != nil {
		log.Print(err)
		return
	}

	rows, err := cl.Query(ctx, "SELECT name, count() FROM events GROUP BY name ORDER BY name")
	if err != nil {
		log.Print(err)
		return
	}
	defer func() { _ = rows.Close() }()
	for rows.Next() {
		var (
			name string
			n    uint64
		)
		if err := rows.Scan(&name, &n); err != nil {
			log.Print(err)
			return
		}
		fmt.Println(name, n)
	}
	if err := rows.Err(); err != nil {
		log.Print(err)
	}
}

func (*Client) Select

func (c *Client) Select(ctx context.Context, dest any, query string, args ...any) error

Select scans a full result set into dest (a pointer to a slice of structs).

type Config

type Config struct {
	// Addrs lists the native-protocol endpoints, host:port (ClickHouse
	// listens on 9000).
	Addrs []string
	// Database, Username, Password select the database and the credentials.
	Database string
	Username string
	Password string
	// DialTimeout bounds dialing a connection (default 10s).
	DialTimeout time.Duration
	// MaxOpenConns caps the pool (0 = the driver default, 10).
	MaxOpenConns int
	// Compression turns on LZ4 wire compression, worthwhile for the large
	// batches ClickHouse ingests.
	Compression bool
}

Config describes how to reach ClickHouse.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL