• Stars
    star
    418
  • Rank 103,620 (Top 3 %)
  • Language
    Go
  • License
    MIT License
  • Created over 7 years ago
  • Updated 6 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Golang SQL database driver for Yandex ClickHouse

ClickHouse Build Status Go Report Card Coverage Status

Yet another Golang SQL database driver for Yandex ClickHouse

Key features

DSN

schema://user:password@host[:port]/database?param1=value1&...&paramN=valueN

parameters

  • timeout - is the maximum amount of time a dial will wait for a connect to complete
  • idle_timeout - is the maximum amount of time an idle (keep-alive) connection will remain idle before closing itself.
  • read_timeout - specifies the amount of time to wait for a server's response
  • location - timezone to parse Date and DateTime
  • debug - enables debug logging
  • kill_query - enables killing query on the server side if we have error from transport
  • kill_query_timeout - timeout to kill query (default value is 1 second)
  • other clickhouse options can be specified as well (except default_format)

example:

http://user:password@host:8123/clicks?read_timeout=10s&write_timeout=20s

Supported data types

Notes:

  • database/sql does not allow to use big uint64 values. It is recommended use type UInt64 which is provided by driver for such kind of values.
  • type []byte are used as raw string (without quoting)
  • for passing value of type []uint8 to driver as array - please use the wrapper clickhouse.Array
  • for passing decimal value please use the wrappers clickhouse.Decimal*
  • for passing IPv4/IPv6 types use clickhouse.IP
  • for passing Tuple types use clickhouse.Tuple or structs
  • for passing Map types use clickhouse.Map

Supported request params

Clickhouse supports setting query_id and quota_key for each query. The database driver provides ability to set these parameters as well.

There are constants QueryID and QuotaKey for correct setting these params.

quota_key could be set as empty string, but query_id - does not. Keep in mind, that setting same query_id could produce exception or replace already running query depending on current Clickhouse settings. See replace_running_query for details.

See Example section for use cases.

Install

go get -u github.com/mailru/go-clickhouse/v2

Example

package main

import (
	"context"
	"database/sql"
	"log"
	"time"

	"github.com/mailru/go-clickhouse/v2"
)

func main() {
	connect, err := sql.Open("chhttp", "http://127.0.0.1:8123/default")
	if err != nil {
		log.Fatal(err)
	}
	if err := connect.Ping(); err != nil {
		log.Fatal(err)
	}

	_, err = connect.Exec(`
		CREATE TABLE IF NOT EXISTS example (
			country_code FixedString(2),
			os_id        UInt8,
			browser_id   UInt8,
			categories   Array(Int16),
			action_day   Date,
			action_time  DateTime
		) engine=Memory
	`)

	if err != nil {
		log.Fatal(err)
	}

	tx, err := connect.Begin()
	if err != nil {
		log.Fatal(err)
	}
	stmt, err := tx.Prepare(`
		INSERT INTO example (
			country_code,
			os_id,
			browser_id,
			categories,
			action_day,
			action_time
		) VALUES (
			?, ?, ?, ?, ?, ?
		)`)

	if err != nil {
		log.Fatal(err)
	}

	for i := 0; i < 100; i++ {
		if _, err := stmt.Exec(
			"RU",
			10+i,
			100+i,
			clickhouse.Array([]int16{1, 2, 3}),
			clickhouse.Date(time.Now()),
			time.Now(),
		); err != nil {
			log.Fatal(err)
		}
	}

	if err := tx.Commit(); err != nil {
		log.Fatal(err)
	}

	rows, err := connect.Query(`
		SELECT
			country_code,
			os_id,
			browser_id,
			categories,
			action_day,
			action_time
		FROM
			example`)

	if err != nil {
		log.Fatal(err)
	}

	for rows.Next() {
		var (
			country               string
			os, browser           uint8
			categories            []int16
			actionDay, actionTime time.Time
		)
		if err := rows.Scan(
			&country,
			&os,
			&browser,
			&categories,
			&actionDay,
			&actionTime,
		); err != nil {
			log.Fatal(err)
		}
		log.Printf("country: %s, os: %d, browser: %d, categories: %v, action_day: %s, action_time: %s",
			country, os, browser, categories, actionDay, actionTime,
		)
	}

	ctx := context.Background()
	rows, err = connect.QueryContext(context.WithValue(ctx, clickhouse.QueryID, "dummy-query-id"), `
		SELECT
			country_code,
			os_id,
			browser_id,
			categories,
			action_day,
			action_time
		FROM
			example`)

	if err != nil {
		log.Fatal(err)
	}

	for rows.Next() {
		var (
			country               string
			os, browser           uint8
			categories            []int16
			actionDay, actionTime time.Time
		)
		if err := rows.Scan(
			&country,
			&os,
			&browser,
			&categories,
			&actionDay,
			&actionTime,
		); err != nil {
			log.Fatal(err)
		}
		log.Printf("country: %s, os: %d, browser: %d, categories: %v, action_day: %s, action_time: %s",
			country, os, browser, categories, actionDay, actionTime,
		)
	}
}

Use dbr

package main

import (
	"log"
	"time"

	_ "github.com/mailru/go-clickhouse/v2"
	"github.com/mailru/dbr"
)

func main() {
	connect, err := dbr.Open("chhttp", "http://127.0.0.1:8123/default", nil)
	if err != nil {
		log.Fatal(err)
	}
	var items []struct {
		CountryCode string    `db:"country_code"`
		OsID        uint8     `db:"os_id"`
		BrowserID   uint8     `db:"browser_id"`
		Categories  []int16   `db:"categories"`
		ActionTime  time.Time `db:"action_time"`
	}
	sess := connect.NewSession(nil)
	query := sess.Select("country_code", "os_id", "browser_id", "categories", "action_time").From("example")
	query.Where(dbr.Eq("country_code", "RU"))
	if _, err := query.Load(&items); err != nil {
		log.Fatal(err)
	}

	for _, item := range items {
		log.Printf("country: %s, os: %d, browser: %d, categories: %v, action_time: %s",
			item.CountryCode, item.OsID, item.BrowserID, item.Categories, item.ActionTime,
		)
	}
}

Go versions

Officially support last 4 golang releases

Additional clickhouse libraries

Development

You can check the effect of changes on CI or run tests locally:

make init # dep ensure and install
make test

Remember that make init will add a few binaries used for testing

More Repositories

1

easyjson

Fast JSON serializer for golang.
Go
4,406
star
2

FileAPI

FileAPI — a set of javascript tools for working with files. Multiupload, drag'n'drop and chunked file upload. Images: crop, resize and auto orientation by EXIF.
JavaScript
3,579
star
3

easygo

Tools for building go apps.
Go
671
star
4

icqdesktop.deprecated

C++
461
star
5

dbr

Additions to Go's database/sql for super fast performance and convenience. (fork of gocraft/dbr)
Go
174
star
6

graphite-nginx-module

An nginx module for collecting stats into Graphite
C
135
star
7

fest

javascript templates
JavaScript
128
star
8

jira-scripts

Groovy
113
star
9

tntlua

Tarantool 1.5 Lua stored procedures
Lua
83
star
10

tarantool-authman

Lua
53
star
11

surgemq

Go
19
star
12

jira-plugins-jsincluder

JavaScript
16
star
13

shadowplay

Rust
15
star
14

designsystemsclub

Каталог отечественных компонентных дизайн-систем, реализованных на технологическом уровне. Живые гайдлайны, статьи, презентации, выступления и другие материалы о них.
CSS
15
star
15

jira-plugins-mrimsender

Mail.Ru Agent Notifications JIRA Plugin
Java
13
star
16

sumbur-ruby

sumbur-ruby
Java
12
star
17

ipro-cli

iproto cli tools
C
12
star
18

March

Kotlin
11
star
19

activerecord

Go
10
star
20

confetti

confetti - configuration file parser generator
C
10
star
21

mail-auth-sdk-android

Java
9
star
22

opensource.mail.ru

opensource.mail.ru wiki content
HTML
9
star
23

nocaptcha-php

PHP
8
star
24

imaginelua

Lua
6
star
25

slick-migration

Slick-migration - is a Scala library that helps to maintain compilable migration scripts
Scala
5
star
26

top-mail-ru

PHP
5
star
27

hit-doc

PHP
5
star
28

libzxcvbn

Simple implementation of zxcvbn in C
C
4
star
29

queue-processor

PHP queues processing tool
PHP
4
star
30

inetnums

Python
4
star
31

jira-plugins-commons

Dependency module
Java
4
star
32

nocaptcha-bitrix

CMS Bitrix module for working with Nocaptcha Mail.Ru service
PHP
4
star
33

iproto-ruby

Ruby implementation of Mail.Ru iproto protocol
Ruby
3
star
34

confluence-plugins-utils

Java
3
star
35

mrasender

Tarantool module for sending messages to Mail.Ru Agent
C
3
star
36

nocaptcha-perl

Perl module for working with Nocaptcha Mail.Ru service
Perl
3
star
37

bamboo-plugins-utils

Utils for Bamboo
Java
2
star
38

nocaptcha-python

Python
2
star
39

mail-auth-sdk-ios

Objective-C
2
star
40

VK-Jira-Plugins

1
star
41

quotas

Lua
1
star
42

2kit

1
star
43

skill_cosmo_quest

Python
1
star
44

wdio-redirect-by-pattern-service

TypeScript
1
star
45

tslint-2kit-rules

1
star
46

nocaptcha-wordpress

WordPress module for working with Nocaptcha Mail.Ru service
PHP
1
star
47

clearnet

Kotlin
1
star
48

activerecord-cookbook

Go
1
star