ClickHouse Defining Models

Mapping tables to structs

For each table you need to define a corresponding Go struct (model). go-clickhouse maps the exported struct fields to the table columns and ignores the unexported fields.

type Span struct {
	ch.CHModel `ch:"table:spans,partition:toYYYYMM(time)"`

	ID	 uint64
	Text string	   `ch:",lc"` // low cardinality column
	Time time.Time `ch:",pk"` // ClickHouse primary key for order by

	email string // unexported fields are ignored
}

Struct tags

Ch uses sensible defaults to generate names and deduct types, but you can use the following struct tags to override the defaults.

TagComment
ch.CHModel `ch:"table:table_name"`Override default table name.
ch.CHModel `ch:"alias:table_alias"`Override default table alias.
ch.CHModel `ch:"insert:table_name_buffer"`Override table name for INSERT queries.
ch:"-"Ignore the field.
ch:"column_name"Override default column name.
ch:"alt:alt_name"Alternative column name. Useful during migrations.
ch:",pk"Mark column as a ClickHouse primary key (order by).
ch:"type:uuid"Override default SQL type.
ch:"default:gen_random_uuid()"Tell CreateTable to set DEFAULT expression.
ch:",notnull"Tell CreateTable to add NOT NULL constraint.
ch:",scanonly"Only use this field to scan query results, not for inserts.
ch:",array"Use PostgreSQL array.
ch:",json_use_number"Use json.Decoder.UseNumber to decode JSON.

Table names

Ch generates table names and aliases from struct names by underscoring them. It also pluralizes table names, for example, struct ArticleCategory gets table name article_categories and alias article_category.

To override the generated name and the alias:

type Span struct {
	ch.CHModel `ch:"table:spans,alias:s"`
}

To specify a different table name for INSERT queries:

type Span struct {
	ch.CHModel `ch:"table:spans,insert:spans_buffer,alias:s"`
}

Column names

Ch generates column names from struct field names by underscoring them. For example, struct field UserID gets column name user_id.

To override the generated column name:

type Span struct {
	Name string `ch:"myname"`
}

Column types

go-clickhouse generates column types from the struct field types. For example, Go type string is translated to ClickHouse type String.

To override the generated column type:

type Span struct {
    ID int64 `ch:"type:UInt64"`
}

Low cardinality

To use LowCardinality(String) ClickHouse type, add the lc tag option or specify the type on the field, for example:

type Span struct {
	Name string `ch:",lc"`
}

// or

type Span struct {
	Name string `ch:"type:LowCardinality(String)"`
}

Nullable

To use Nullable(T) ClickHouse data type, define a model with a pointer to the corresponding Go type, for example, Nullable(String) and *string:

type Span struct {
    Name *string
}
Last Updated: