diff --git a/ast/ast.go b/ast/ast.go index 0aed1641ee..9582f0c010 100644 --- a/ast/ast.go +++ b/ast/ast.go @@ -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. diff --git a/internal/explain/select.go b/internal/explain/select.go index 6143836e6e..9d067d1241 100644 --- a/internal/explain/select.go +++ b/internal/explain/select.go @@ -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 @@ -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++ } diff --git a/lexer/lexer.go b/lexer/lexer.go index 7f5e6d6fec..3bcbeb74fb 100644 --- a/lexer/lexer.go +++ b/lexer/lexer.go @@ -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 ':': diff --git a/parser/expression.go b/parser/expression.go index 3b669ca475..3616c904d0 100644 --- a/parser/expression.go +++ b/parser/expression.go @@ -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)) { @@ -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{ @@ -1741,6 +1741,13 @@ func (p *Parser) parseInterval() ast.Expression { } p.nextToken() // skip INTERVAL + // INTERVAL '' TO + 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. @@ -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 @@ -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 @@ -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) { @@ -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 '' TO with the +// current token at the string. ClickHouse turns it into a tuple of +// toInterval(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} +} diff --git a/parser/parser.go b/parser/parser.go index 991eeb234b..0a65f59a22 100644 --- a/parser/parser.go +++ b/parser/parser.go @@ -2,6 +2,7 @@ package parser import ( + "reflect" "context" "fmt" "io" @@ -392,6 +393,15 @@ func (p *Parser) parseWithStatement() ast.Statement { return ins } + // WITH ... FROM t [SELECT ...] (FROM-first query) + if p.currentIs(token.FROM) { + query := p.parseFromSelectSyntaxNoPipe(with) + if query != nil && p.currentIs(token.PIPE) { + query = p.parsePipeOperators(query) + } + return query + } + // For SELECT, we use parseSelectWithParsedWith to continue with normal parsing // but with the already-parsed WITH clause return p.parseSelectWithUnionWithParsedWith(pos, with) @@ -590,7 +600,20 @@ func (p *Parser) parseSelectWithParsedWith(with []ast.Expression) *ast.SelectQue } // parseSelectWithUnion parses SELECT ... UNION/INTERSECT/EXCEPT ... queries +// parseSelectWithUnion parses a SELECT query with UNIONs, followed by an +// optional chain of pipe operators. func (p *Parser) parseSelectWithUnion() *ast.SelectWithUnionQuery { + query := p.parseSelectWithUnionNoPipe() + if query != nil && p.currentIs(token.PIPE) { + query = p.parsePipeOperators(query) + } + return query +} + +func (p *Parser) parseSelectWithUnionNoPipe() *ast.SelectWithUnionQuery { + if p.isFromFirstQuery() { + return p.parseFromSelectSyntaxNoPipe(nil) + } query := &ast.SelectWithUnionQuery{ Position: p.current.Pos, } @@ -1439,7 +1462,7 @@ func (p *Parser) parseWithClause() []ast.Expression { if p.currentIs(token.LPAREN) { // Could be CTE: name AS (subquery) OR could be name AS (expr) p.nextToken() - if p.currentIs(token.SELECT) || p.currentIs(token.WITH) { + if p.isQueryStart() { // Standard CTE: name AS (SELECT...) subquery := p.parseSelectWithUnion() if !p.expect(token.RPAREN) { @@ -1723,7 +1746,7 @@ func (p *Parser) parseTableExpression() *ast.TableExpression { // Handle subquery if p.currentIs(token.LPAREN) { p.nextToken() - if p.currentIs(token.SELECT) || p.currentIs(token.WITH) || p.currentIs(token.LPAREN) { + if p.isQueryStart() || p.currentIs(token.LPAREN) { // SELECT, WITH, or nested (SELECT...) for UNION queries like ((SELECT 1) UNION ALL SELECT 2) subquery := p.parseSelectWithUnion() expr.Table = &ast.Subquery{Query: subquery} @@ -1790,7 +1813,8 @@ func (p *Parser) parseTableExpression() *ast.TableExpression { } // Column aliases: t(a, b, ...) - if expr.Alias != "" && p.currentIs(token.LPAREN) { + _, isSubquery := expr.Table.(*ast.Subquery) + if (expr.Alias != "" || isSubquery) && p.currentIs(token.LPAREN) { p.nextToken() for !p.currentIs(token.RPAREN) && !p.currentIs(token.EOF) { expr.ColumnAliases = append(expr.ColumnAliases, p.parseIdentifierName()) @@ -1860,6 +1884,10 @@ func (p *Parser) parseOrderByList() []*ast.OrderByElement { Position: p.current.Pos, Expression: p.parseExpression(LOWEST), } + // ORDER BY ALL is printed as the identifier all + if id, ok := elem.Expression.(*ast.Identifier); ok && len(id.Parts) == 1 && id.Alias == "" && strings.EqualFold(id.Parts[0], "all") { + id.Parts[0] = "all" + } // Handle ASC/DESC if p.currentIs(token.ASC) { @@ -2124,6 +2152,11 @@ func (p *Parser) parseInsert() *ast.InsertQuery { p.parseSettingsList() } + // INSERT INTO t FROM src ... (FROM-first query) + if p.isFromFirstQuery() { + ins.Select = p.parseSelectWithUnion() + } + // Parse FROM INFILE clause (for INSERT ... FROM INFILE '...' COMPRESSION 'gz') if p.currentIs(token.FROM) { p.nextToken() @@ -2177,7 +2210,7 @@ func (p *Parser) parseInsert() *ast.InsertQuery { break } } - } else if p.currentIs(token.SELECT) || p.currentIs(token.WITH) { + } else if p.isQueryStart() { ins.Select = p.parseSelectWithUnion() // If the SELECT has settings, mark the INSERT as having settings too if ins.Select != nil { @@ -2623,7 +2656,7 @@ func (p *Parser) parseCreateTable(create *ast.CreateQuery) { // Parse AS SELECT or AS (subquery) or AS table_function() or AS database.table if p.currentIs(token.AS) { p.nextToken() - if p.currentIs(token.SELECT) || p.currentIs(token.WITH) || p.currentIs(token.LPAREN) { + if p.isQueryStart() || p.currentIs(token.LPAREN) { // AS SELECT... or AS (SELECT...) INTERSECT ... create.AsSelect = p.parseSelectWithUnion() } else if p.currentIs(token.IDENT) || p.current.Token.IsKeyword() { @@ -3092,7 +3125,7 @@ func (p *Parser) parseCreateView(create *ast.CreateQuery) { // Parse AS SELECT or AS (subquery) INTERSECT/UNION (subquery) if p.currentIs(token.AS) { p.nextToken() - if p.currentIs(token.SELECT) || p.currentIs(token.WITH) || p.currentIs(token.LPAREN) { + if p.isQueryStart() || p.currentIs(token.LPAREN) { create.AsSelect = p.parseSelectWithUnion() // Extract FORMAT from inner SelectQuery and move it to CreateQuery // For CREATE VIEW/MATERIALIZED VIEW, FORMAT should be at CreateQuery level @@ -7872,13 +7905,24 @@ func (p *Parser) parseDottedIdentifier() string { // parseFromSelectSyntax handles ClickHouse's FROM ... SELECT syntax // e.g., FROM numbers(1) SELECT number +// parseFromSelectSyntax parses a FROM-first query, followed by an optional +// chain of pipe operators. func (p *Parser) parseFromSelectSyntax() *ast.SelectWithUnionQuery { + query := p.parseFromSelectSyntaxNoPipe(nil) + if query != nil && p.currentIs(token.PIPE) { + query = p.parsePipeOperators(query) + } + return query +} + +func (p *Parser) parseFromSelectSyntaxNoPipe(with []ast.Expression) *ast.SelectWithUnionQuery { query := &ast.SelectWithUnionQuery{ Position: p.current.Pos, } sel := &ast.SelectQuery{ Position: p.current.Pos, + With: with, } // Skip FROM @@ -7887,10 +7931,27 @@ func (p *Parser) parseFromSelectSyntax() *ast.SelectWithUnionQuery { // Parse table expression sel.From = p.parseTablesInSelect() - // Parse SELECT - if !p.expect(token.SELECT) { - return nil + // FROM t (a, b): column aliases for the tables + if p.currentIs(token.LPAREN) { + p.nextToken() + for !p.currentIs(token.RPAREN) && !p.currentIs(token.EOF) { + sel.ColumnAliases = append(sel.ColumnAliases, p.parseIdentifierName()) + if !p.currentIs(token.COMMA) { + break + } + p.nextToken() + } + p.expect(token.RPAREN) + } + + // SELECT is optional: FROM t [WHERE ...] means SELECT * + if !p.currentIs(token.SELECT) { + sel.Columns = []ast.Expression{&ast.Asterisk{Position: p.current.Pos}} + p.parseSelectRemainder(sel) + query.Selects = append(query.Selects, sel) + return query } + p.nextToken() // skip SELECT // Handle DISTINCT if p.currentIs(token.DISTINCT) { @@ -8810,3 +8871,317 @@ func (p *Parser) showAccessEntitiesKeyword() string { } return "" } + +// parsePipeOperators parses a chain of pipe operators (FROM t |> WHERE x |> +// SELECT y) following query. Like ClickHouse, each operator wraps the query +// so far into a subquery: SELECT ... FROM (query). +func (p *Parser) parsePipeOperators(query *ast.SelectWithUnionQuery) *ast.SelectWithUnionQuery { + pendingAlias := "" + for p.currentIs(token.PIPE) { + p.nextToken() // skip |> + switch { + case p.currentIs(token.WHERE): + p.nextToken() + sel := pipeWrap(query, &pendingAlias, nil) + sel.Where = p.parseExpression(LOWEST) + query = pipeUnion(sel) + case p.currentIs(token.SELECT): + p.nextToken() + distinct := false + if p.currentIs(token.DISTINCT) { + distinct = true + p.nextToken() + } + sel := pipeWrap(query, &pendingAlias, p.parsePipeSelectList()) + sel.Distinct = distinct + query = pipeUnion(sel) + case p.currentIs(token.IDENT) && strings.EqualFold(p.current.Value, "EXTEND"): + p.nextToken() + cols := append([]ast.Expression{&ast.Asterisk{Position: p.current.Pos}}, p.parsePipeSelectList()...) + query = pipeUnion(pipeWrap(query, &pendingAlias, cols)) + case p.currentIs(token.SET): + p.nextToken() + tr := &ast.ColumnTransformer{Position: p.current.Pos, Type: "replace"} + for { + name := p.parseIdentifierName() + if !p.expect(token.EQ) { + return query + } + tr.Replaces = append(tr.Replaces, &ast.ReplaceExpr{Position: p.current.Pos, Name: name, Expr: p.parseExpression(LOWEST)}) + if !p.currentIs(token.COMMA) { + break + } + p.nextToken() + } + star := &ast.Asterisk{Position: tr.Position, Transformers: []*ast.ColumnTransformer{tr}} + query = pipeUnion(pipeWrap(query, &pendingAlias, []ast.Expression{star})) + case p.currentIs(token.DROP): + p.nextToken() + tr := &ast.ColumnTransformer{Position: p.current.Pos, Type: "except"} + for { + tr.Except = append(tr.Except, p.parseIdentifierName()) + if !p.currentIs(token.COMMA) { + break + } + p.nextToken() + } + star := &ast.Asterisk{Position: tr.Position, Transformers: []*ast.ColumnTransformer{tr}} + query = pipeUnion(pipeWrap(query, &pendingAlias, []ast.Expression{star})) + case p.currentIs(token.AS): + p.nextToken() + pendingAlias = p.parseIdentifierName() + case p.currentIs(token.IDENT) && strings.EqualFold(p.current.Value, "AGGREGATE"): + p.nextToken() + aggregates := p.parsePipeSelectList() + var groups []ast.Expression + if p.currentIs(token.GROUP) && p.peekIs(token.BY) { + p.nextToken() + p.nextToken() + groups = p.parseExpressionList() + } + var cols, groupBy []ast.Expression + for _, g := range groups { + cols = append(cols, g) + groupBy = append(groupBy, withoutAlias(g)) + } + cols = append(cols, aggregates...) + sel := pipeWrap(query, &pendingAlias, cols) + sel.GroupBy = groupBy + query = pipeUnion(sel) + case p.currentIs(token.DISTINCT): + p.nextToken() + sel := pipeWrap(query, &pendingAlias, nil) + sel.Distinct = true + query = pipeUnion(sel) + case p.currentIs(token.ORDER) && p.peekIs(token.BY): + p.nextToken() + p.nextToken() + sel := pipeWrap(query, &pendingAlias, nil) + sel.OrderBy = p.parseOrderByList() + if p.currentIs(token.INTERPOLATE) { + p.nextToken() + sel.Interpolate = p.parseInterpolateList() + } + query = pipeUnion(sel) + case p.currentIs(token.LIMIT): + p.nextToken() + sel := pipeWrap(query, &pendingAlias, nil) + sel.Limit = p.parseExpression(LOWEST) + if p.currentIs(token.OFFSET) { + p.nextToken() + sel.Offset = p.parseExpression(LOWEST) + } + query = pipeUnion(sel) + case p.currentIs(token.OFFSET): + p.nextToken() + sel := pipeWrap(query, &pendingAlias, nil) + sel.Offset = p.parseExpression(LOWEST) + query = pipeUnion(sel) + case p.currentIs(token.UNION): + p.nextToken() + mode := "" + if p.currentIs(token.ALL) || p.currentIs(token.DISTINCT) { + mode = strings.ToUpper(p.current.Value) + p.nextToken() + } + if pendingAlias != "" { + query = pipeUnion(pipeWrap(query, &pendingAlias, nil)) + } + res := &ast.SelectWithUnionQuery{Position: query.Position} + // A single SELECT is flattened into the union + if len(query.Selects) == 1 { + res.Selects = append(res.Selects, query.Selects[0]) + } else { + res.Selects = append(res.Selects, query) + } + for { + elem := p.parsePipeUnionElement() + if elem == nil { + return res + } + res.Selects = append(res.Selects, elem) + res.UnionModes = append(res.UnionModes, mode) + if mode == "ALL" { + res.UnionAll = true + } + if !p.currentIs(token.COMMA) { + break + } + p.nextToken() + } + query = res + case p.isJoinKeyword() || p.currentIs(token.COMMA): + // |> [LEFT ...] JOIN t ON ..., |> ARRAY JOIN expr, |> , t + sel := pipeWrap(query, &pendingAlias, nil) + for p.isJoinKeyword() { + elem := p.parseTableElementWithJoin() + if elem == nil { + break + } + sel.From.Tables = append(sel.From.Tables, elem) + } + query = pipeUnion(sel) + default: + p.errors = append(p.errors, fmt.Errorf("unexpected pipe operator %s at line %d, column %d", + p.current.Value, p.current.Pos.Line, p.current.Pos.Column)) + return query + } + + // A SETTINGS clause after an operator belongs to the generated SELECT + if p.currentIs(token.SETTINGS) && len(query.Selects) == 1 { + if sel, ok := query.Selects[0].(*ast.SelectQuery); ok && len(sel.Settings) == 0 { + p.nextToken() + sel.Settings = p.parseSettingsList() + } + } + } + if pendingAlias != "" { + query = pipeUnion(pipeWrap(query, &pendingAlias, nil)) + } + return query +} + +// parsePipeSelectList parses the select list of a pipe operator, which may +// have a trailing comma. +func (p *Parser) parsePipeSelectList() []ast.Expression { + var exprs []ast.Expression + for { + expr := p.parseExpression(LOWEST) + if expr == nil { + break + } + exprs = append(exprs, p.parseImplicitAlias(expr)) + if !p.currentIs(token.COMMA) { + break + } + p.nextToken() + if p.currentIs(token.PIPE) || p.currentIs(token.EOF) || p.currentIs(token.SEMICOLON) || + p.currentIs(token.RPAREN) || p.isClauseKeyword() { + break + } + } + return exprs +} + +// parsePipeUnionElement parses an operand of |> UNION: a parenthesized query +// or a SELECT/FROM query. +func (p *Parser) parsePipeUnionElement() ast.Statement { + if p.currentIs(token.LPAREN) { + p.nextToken() + var q *ast.SelectWithUnionQuery + if p.currentIs(token.FROM) { + q = p.parseFromSelectSyntax() + } else { + q = p.parseSelectWithUnion() + } + p.expect(token.RPAREN) + if q != nil && len(q.Selects) == 1 { + return q.Selects[0] + } + return q + } + var q *ast.SelectWithUnionQuery + if p.currentIs(token.FROM) { + q = p.parseFromSelectSyntaxNoPipe(nil) + } else { + sel := p.parseSelect() + if sel == nil { + return nil + } + return sel + } + if q != nil && len(q.Selects) == 1 { + return q.Selects[0] + } + return q +} + +// pipeWrap returns SELECT cols FROM (query) [AS alias], with cols defaulting +// to *. The WITH clause of the query's first SELECT is copied so that its +// aliases and CTEs stay visible. +func pipeWrap(query *ast.SelectWithUnionQuery, pendingAlias *string, cols []ast.Expression) *ast.SelectQuery { + sel := &ast.SelectQuery{Position: query.Position} + if first := firstSelect(query); first != nil && len(first.With) > 0 { + sel.With = append([]ast.Expression(nil), first.With...) + } + if cols == nil { + cols = []ast.Expression{&ast.Asterisk{Position: query.Position}} + } + sel.Columns = cols + sel.From = &ast.TablesInSelectQuery{ + Position: query.Position, + Tables: []*ast.TablesInSelectQueryElement{{ + Position: query.Position, + Table: &ast.TableExpression{ + Position: query.Position, + Table: &ast.Subquery{Position: query.Position, Query: query}, + Alias: *pendingAlias, + }, + }}, + } + *pendingAlias = "" + return sel +} + +func pipeUnion(sel *ast.SelectQuery) *ast.SelectWithUnionQuery { + return &ast.SelectWithUnionQuery{Position: sel.Position, Selects: []ast.Statement{sel}} +} + +func firstSelect(stmt ast.Statement) *ast.SelectQuery { + switch s := stmt.(type) { + case *ast.SelectQuery: + return s + case *ast.SelectWithUnionQuery: + if len(s.Selects) > 0 { + return firstSelect(s.Selects[0]) + } + case *ast.SelectIntersectExceptQuery: + if len(s.Selects) > 0 { + return firstSelect(s.Selects[0]) + } + } + return nil +} + +// withoutAlias returns a shallow copy of expr without its alias. +func withoutAlias(expr ast.Expression) ast.Expression { + if a, ok := expr.(*ast.AliasedExpr); ok { + return a.Expr + } + v := reflect.ValueOf(expr) + if v.Kind() != reflect.Ptr || v.Elem().Kind() != reflect.Struct { + return expr + } + f := v.Elem().FieldByName("Alias") + if !f.IsValid() || f.Kind() != reflect.String || f.String() == "" { + return expr + } + c := reflect.New(v.Elem().Type()) + c.Elem().Set(v.Elem()) + c.Elem().FieldByName("Alias").SetString("") + return c.Interface().(ast.Expression) +} + +// isQueryStart reports whether the current token starts a query: SELECT, +// WITH, or a FROM-first query. +func (p *Parser) isQueryStart() bool { + return p.currentIs(token.SELECT) || p.currentIs(token.WITH) || p.isFromFirstQuery() +} + +// isFromFirstQuery reports whether the current FROM starts a FROM-first query +// (FROM t ...) rather than being a column named from, as in (from IN (1)). +func (p *Parser) isFromFirstQuery() bool { + if !p.currentIs(token.FROM) { + return false + } + switch p.peek.Token { + case token.IDENT: + return !strings.EqualFold(p.peek.Value, "INFILE") + case token.LPAREN: + return true + case token.AS, token.IN, token.IS, token.NOT, token.AND, token.OR, token.LIKE, token.ILIKE, + token.BETWEEN, token.GLOBAL, token.REGEXP: + return false + } + return p.peek.Token.IsKeyword() +} diff --git a/parser/testdata/03808_with_duplicate_alias_nested_scopes/metadata.json b/parser/testdata/03808_with_duplicate_alias_nested_scopes/metadata.json index 1295a45747..0967ef424b 100644 --- a/parser/testdata/03808_with_duplicate_alias_nested_scopes/metadata.json +++ b/parser/testdata/03808_with_duplicate_alias_nested_scopes/metadata.json @@ -1,5 +1 @@ -{ - "explain_todo": { - "stmt3": true - } -} +{} diff --git a/parser/testdata/04027_redundant_equals_variant_type/metadata.json b/parser/testdata/04027_redundant_equals_variant_type/metadata.json index ef58f80315..0967ef424b 100644 --- a/parser/testdata/04027_redundant_equals_variant_type/metadata.json +++ b/parser/testdata/04027_redundant_equals_variant_type/metadata.json @@ -1,5 +1 @@ -{ - "explain_todo": { - "stmt2": true - } -} +{} diff --git a/parser/testdata/04054_compound_interval_literals/metadata.json b/parser/testdata/04054_compound_interval_literals/metadata.json index b8bf009e9e..0967ef424b 100644 --- a/parser/testdata/04054_compound_interval_literals/metadata.json +++ b/parser/testdata/04054_compound_interval_literals/metadata.json @@ -1,38 +1 @@ -{ - "explain_todo": { - "stmt14": true, - "stmt15": true, - "stmt19": true, - "stmt2": true, - "stmt20": true, - "stmt25": true, - "stmt26": true, - "stmt3": true, - "stmt30": true, - "stmt31": true, - "stmt35": true, - "stmt36": true, - "stmt60": true, - "stmt61": true, - "stmt63": true, - "stmt64": true, - "stmt65": true, - "stmt67": true, - "stmt68": true, - "stmt69": true, - "stmt70": true, - "stmt71": true, - "stmt72": true, - "stmt73": true, - "stmt75": true, - "stmt77": true, - "stmt79": true, - "stmt8": true, - "stmt80": true, - "stmt81": true, - "stmt82": true, - "stmt84": true, - "stmt86": true, - "stmt9": true - } -} +{} diff --git a/parser/testdata/04613_pipe_operators/metadata.json b/parser/testdata/04613_pipe_operators/metadata.json index 73283c5c29..d6aae004b7 100644 --- a/parser/testdata/04613_pipe_operators/metadata.json +++ b/parser/testdata/04613_pipe_operators/metadata.json @@ -1,86 +1,12 @@ { "explain_todo": { "stmt104": true, - "stmt108": true, - "stmt109": true, - "stmt110": true, - "stmt111": true, - "stmt112": true, - "stmt115": true, - "stmt116": true, - "stmt117": true, - "stmt118": true, - "stmt119": true, - "stmt12": true, - "stmt120": true, - "stmt124": true, - "stmt125": true, - "stmt126": true, - "stmt127": true, - "stmt128": true, - "stmt13": true, - "stmt130": true, - "stmt133": true, - "stmt136": true, - "stmt137": true, - "stmt138": true, - "stmt139": true, - "stmt14": true, - "stmt141": true, - "stmt143": true, - "stmt144": true, - "stmt146": true, - "stmt148": true, - "stmt149": true, - "stmt17": true, - "stmt18": true, - "stmt22": true, - "stmt23": true, - "stmt24": true, "stmt28": true, "stmt29": true, - "stmt31": true, - "stmt33": true, - "stmt35": true, - "stmt36": true, - "stmt38": true, - "stmt40": true, - "stmt42": true, - "stmt44": true, - "stmt46": true, - "stmt48": true, - "stmt50": true, - "stmt52": true, - "stmt53": true, - "stmt54": true, - "stmt56": true, - "stmt57": true, - "stmt58": true, - "stmt59": true, - "stmt6": true, - "stmt61": true, - "stmt63": true, - "stmt64": true, - "stmt66": true, - "stmt67": true, - "stmt69": true, - "stmt7": true, "stmt70": true, "stmt71": true, - "stmt72": true, - "stmt74": true, - "stmt75": true, - "stmt77": true, - "stmt79": true, - "stmt83": true, - "stmt84": true, "stmt88": true, - "stmt89": true, "stmt92": true, - "stmt93": true, - "stmt96": true, - "stmt97": true, - "stmt98": true, - "stmt99": true + "stmt93": true } } diff --git a/parser/testdata/05229_column_named_from_in_parenthesized_expression/metadata.json b/parser/testdata/05229_column_named_from_in_parenthesized_expression/metadata.json index 9666ce458d..d4d1d99f95 100644 --- a/parser/testdata/05229_column_named_from_in_parenthesized_expression/metadata.json +++ b/parser/testdata/05229_column_named_from_in_parenthesized_expression/metadata.json @@ -1,10 +1,5 @@ { "explain_todo": { - "stmt14": true, - "stmt30": true, - "stmt31": true, - "stmt32": true, - "stmt33": true, - "stmt34": true + "stmt14": true } } diff --git a/token/token.go b/token/token.go index 88e2cc1584..2ccb7848e6 100644 --- a/token/token.go +++ b/token/token.go @@ -30,6 +30,7 @@ const ( LTE // <= GTE // >= CONCAT // || + PIPE // |> ARROW // -> COLONCOLON // :: NULL_SAFE_EQ // <=> @@ -234,6 +235,7 @@ var tokens = [...]string{ LTE: "<=", GTE: ">=", CONCAT: "||", + PIPE: "|>", ARROW: "->", COLONCOLON: "::", NULL_SAFE_EQ: "<=>",