Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions ast/ast.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,8 @@ type SelectQuery struct {
SettingsBeforeFormat bool `json:"settings_before_format,omitempty"` // true if SETTINGS came before FORMAT (at union level)
IntoOutfile *IntoOutfileClause `json:"into_outfile,omitempty"`
Format *Identifier `json:"format,omitempty"`
// ColumnAliases holds the alias list of a FROM-first query: FROM t (a, b) SELECT a.
ColumnAliases []string `json:"column_aliases,omitempty"`
}

// ArrayJoinClause represents an ARRAY JOIN clause.
Expand Down
5 changes: 5 additions & 0 deletions internal/explain/select.go
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,8 @@ func explainSelectQuery(sb *strings.Builder, n *ast.SelectQuery, indent string,
if n.From != nil || n.ArrayJoin != nil {
TablesWithArrayJoin(sb, n.From, n.ArrayJoin, depth+1)
}
// Column aliases of a FROM-first query (FROM t (a, b) SELECT ...)
explainIdentifierList(sb, n.ColumnAliases, indent+" ")
// CTE column aliases (WITH t (a, b) AS ...)
explainIdentifierList(sb, cteAliases(n), indent+" ")
// PREWHERE
Expand Down Expand Up @@ -801,6 +803,9 @@ func countSelectQueryChildren(n *ast.SelectQuery) int {
if n.From != nil || n.ArrayJoin != nil {
count++
}
if len(n.ColumnAliases) > 0 {
count++
}
if len(cteAliases(n)) > 0 {
count++
}
Expand Down
5 changes: 5 additions & 0 deletions lexer/lexer.go
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,11 @@ func (l *Lexer) NextToken() Item {
l.readChar()
return Item{Token: token.CONCAT, Value: "||", Pos: pos}
}
if l.peekChar() == '>' {
l.readChar()
l.readChar()
return Item{Token: token.PIPE, Value: "|>", Pos: pos}
}
l.readChar()
return Item{Token: token.ILLEGAL, Value: "|", Pos: pos}
case ':':
Expand Down
114 changes: 109 additions & 5 deletions parser/expression.go
Original file line number Diff line number Diff line change
Expand Up @@ -796,7 +796,7 @@ func (p *Parser) parseFunctionCall(name string, pos token.Position) *ast.Functio

// Handle view() and similar functions that take a subquery as argument
// view(SELECT ...) should parse SELECT as a subquery
if strings.ToLower(name) == "view" && (p.currentIs(token.SELECT) || p.currentIs(token.WITH)) {
if strings.ToLower(name) == "view" && (p.isQueryStart()) {
subquery := p.parseSelectWithUnion()
fn.Arguments = []ast.Expression{&ast.Subquery{Position: pos, Query: subquery}}
} else if !p.currentIs(token.RPAREN) && !(p.currentIs(token.SETTINGS) && !p.peekIs(token.LBRACKET)) {
Expand Down Expand Up @@ -1248,7 +1248,7 @@ func (p *Parser) parseGroupedOrTuple() ast.Expression {
}

// Check for subquery (SELECT, WITH, or EXPLAIN)
if p.currentIs(token.SELECT) || p.currentIs(token.WITH) {
if p.isQueryStart() {
subquery := p.parseSelectWithUnion()
p.expect(token.RPAREN)
return &ast.Subquery{
Expand Down Expand Up @@ -1741,6 +1741,13 @@ func (p *Parser) parseInterval() ast.Expression {
}
p.nextToken() // skip INTERVAL

// INTERVAL '<compound>' <from_kind> TO <to_kind>
if p.currentIs(token.STRING) && p.peekIs(token.IDENT) && p.peekPeekIs(token.TO) {
if e := p.parseCompoundInterval(expr.Position); e != nil {
return e
}
}

// Choose precedence based on the first token of the interval value:
// - String literals like '1 day' have embedded units, so use ADD_PREC to stop before
// arithmetic operators. This handles `interval '1 day' - interval '1 hour'` correctly.
Expand Down Expand Up @@ -2067,7 +2074,7 @@ func (p *Parser) parseBinaryExpression(left ast.Expression) ast.Expression {
if p.currentIs(token.LPAREN) {
p.nextToken()
// Parse the subquery
if p.currentIs(token.SELECT) || p.currentIs(token.WITH) {
if p.isQueryStart() {
subquery := p.parseSelectWithUnion()
p.expect(token.RPAREN)
// Create function name that encodes both modifier and operator
Expand Down Expand Up @@ -2193,7 +2200,7 @@ func (p *Parser) parseInExpression(left ast.Expression, not bool) ast.Expression
if p.currentIs(token.LPAREN) {
p.nextToken() // skip (
// Check for subquery
if p.currentIs(token.SELECT) || p.currentIs(token.WITH) {
if p.isQueryStart() {
expr.Query = p.parseSelectWithUnion()
} else {
// Parse IN list manually to detect trailing comma
Expand Down Expand Up @@ -2872,7 +2879,7 @@ func (p *Parser) parseKeywordAsFunction() ast.Expression {
}

// Handle view() and similar functions that take a subquery as argument
if name == "view" && (p.currentIs(token.SELECT) || p.currentIs(token.WITH)) {
if name == "view" && (p.isQueryStart()) {
subquery := p.parseSelectWithUnion()
fn.Arguments = []ast.Expression{&ast.Subquery{Position: pos, Query: subquery}}
} else if !p.currentIs(token.RPAREN) {
Expand Down Expand Up @@ -3328,3 +3335,100 @@ func jsonPathPart(prefix, name string) string {
}
return prefix + name
}

// compoundIntervalFields lists the fields of the SQL-standard compound
// interval groups with the separator that precedes each one.
var compoundIntervalFields = [][]struct {
unit string
sep byte
}{
{{"Year", 0}, {"Month", '-'}},
{{"Day", 0}, {"Hour", ' '}, {"Minute", ':'}, {"Second", ':'}},
}

// parseCompoundInterval parses INTERVAL '<compound>' <from> TO <to> with the
// current token at the string. ClickHouse turns it into a tuple of
// toInterval<Unit>(n) calls, each wrapped in negate() for a leading '-'.
// It returns nil, consuming nothing, when the first unit is not an interval unit.
func (p *Parser) parseCompoundInterval(pos token.Position) ast.Expression {
from, ok := extractunit.Canonical(p.peek.Value)
if !ok {
return nil
}
literal := p.current.Value
p.nextToken() // skip string
p.nextToken() // skip from unit
p.nextToken() // skip TO
to, _ := extractunit.Canonical(p.current.Value)
p.nextToken() // skip to unit
fallback := &ast.IntervalExpr{
Position: pos,
Value: &ast.Literal{Position: pos, Type: ast.LiteralString, Value: literal},
Unit: from,
}
if to == "" {
return fallback
}
title := func(u string) string { return u[:1] + strings.ToLower(u[1:]) }
from, to = title(from), title(to)

var fields []struct {
unit string
sep byte
}
for _, group := range compoundIntervalFields {
fi, ti := -1, -1
for i, f := range group {
if f.unit == from {
fi = i
}
if f.unit == to {
ti = i
}
}
if fi >= 0 && ti > fi {
fields = group[fi : ti+1]
break
}
}
if fields == nil {
return fallback
}

i := 0
negative := false
var args []ast.Expression
for n, f := range fields {
if n > 0 {
if i >= len(literal) || literal[i] != f.sep {
return fallback
}
i++
} else if i < len(literal) && (literal[i] == '+' || literal[i] == '-') {
negative = literal[i] == '-'
i++
}
start := i
for i < len(literal) && literal[i] >= '0' && literal[i] <= '9' {
i++
}
v, err := strconv.ParseUint(literal[start:i], 10, 64)
if err != nil {
return fallback
}
var e ast.Expression = &ast.FunctionCall{
Position: pos,
Name: "toInterval" + f.unit,
Arguments: []ast.Expression{&ast.Literal{Position: pos, Type: ast.LiteralInteger, Value: v}},
}
if negative {
e = &ast.FunctionCall{Position: pos, Name: "negate", Arguments: []ast.Expression{e}}
}
args = append(args, e)
}
if i != len(literal) {
return fallback
}

return &ast.FunctionCall{Position: pos, Name: "tuple", Arguments: args}
}
Loading
Loading