chsql

package
v0.46.0 Latest Latest
Warning

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

Go to latest
Published: Jul 3, 2026 License: Apache-2.0 Imports: 11 Imported by: 0

Documentation

Overview

Package chsql provides fluent Clickhouse SQL query builder.

Index

Constants

View Source
const (
	IntervalYear = IntervalPrecision(iota + 1)
	IntervalQuarter
	IntervalMonth
	IntervalWeek
	IntervalDay
	IntervalHour
	IntervalMinute
	IntervalSecond
	IntervalMillisecond
	IntervalMicrosecond
	IntervalNanosecond
)

Variables

This section is empty.

Functions

func CollectTokens

func CollectTokens[S ~string | ~[]byte](s S, cb func(s S) bool)

CollectTokens iterates over tokens in given string.

func PutPrinter

func PutPrinter(*Printer)

PutPrinter returns Printer to pool.

Types

type Expr

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

Expr is a Clickhouse expression.

func Add

func Add(left, right Expr) Expr

Add returns new `+` operation.

func And

func And(left, right Expr) Expr

And returns new `AND` operation.

func AnyLast

func AnyLast(expr Expr) Expr

AnyLast returns `anyLast(<expr>)` function call expression.

func ArgMax

func ArgMax(arg, val Expr) Expr

ArgMax returns `argMax(<arg>, <val>)` function call expression.

func ArgMin

func ArgMin(arg, val Expr) Expr

ArgMin returns `argMin(<arg>, <val>)` function call expression.

func Array

func Array(args ...Expr) Expr

Array returns `array(<args>...)` function call expression.

func ArrayConcat

func ArrayConcat(args ...Expr) Expr

ArrayConcat returns `arrayConcat(<args>...)` function call expression.

func ArrayElement

func ArrayElement(arr, index Expr) Expr

ArrayElement returns `arrayElement(<arr>, <index>)` function call expression.

func ArrayFilter

func ArrayFilter(lambda, arr Expr) Expr

ArrayFilter returns `arrayFilter(<lambda>, <arr>)` function call expression.

func ArrayJoin

func ArrayJoin(args ...Expr) Expr

ArrayJoin returns `arrayJoin(<args>...)` function call expression.

func ArrayMap

func ArrayMap(lambda, arr Expr) Expr

ArrayMap returns `arrayMap(<lambda>, <arr>)` function call expression.

func ArrayPopBack

func ArrayPopBack(arr Expr) Expr

ArrayPopBack returns `arrayPopBack(<arr>)` function call expression.

func ArrayPopFront

func ArrayPopFront(arr Expr) Expr

ArrayPopFront returns `arrayPopFront(<arr>)` function call expression.

func ArraySort

func ArraySort(lambda, arr Expr) Expr

ArraySort returns `arraySort(<lambda>, <arr>)` function call expression.

func ArraySum

func ArraySum(lambda Expr, args ...Expr) Expr

ArraySum returns `arraySum(<lambda>, <args>...)` function call expression.

func Avg

func Avg(expr Expr) Expr

Avg returns `avg(<expr>)` function call expression.

func Bool

func Bool(v bool) Expr

Bool returns bool literal.

func Cast

func Cast(x Expr, typ string) Expr

Cast returns `CAST(<x>, <typ>)` function call expression.

func Coalesce

func Coalesce(args ...Expr) Expr

Coalesce returns `coalesce(<args>...)` function call expression.

func ColumnEq

func ColumnEq[V litValue](column string, right V) Expr

ColumnEq returns new `=` operation on column and literal.

func ColumnToInt64

func ColumnToInt64(column string) Expr

ColumnToInt64 returns `toInt64(Ident(<column>))` function call expression.

func ColumnTupleElement

func ColumnTupleElement(column string, index int) Expr

ColumnTupleElement returns `tupleElement(Ident(<column>), <index>)` function call expression.

func Contains

func Contains(column, needle string) Expr

Contains returns boolean expression to filter strings containing needle.

func Count

func Count() Expr

Count returns `count()` function call expression.

func DateTime

func DateTime(t time.Time) Expr

DateTime returns an expression representing time.Time as DateTime.

func DateTime64

func DateTime64(t time.Time, prec proto.Precision) Expr

DateTime64 returns an expression representing time.Time with given precision as DateTime64.

func Div

func Div(left, right Expr) Expr

Div returns new `/` operation.

func Eq

func Eq(left, right Expr) Expr

Eq returns new `=` operation.

func FirstValue

func FirstValue(arg Expr) Expr

FirstValue returns `first_value(<arg>)` function call expression.

func Float

func Float[I litFloat](v I) Expr

Float returns float literal.

func Function

func Function(name string, args ...Expr) Expr

Function reutrns function call expression.

func Greatest

func Greatest(args ...Expr) Expr

Greatest returns `greatest(<args>...)` function call expression.

func GroupArray

func GroupArray(arg Expr) Expr

GroupArray returns `groupArray(<arg>)` function call expression.

func Gt

func Gt(left, right Expr) Expr

Gt returns new `>` operation.

func Gte

func Gte(left, right Expr) Expr

Gte returns new `>=` operation.

func Has

func Has(arr, elem Expr) Expr

Has returns `has(<arr>, <elem>)` function call expression.

func HasToken

func HasToken(haystack Expr, token string) Expr

HasToken returns `hasToken(<haystack>, <token>)` function call expression.

func Hex

func Hex(arg Expr) Expr

Hex returns `hex(<arg>)` function call expression.

func Hop

func Hop(arg Expr, hopInterval, windowInterval IntervalLit) Expr

Hop returns `hop(<time_attr>, <hop_interval>, <window_interval>)` function call expression.

func HopEnd

func HopEnd(arg Expr, hopInterval, windowInterval IntervalLit) Expr

HopEnd returns `hopEnd(<time_attr>, <hop_interval>, <window_interval>)` function call expression.

func HopStart

func HopStart(arg Expr, hopInterval, windowInterval IntervalLit) Expr

HopStart returns `hopStart(<time_attr>, <hop_interval>, <window_interval>)` function call expression.

func Ident

func Ident(tok string) Expr

Ident returns identifier.

func If

func If(cond, then, elseExpr Expr) Expr

If returns `if(<cond>, <then>, <else>)` function call expression.

func In

func In(left, right Expr) Expr

In returns new `IN` operation.

func InTimeRange

func InTimeRange(column string, start, end time.Time, prec proto.Precision) Expr

InTimeRange returns boolean expression to filter by [start:end].

func IntDiv

func IntDiv(a, b Expr) Expr

IntDiv returns `intDiv(<a>, <b>)` function call expression.

func Integer

func Integer[I litInt](v I) Expr

Integer returns integer literal.

func Interval

func Interval(d time.Duration) Expr

Interval converts duration d to ClickHouse Interval expression.

func JSONExtract

func JSONExtract(from Expr, typ string) Expr

JSONExtract returns `JSONExtract(<from>, <typ>)` function call expression.

func JSONExtractField

func JSONExtractField(from Expr, field, typ string) Expr

JSONExtractField returns `JSONExtract(<from>, <field>, <typ>)` function call expression.

func JSONExtractKeys

func JSONExtractKeys(from Expr) Expr

JSONExtractKeys returns `JSONExtractKeys(<from>)` function call expression.

func JSONExtractString

func JSONExtractString(from Expr, field string) Expr

JSONExtractString returns `JSONExtractString(<from>, <field>)` function call expression.

func JoinAnd

func JoinAnd(args ...Expr) Expr

JoinAnd joins given expressions using AND op.

  • If len(args) == 0, returns `true` literal.
  • If len(args) == 1, returns first argument.
  • Otherwise, joins arguments with AND.

func JoinOr

func JoinOr(args ...Expr) Expr

JoinOr joins given expressions using OR op.

  • If len(args) == 0, returns `true` literal.
  • If len(args) == 1, returns first argument.
  • Otherwise, joins arguments with OR.

func LagInFrame

func LagInFrame(arg, offset, defaultVal Expr) Expr

LagInFrame returns `lagInFrame(<arg>, <offset>, <default>)`.

func Lambda

func Lambda(args []string, body Expr) Expr

Lambda returns lambda expression.

func LastValue

func LastValue(arg Expr) Expr

LastValue returns `last_value(<arg>)` function call expression.

func Least

func Least(args ...Expr) Expr

Least returns `least(<args>...)` function call expression.

func Length

func Length(arg Expr) Expr

Length returns `length(<arg>)` function call expression.

func Like

func Like(haystack, pattern Expr) Expr

Like returns `like(<haystack>, <pattern>)` function call expression.

func Lt

func Lt(left, right Expr) Expr

Lt returns new `<` operation.

func Lte

func Lte(left, right Expr) Expr

Lte returns new `<=` operation.

func Map

func Map(args ...Expr) Expr

Map returns `map(<args>...)` function call expression.

func MapConcat

func MapConcat(args ...Expr) Expr

MapConcat returns `mapConcat(<args>...)` function call expression.

func Match

func Match(haystack, pattern Expr) Expr

Match returns `match(<haystack>, <pattern>)` function call expression.

func Max

func Max(expr Expr) Expr

Max returns `max(<expr>)` function call expression.

func Min

func Min(expr Expr) Expr

Min returns `min(<expr>)` function call expression.

func Minus

func Minus(left, right Expr) Expr

Minus returns new `-` operation.

func Mod

func Mod(left, right Expr) Expr

Mod returns new `%` operation.

func Mul

func Mul(left, right Expr) Expr

Mul returns new `*` operation.

func Not

func Not(sub Expr) Expr

Not returns new `NOT` operation.

func NotEq

func NotEq(left, right Expr) Expr

NotEq returns new `!=` operation.

func Or

func Or(left, right Expr) Expr

Or returns new `OR` operation.

func Over

func Over(fn Expr, partitionBy []Expr, orderBy []WindowOrderSpec) Expr

Over builds `<fn> OVER (PARTITION BY <partitionBy...> ORDER BY <orderBy...>)`.

func Position

func Position(haystack, needle Expr) Expr

Position returns `position(<haystack>, <needle>)` function call expression.

func PositionUTF8

func PositionUTF8(haystack, needle Expr) Expr

PositionUTF8 returns `positionUTF8(<haystack>, <needle>)` function call expression.

func PrefixedIdent

func PrefixedIdent(prefix, tok string) Expr

PrefixedIdent return identifier with prefix.

func Range

func Range(n Expr) Expr

Range returns `range(<n>)` function call expression.

func ReinterpretAsUInt64

func ReinterpretAsUInt64(arg Expr) Expr

ReinterpretAsUInt64 returns `reinterpretAsUInt64(<arg>)` function call expression.

func SimpleJSONHas

func SimpleJSONHas(json Expr, field string) Expr

SimpleJSONHas returns `simpleJSONHas(<json>, <field>)` function call expression.

func String

func String(v string) Expr

String returns string literal.

func Sub

func Sub(left, right Expr) Expr

Sub returns new `-` operation.

func SubQuery

func SubQuery(q Query) Expr

SubQuery returns sub-query as an expression.

func Sum

func Sum(expr Expr) Expr

Sum returns `sum(<expr>)` function call expression.

func SumIf

func SumIf(arg, cond Expr) Expr

SumIf returns `sumIf(<arg>, <cond>)` function call expression.

func ToDateTime

func ToDateTime(arg Expr) Expr

ToDateTime returns `toDateTime(<arg>)` function call expression.

func ToDateTime64

func ToDateTime64(arg Expr, prec proto.Precision) Expr

ToDateTime64 returns `toDateTime64(<arg>, <prec>)` function call expression.

func ToFloat64

func ToFloat64(arg Expr) Expr

ToFloat64 returns `toFloat64(<arg>)` function call expression.

func ToInt64

func ToInt64(arg Expr) Expr

ToInt64 returns `toInt64(<arg>)` function call expression.

func ToInt64Val

func ToInt64Val[I litInt](v I) Expr

ToInt64Val returns `toInt64(<v>)` function call expression.

func ToLowCardinality

func ToLowCardinality(arg Expr) Expr

ToLowCardinality returns `ToLowCardinality(<arg>)` function call expression.

func ToStartOfHour

func ToStartOfHour(arg Expr) Expr

ToStartOfDay returns `toStartOfHour(<arg>)` function call expression.

func ToString

func ToString(arg Expr) Expr

ToString returns `toString(<arg>)` function call expression.

func ToUInt64

func ToUInt64(arg Expr) Expr

ToUInt64 returns `toUInt64(<arg>)` function call expression.

func ToUnixTimestamp64Milli

func ToUnixTimestamp64Milli(arg Expr) Expr

ToUnixTimestamp64Milli returns `toUnixTimestamp64Milli(<arg>)` function call expression.

func ToUnixTimestamp64Nano

func ToUnixTimestamp64Nano(arg Expr) Expr

ToUnixTimestamp64Nano returns `toUnixTimestamp64Nano(<arg>)` function call expression.

func Tumble

func Tumble(arg Expr, hopInterval time.Duration) Expr

Tumble returns `tumble(<time_attr>, <hop_interval>)` function call expression.

func TumbleEnd

func TumbleEnd(arg Expr, hopInterval time.Duration) Expr

TumbleEnd returns `tumbleEnd(<time_attr>, <hop_interval>)` function call expression.

func TumbleStart

func TumbleStart(arg Expr, hopInterval time.Duration) Expr

TumbleStart returns `tumbleStart(<time_attr>, <hop_interval>)` function call expression.

func Tuple

func Tuple(args ...Expr) Expr

Tuple returns tuple of given expressions.

func TupleElement

func TupleElement(tup Expr, index int) Expr

TupleElement returns `tupleElement(<tup>, <index>)` function call expression.

func TupleValues

func TupleValues[V litValue](vals ...V) Expr

TupleValues returns tuple of given values.

func Unhex

func Unhex(arg Expr) Expr

Unhex returns `unhex(<arg>)` function call expression.

func UnixNano

func UnixNano(t time.Time) Expr

UnixNano returns time.Time as unix nano timestamp.

func Value

func Value[V litValue](v V) Expr

Value returns literal.

func (Expr) IsZero

func (e Expr) IsZero() bool

type IntervalLit

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

IntervalLit defines an interval.

func MakeIntervalLit

func MakeIntervalLit[I int | int8 | int16 | int32 | int64](val I, prec IntervalPrecision) IntervalLit

MakeIntervalLit returns an IntervalLit with given precision.

func MakeIntervalLitFromDuration

func MakeIntervalLitFromDuration(d time.Duration) IntervalLit

MakeIntervalLitFromDuration creates an IntervalLit from given duration.

func (IntervalLit) Expr

func (l IntervalLit) Expr() Expr

Expr returns SQL literal for this duration.

type IntervalPrecision

type IntervalPrecision uint8

IntervalPrecision sets interval precision.

func GetIntervalPrecision

func GetIntervalPrecision(d time.Duration) IntervalPrecision

GetIntervalPrecision returns coarest IntervalPrecision to represent given duration.

func (IntervalPrecision) Duration

func (p IntervalPrecision) Duration(d time.Duration) int64

Duration returns duration truncated to precision p.

func (IntervalPrecision) Expr

func (p IntervalPrecision) Expr(val int64) Expr

Expr returns SQL literal for given duration.

type OnResult

type OnResult = func(ctx context.Context, block proto.Block) error

OnResult defines ch.Query.OnResult callback type.

type Order

type Order uint8

Order defines sorting order.

const (
	Desc Order = iota + 1
	Asc
)

func (Order) String

func (o Order) String() string

String implements fmt.Stringer.

type Printer

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

Printer prints SQL query.

func GetPrinter

func GetPrinter() *Printer

GetPrinter creates a new Printer.

func (*Printer) And

func (p *Printer) And()

And writes `AND` ident.

func (*Printer) Asc

func (p *Printer) Asc()

Asc writes `ASC` ident.

func (*Printer) By

func (p *Printer) By()

By writes `BY` ident.

func (*Printer) CloseParen

func (p *Printer) CloseParen()

CloseParen writes a paren.

func (*Printer) Comma

func (p *Printer) Comma()

Comma writes a comma.

func (*Printer) Cross

func (p *Printer) Cross()

Cross writes `CROSS` ident.

func (*Printer) Desc

func (p *Printer) Desc()

Desc writes `DESC` ident.

func (*Printer) Distinct

func (p *Printer) Distinct()

Distinct writes `DISTINCT` ident.

func (*Printer) Dot

func (p *Printer) Dot()

Dot writes a dot.

func (*Printer) Final

func (p *Printer) Final()

Final writes `FINAL` ident.

func (*Printer) From

func (p *Printer) From()

From writes `FROM` ident.

func (*Printer) Full

func (p *Printer) Full()

Full writes `FULL` ident.

func (*Printer) Group

func (p *Printer) Group()

Group writes `GROUP` ident.

func (*Printer) Having

func (p *Printer) Having()

Having writes `HAVING` ident.

func (*Printer) Ident

func (p *Printer) Ident(tok string)

Ident writes an identifier.

func (*Printer) Inner

func (p *Printer) Inner()

Inner writes `INNER` ident.

func (*Printer) Join

func (p *Printer) Join()

Join writes `JOIN` ident.

func (*Printer) Left

func (p *Printer) Left()

Left writes `LEFT` ident.

func (*Printer) Limit

func (p *Printer) Limit()

Limit writes `LIMIT` ident.

func (*Printer) Literal

func (p *Printer) Literal(lit string)

Literal writes an literal.

func (*Printer) On

func (p *Printer) On()

On writes `ON` ident.

func (*Printer) OpenParen

func (p *Printer) OpenParen()

OpenParen writes a paren.

func (*Printer) Order

func (p *Printer) Order()

Order writes `ORDER` ident.

func (*Printer) Outer

func (p *Printer) Outer()

Outer writes `OUTER` ident.

func (*Printer) Prewhere

func (p *Printer) Prewhere()

Prewhere writes `PREWHERE` ident.

func (*Printer) Right

func (p *Printer) Right()

Right writes `RIGHT` ident.

func (*Printer) Select

func (p *Printer) Select()

Select writes `SELECT` ident.

func (*Printer) String

func (p *Printer) String() string

String returns query.

func (*Printer) Where

func (p *Printer) Where()

Where writes `WHERE` ident.

func (*Printer) With

func (p *Printer) With()

With writes `WITH` ident.

func (*Printer) WriteExpr

func (p *Printer) WriteExpr(e Expr) error

WriteExpr writes given expression.

type Query

type Query interface {
	WriteSQL(p *Printer) error
}

Query is an query interface.

type ResultColumn

type ResultColumn struct {
	Name string
	Expr Expr
	Data proto.ColResult
}

ResultColumn defines a column result.

func Column

func Column(name string, data proto.ColResult) ResultColumn

Column returns new ResultColumn.

type SelectQuery

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

SelectQuery is a SELECT query builder.

func Select

func Select(table string, columns ...ResultColumn) *SelectQuery

Select creates a new SelectQuery.

func SelectFrom

func SelectFrom(sub *SelectQuery, columns ...ResultColumn) *SelectQuery

SelectFrom creates a new SelectQuery from subquery.

func (*SelectQuery) Alias

func (q *SelectQuery) Alias(alias string) *SelectQuery

Alias sets alias for selected table.

func (*SelectQuery) Distinct

func (q *SelectQuery) Distinct(b bool) *SelectQuery

Distinct sets if query is `DISTINCT`.

func (*SelectQuery) Final

func (q *SelectQuery) Final(b bool) *SelectQuery

Final sets if query is `FINAL`.

func (*SelectQuery) GroupBy

func (q *SelectQuery) GroupBy(groups ...Expr) *SelectQuery

GroupBy adds grouping to query.

func (*SelectQuery) Having

func (q *SelectQuery) Having(filters ...Expr) *SelectQuery

Having adds grouped filters to query.

func (*SelectQuery) InnerJoin

func (q *SelectQuery) InnerJoin(table, alias string, on Expr) *SelectQuery

InnerJoin adds an INNER JOIN to query.

func (*SelectQuery) Limit

func (q *SelectQuery) Limit(n int) *SelectQuery

Limit sets query limit.

If n is equal to or less than zero, limit is ignored.

func (*SelectQuery) Order

func (q *SelectQuery) Order(e Expr, order Order) *SelectQuery

Order adds order to query.

func (*SelectQuery) Prepare

func (q *SelectQuery) Prepare(onResult OnResult) (ch.Query, error)

Prepare builds SQL query and passes columns to ch.Query.

func (*SelectQuery) Prewhere

func (q *SelectQuery) Prewhere(filters ...Expr) *SelectQuery

Prewhere adds filters to query.

func (*SelectQuery) Results

func (q *SelectQuery) Results() (r proto.Results)

Results returns list of result columns.

func (*SelectQuery) Where

func (q *SelectQuery) Where(filters ...Expr) *SelectQuery

Where adds filters to query.

func (*SelectQuery) With

func (q *SelectQuery) With(name string, expr Expr) *SelectQuery

With adds common table expressions to a query.

func (*SelectQuery) WriteSQL

func (q *SelectQuery) WriteSQL(p *Printer) error

WriteSQL writes SQL query.

type WindowOrderSpec

type WindowOrderSpec struct {
	Expr  Expr
	Order Order
}

WindowOrderSpec is an expression with its sort direction, used in the ORDER BY clause of an OVER window specification.

func WindowAsc

func WindowAsc(e Expr) WindowOrderSpec

WindowAsc returns a WindowOrderSpec with ascending order.

func WindowDesc

func WindowDesc(e Expr) WindowOrderSpec

WindowDesc returns a WindowOrderSpec with descending order.

type WithColumn

type WithColumn struct {
	Name string
	Expr Expr
}

WithColumn defines a Common table expression.

Jump to

Keyboard shortcuts

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