Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(hogql): extract shared query analysis from validation (#101613)

Paweł Szczurcf582ae51c6f
diff --git a/docs/internal/hogql-language-service.md b/docs/internal/hogql-language-service.md
index ced092aa3ab2..1306f12e4b71 100644
--- a/docs/internal/hogql-language-service.md
+++ b/docs/internal/hogql-language-service.md
@@ -32,6 +32,18 @@ Django remains authoritative for authentication, team membership, entitlements,
resolution. The Go service does not read PostHog permission tables or accept browser-selected identity without an
authenticated internal request.
+## Query analysis
+
+`internal/analysis` owns validation's parsed statements, nested scopes, table and CTE bindings, and projected fields.
+Each document belongs to one request and borrows that request's immutable catalog.
+Statements initialize on demand, while CTE projections share one budget across the document.
+Validation retains diagnostic formatting, typo suggestions, and position-encoding conversion.
+
+This extraction does not change completion behavior.
+Completion still uses its existing cursor repair and table-binding recovery.
+The next layer will connect completion to the analyzer, then add CTE and subquery output suggestions.
+Select-alias visibility and property provenance remain follow-up work; recursive CTEs and compiler parity are out of scope.
+
## Isolation boundary
Every protected route requires both `team_id` and `user_id` in its path. Shared middleware converts those values into
diff --git a/services/hogql-language-service/internal/analysis/document.go b/services/hogql-language-service/internal/analysis/document.go
new file mode 100644
index 000000000000..60160065929a
--- /dev/null
+++ b/services/hogql-language-service/internal/analysis/document.go
@@ -0,0 +1,168 @@
+package analysis
+
+import (
+ "iter"
+ "slices"
+ "strings"
+
+ clickhouse "github.com/orian/clickhouse-sql-parser/parser"
+
+ "github.com/PostHog/posthog/services/hogql-language-service/internal/catalog"
+ "github.com/PostHog/posthog/services/hogql-language-service/internal/propertyresolver"
+ "github.com/PostHog/posthog/services/hogql-language-service/internal/querylimits"
+)
+
+// A Document belongs to one request. Lazy projections share its budget and must not run concurrently.
+type Document struct {
+ statements []*Statement
+ budget projectionBudget
+}
+
+type Statement struct {
+ expr clickhouse.Expr
+ schema *catalog.PreparedCatalog
+ originalTableNames map[string]string
+ budget *projectionBudget
+ scopes []*queryScope
+ tables []TableReference
+ analyzed bool
+}
+
+type TableReference struct {
+ Name string
+ Start, End int
+ Known bool
+}
+
+type Bindings struct {
+ relations map[string]Relation
+}
+
+func Analyze(schema *catalog.PreparedCatalog, query string) (*Document, error) {
+ if err := querylimits.Validate(query); err != nil {
+ return nil, err
+ }
+ parserQuery, originalTableNames := normalizeHogQLTableReferences(query)
+ statements, err := clickhouse.NewParser(parserQuery).ParseStmts()
+ if err != nil {
+ return nil, err
+ }
+ document := &Document{budget: projectionBudget{remaining: querylimits.MaxCTEProjectedFields}}
+ for _, expr := range statements {
+ document.statements = append(document.statements, &Statement{
+ expr: expr, schema: schema, originalTableNames: originalTableNames, budget: &document.budget,
+ })
+ }
+ return document, nil
+}
+
+func (d *Document) Statements() iter.Seq[*Statement] {
+ return func(yield func(*Statement) bool) {
+ for _, statement := range d.statements {
+ // Validation stops between statements when projection work exhausts the request budget.
+ statement.analyze()
+ if !yield(statement) {
+ return
+ }
+ }
+ }
+}
+
+func (d *Document) ProjectionLimitExceeded() bool {
+ return d.budget.exceeded
+}
+
+func (s *Statement) analyze() {
+ if s.analyzed {
+ return
+ }
+ s.analyzed = true
+ s.scopes = queryScopes(s.expr, s.budget)
+ clickhouse.Walk(s.expr, func(node clickhouse.Expr) bool {
+ expr, ok := node.(*clickhouse.TableExpr)
+ if !ok {
+ return true
+ }
+ name, alias, start, end, ok := tableReference(expr)
+ if !ok {
+ return true
+ }
+ scope := innermostScope(s.scopes, start, end)
+ if scope == nil {
+ return true
+ }
+ if cte := resolveCTE(scope, name, start); cte != nil {
+ addBinding(scope, name, alias, Relation{name: cte.name, cte: cte})
+ return true
+ }
+ if original, exists := s.originalTableNames[strings.ToLower(name)]; exists {
+ name = original
+ }
+ table, exists := s.schema.Table(name)
+ s.tables = append(s.tables, TableReference{Name: name, Start: start, End: end, Known: exists})
+ if exists {
+ addBinding(scope, name, alias, Relation{name: name, table: table})
+ }
+ return true
+ })
+}
+
+// Walk borrows parser nodes for validation; callers must not mutate them or retain them across requests.
+func (s *Statement) Walk(visit func(clickhouse.Expr) bool) {
+ clickhouse.Walk(s.expr, visit)
+}
+
+func (s *Statement) Tables() iter.Seq[TableReference] {
+ return slices.Values(s.tables)
+}
+
+func (s *Statement) BindingsAt(start, end int) Bindings {
+ scope := innermostScope(s.scopes, start, end)
+ if scope == nil {
+ return Bindings{}
+ }
+ if scope.visible == nil {
+ scope.visible = visibleBindings(scope)
+ }
+ return Bindings{relations: scope.visible}
+}
+
+func (b Bindings) Len() int {
+ return len(b.relations)
+}
+
+func (b Bindings) Relation(name string) (Relation, bool) {
+ relation, ok := b.relations[strings.ToLower(name)]
+ return relation, ok
+}
+
+func (b Bindings) All() iter.Seq2[string, Relation] {
+ return func(yield func(string, Relation) bool) {
+ for name, relation := range b.relations {
+ if !yield(name, relation) {
+ return
+ }
+ }
+ }
+}
+
+func (b Bindings) PropertyNamespace(parts []string) (string, bool) {
+ names := make(map[string]string, len(b.relations))
+ for name, relation := range b.relations {
+ names[name] = relation.name
+ }
+ return propertyresolver.Resolve(parts, names)
+}
+
+func (r Relation) Name() string {
+ return r.name
+}
+
+func (r Relation) Field(name string) (catalog.Entry, bool) {
+ return bindingField(r, name)
+}
+
+// Fields yields values without copying catalog indexes or exposing their backing slices.
+func (r Relation) Fields() iter.Seq[catalog.Entry] {
+ return slices.Values(bindingFields(r))
+}
diff --git a/services/hogql-language-service/internal/analysis/scopes.go b/services/hogql-language-service/internal/analysis/scopes.go
new file mode 100644
index 000000000000..e4998d60a9e0
--- /dev/null
+++ b/services/hogql-language-service/internal/analysis/scopes.go
@@ -0,0 +1,316 @@
+package analysis
+
+import (
+ "regexp"
+ "strings"
+
+ clickhouse "github.com/orian/clickhouse-sql-parser/parser"
+
+ "github.com/PostHog/posthog/services/hogql-language-service/internal/catalog"
+)
+
+type Relation struct {
+ name string
+ table *catalog.PreparedTable
+ cte *cteBinding
+}
+
+type cteBinding struct {
+ name string
+ query *clickhouse.SelectQuery
+ scope *queryScope
+ budget *projectionBudget
+ fields []catalog.Entry
+ fieldsDone bool
+ resolving bool
+}
+
+type projectionBudget struct {
+ remaining int
+ exceeded bool
+}
+
+type queryScope struct {
+ query *clickhouse.SelectQuery
+ parent *queryScope
+ bindings map[string]Relation
+ visible map[string]Relation
+ ctes []*cteBinding
+ cteRoot bool
+}
+
+var tableReferencePattern = regexp.MustCompile(`(?i)\b(?:FROM|JOIN)\s+([A-Za-z_][A-Za-z0-9_.$]*)`)
+
+func queryScopes(statement clickhouse.Expr, budget *projectionBudget) []*queryScope {
+ var scopes []*queryScope
+ byQuery := map[*clickhouse.SelectQuery]*queryScope{}
+ clickhouse.Walk(statement, func(node clickhouse.Expr) bool {
+ if query, ok := node.(*clickhouse.SelectQuery); ok {
+ scope := &queryScope{query: query, bindings: map[string]Relation{}}
+ scopes = append(scopes, scope)
+ byQuery[query] = scope
+ }
+ return true
+ })
+ for _, scope := range scopes {
+ for _, candidate := range scopes {
+ if scope == candidate || span(candidate.query) <= span(scope.query) || !contains(candidate.query, int(scope.query.Pos()), int(scope.query.End())) {
+ continue
+ }
+ if scope.parent == nil || span(candidate.query) < span(scope.parent.query) {
+ scope.parent = candidate
+ }
+ }
+ }
+ for _, scope := range scopes {
+ if scope.query.With == nil {
+ continue
+ }
+ for _, statement := range scope.query.With.CTEs {
+ name, nameOK := statement.Expr.(*clickhouse.Ident)
+ query, queryOK := statement.Alias.(*clickhouse.SelectQuery)
+ if !nameOK || !queryOK {
+ continue
+ }
+ cte := &cteBinding{name: name.Name, query: query, scope: byQuery[query], budget: budget}
+ if cte.scope != nil {
+ cte.scope.cteRoot = true
+ }
+ scope.ctes = append(scope.ctes, cte)
+ }
+ }
+ return scopes
+}
+
+func addBinding(scope *queryScope, name, alias string, binding Relation) {
+ scope.bindings[strings.ToLower(name)] = binding
+ if alias != "" {
+ scope.bindings[strings.ToLower(alias)] = binding
+ }
+}
+
+func resolveCTE(scope *queryScope, name string, position int) *cteBinding {
+ for current := scope; current != nil; current = current.parent {
+ limit := len(current.ctes)
+ for index, cte := range current.ctes {
+ if contains(cte.query, position, position) {
+ limit = index
+ break
+ }
+ }
+ for index := limit - 1; index >= 0; index-- {
+ if strings.EqualFold(current.ctes[index].name, name) {
+ return current.ctes[index]
+ }
+ }
+ }
+ return nil
+}
+
+func innermostScope(scopes []*queryScope, start, end int) *queryScope {
+ var found *queryScope
+ for _, scope := range scopes {
+ if contains(scope.query, start, end) && (found == nil || span(scope.query) < span(found.query)) {
+ found = scope
+ }
+ }
+ return found
+}
+
+func contains(query *clickhouse.SelectQuery, start, end int) bool {
+ return int(query.Pos()) <= start && end <= int(query.End())
+}
+
+func span(query *clickhouse.SelectQuery) int {
+ return int(query.End() - query.Pos())
+}
+
+func visibleBindings(scope *queryScope) map[string]Relation {
+ bindings := map[string]Relation{}
+ for current := scope; current != nil; current = current.parent {
+ for name, binding := range current.bindings {
+ if _, exists := bindings[name]; !exists {
+ bindings[name] = binding
+ }
+ }
+ if current.cteRoot {
+ break
+ }
+ }
+ return bindings
+}
+
+func normalizeHogQLTableReferences(query string) (string, map[string]string) {
+ normalized := []byte(query)
+ originalNames := map[string]string{}
+ for _, indexes := range tableReferencePattern.FindAllStringSubmatchIndex(query, -1) {
+ start, end := indexes[2], indexes[3]
+ name := query[start:end]
+ firstDot := strings.IndexByte(name, '.')
+ if firstDot == -1 || !strings.Contains(name[firstDot+1:], ".") {
+ continue
+ }
+ for index := start + firstDot + 1; index < end; index++ {
+ if normalized[index] == '.' {
+ normalized[index] = '_'
+ }
+ }
+ originalNames[strings.ToLower(string(normalized[start:end]))] = name
+ }
+ return string(normalized), originalNames
+}
+
+func tableReference(expr *clickhouse.TableExpr) (name, alias string, start, end int, ok bool) {
+ node := expr.Expr
+ if aliased, isAlias := node.(*clickhouse.AliasExpr); isAlias {
+ node = aliased.Expr
+ if ident, isIdent := aliased.Alias.(*clickhouse.Ident); isIdent {
+ alias = ident.Name
+ }
+ }
+ identifier, isTable := node.(*clickhouse.TableIdentifier)
+ if !isTable || identifier.Table == nil {
+ return "", "", 0, 0, false
+ }
+ name = identifier.Table.Name
+ if identifier.Database != nil {
+ name = identifier.Database.Name + "." + name
+ }
+ return name, alias, int(identifier.Pos()), int(identifier.End()), true
+}
+
+func bindingField(binding Relation, name string) (catalog.Entry, bool) {
+ if binding.table != nil {
+ return binding.table.Fields.Exact(name)
+ }
+ for _, field := range bindingFields(binding) {
+ if strings.EqualFold(field.Name, name) {
+ return field, true
+ }
+ }
+ return catalog.Entry{}, false
+}
+
+func bindingFields(binding Relation) []catalog.Entry {
+ if binding.table != nil {
+ return binding.table.Fields.Entries()
+ }
+ if binding.cte == nil {
+ return nil
+ }
+ return binding.cte.projectedFields()
+}
+
+func (c *cteBinding) projectedFields() []catalog.Entry {
+ if c.fieldsDone || c.resolving || c.scope == nil || c.budget.exceeded {
+ return c.fields
+ }
+ c.resolving = true
+ for _, item := range c.query.SelectItems {
+ if item.Alias != nil {
+ c.appendField(catalog.Entry{Name: item.Alias.Name, Type: projectedType(c.scope, item.Expr)})
+ if c.budget.exceeded {
+ break
+ }
+ continue
+ }
+ switch expr := item.Expr.(type) {
+ case *clickhouse.Ident:
+ if expr.Name == "*" {
+ c.appendWildcardFields(c.scope, "")
+ } else {
+ c.appendField(catalog.Entry{Name: expr.Name, Type: projectedType(c.scope, expr)})
+ }
+ case *clickhouse.Path:
+ if len(expr.Fields) > 0 {
+ c.appendField(catalog.Entry{Name: expr.Fields[len(expr.Fields)-1].Name, Type: projectedType(c.scope, expr)})
+ }
+ case *clickhouse.NestedIdentifier:
+ if expr.DotIdent != nil && expr.DotIdent.Name == "*" {
+ c.appendWildcardFields(c.scope, expr.Ident.Name)
+ } else if expr.DotIdent != nil {
+ c.appendField(catalog.Entry{Name: expr.DotIdent.Name, Type: projectedType(c.scope, expr)})
+ } else {
+ c.appendField(catalog.Entry{Name: expr.Ident.Name, Type: projectedType(c.scope, expr)})
+ }
+ default:
+ c.appendField(catalog.Entry{Name: item.Expr.String()})
+ }
+ if c.budget.exceeded {
+ break
+ }
+ }
+ c.resolving = false
+ c.fieldsDone = true
+ return c.fields
+}
+
+func (c *cteBinding) appendField(field catalog.Entry) {
+ if c.budget.take(1) == 1 {
+ c.fields = append(c.fields, field)
+ }
+}
+
+func (c *cteBinding) appendFields(fields []catalog.Entry) {
+ count := c.budget.take(len(fields))
+ c.fields = append(c.fields, fields[:count]...)
+}
+
+func (c *cteBinding) appendWildcardFields(scope *queryScope, qualifier string) {
+ bindings := visibleBindings(scope)
+ if qualifier != "" {
+ c.appendFields(bindingFields(bindings[strings.ToLower(qualifier)]))
+ return
+ }
+ seen := map[string]bool{}
+ for _, binding := range bindings {
+ if seen[binding.name] {
+ continue
+ }
+ seen[binding.name] = true
+ c.appendFields(bindingFields(binding))
+ if c.budget.exceeded {
+ return
+ }
+ }
+}
+
+func (b *projectionBudget) take(count int) int {
+ if count <= b.remaining {
+ b.remaining -= count
+ return count
+ }
+ taken := b.remaining
+ b.remaining = 0
+ b.exceeded = true
+ return taken
+}
+
+func projectedType(scope *queryScope, expr clickhouse.Expr) string {
+ bindings := visibleBindings(scope)
+ switch typed := expr.(type) {
+ case *clickhouse.Ident:
+ for _, binding := range bindings {
+ if field, ok := bindingField(binding, typed.Name); ok {
+ return field.Type
+ }
+ }
+ case *clickhouse.Path:
+ if len(typed.Fields) >= 2 {
+ if binding, ok := bindings[strings.ToLower(typed.Fields[0].Name)]; ok {
+ if field, exists := bindingField(binding, typed.Fields[1].Name); exists {
+ return field.Type
+ }
+ }
+ }
+ case *clickhouse.NestedIdentifier:
+ if typed.DotIdent != nil {
+ if binding, ok := bindings[strings.ToLower(typed.Ident.Name)]; ok {
+ if field, exists := bindingField(binding, typed.DotIdent.Name); exists {
+ return field.Type
+ }
+ }
+ }
+ }
+ return ""
+}
diff --git a/services/hogql-language-service/internal/validation/validation.go b/services/hogql-language-service/internal/validation/validation.go
index 3abbc61b3f2a..5fae52e02209 100644
--- a/services/hogql-language-service/internal/validation/validation.go
+++ b/services/hogql-language-service/internal/validation/validation.go
@@ -1,8 +1,10 @@
package validation
import (
+ "errors"
"fmt"
- "regexp"
+ "iter"
+ "slices"
"sort"
"strings"
"time"
@@ -10,8 +12,8 @@ import (
clickhouse "github.com/orian/clickhouse-sql-parser/parser"
+ "github.com/PostHog/posthog/services/hogql-language-service/internal/analysis"
"github.com/PostHog/posthog/services/hogql-language-service/internal/catalog"
- "github.com/PostHog/posthog/services/hogql-language-service/internal/propertyresolver"
"github.com/PostHog/posthog/services/hogql-language-service/internal/querylimits"
"github.com/PostHog/posthog/services/hogql-language-service/internal/textposition"
)
@@ -36,92 +38,37 @@ type Result struct {
DurationMicros int64 `json:"durationMicros"`
}
-type tableBinding struct {
- name string
- table *catalog.PreparedTable
- cte *cteBinding
-}
-
-type cteBinding struct {
- name string
- query *clickhouse.SelectQuery
- scope *queryScope
- budget *projectionBudget
- fields []catalog.Entry
- fieldsDone bool
- resolving bool
-}
-
-type projectionBudget struct {
- remaining int
- exceeded bool
-}
-
-type queryScope struct {
- query *clickhouse.SelectQuery
- parent *queryScope
- bindings map[string]tableBinding
- ctes []*cteBinding
- cteRoot bool
-}
-
-var tableReferencePattern = regexp.MustCompile(`(?i)\b(?:FROM|JOIN)\s+([A-Za-z_][A-Za-z0-9_.$]*)`)
-
func Validate(schema *catalog.PreparedCatalog, query string) Result {
started := time.Now()
- if err := querylimits.Validate(query); err != nil {
- return result([]Diagnostic{{Code: "query_limit", Message: err.Error(), Start: 0, End: len(query)}}, nil, started)
- }
- parserQuery, originalTableNames := normalizeHogQLTableReferences(query)
- statements, err := clickhouse.NewParser(parserQuery).ParseStmts()
+ document, err := analysis.Analyze(schema, query)
if err != nil {
- return result([]Diagnostic{{
- Code: "syntax_error", Message: err.Error(), Start: 0, End: len(query),
- }}, nil, started)
+ code := "syntax_error"
+ if errors.Is(err, querylimits.ErrQueryTooLarge) || errors.Is(err, querylimits.ErrQueryTooDeep) {
+ code = "query_limit"
+ }
+ return result([]Diagnostic{{Code: code, Message: err.Error(), Start: 0, End: len(query)}}, nil, started)
}
var diagnostics []Diagnostic
var referencedTableNames []string
seenTableNames := map[string]bool{}
- budget := projectionBudget{remaining: querylimits.MaxCTEProjectedFields}
- for _, statement := range statements {
- scopes := queryScopes(statement, &budget)
+ for statement := range document.Statements() {
+ for table := range statement.Tables() {
+ lowerName := strings.ToLower(table.Name)
+ if !seenTableNames[lowerName] {
+ referencedTableNames = append(referencedTableNames, table.Name)
+ seenTableNames[lowerName] = true
+ }
+ if !table.Known && len(diagnostics) < querylimits.MaxDiagnostics {
+ diagnostics = append(diagnostics, Diagnostic{
+ Code: "unknown_table", Message: fmt.Sprintf("Unknown table %q", table.Name), Start: table.Start, End: table.End,
+ Suggestions: closest(table.Name, slices.Values(schema.Tables().Entries()), 5),
+ })
+ }
+ }
ignoredIdents := map[*clickhouse.Ident]bool{}
- clickhouse.Walk(statement, func(node clickhouse.Expr) bool {
+ statement.Walk(func(node clickhouse.Expr) bool {
switch typed := node.(type) {
- case *clickhouse.TableExpr:
- name, alias, start, end, ok := tableReference(typed)
- if !ok {
- return true
- }
- scope := innermostScope(scopes, start, end)
- if scope == nil {
- return true
- }
- if cte := resolveCTE(scope, name, start); cte != nil {
- addBinding(scope, name, alias, tableBinding{name: cte.name, cte: cte})
- return true
- }
- if original, exists := originalTableNames[strings.ToLower(name)]; exists {
- name = original
- }
- lowerName := strings.ToLower(name)
- if !seenTableNames[lowerName] {
- referencedTableNames = append(referencedTableNames, name)
- seenTableNames[lowerName] = true
- }
- table, exists := schema.Table(name)
- if !exists {
- if len(diagnostics) < querylimits.MaxDiagnostics {
- diagnostics = append(diagnostics, Diagnostic{
- Code: "unknown_table", Message: fmt.Sprintf("Unknown table %q", name), Start: start, End: end,
- Suggestions: closest(name, schema.Tables().Entries(), 5),
- })
- }
- return true
- }
- binding := tableBinding{name: name, table: table}
- addBinding(scope, name, alias, binding)
case *clickhouse.TableIdentifier:
ignoredIdents[typed.Database] = true
ignoredIdents[typed.Table] = true
@@ -145,48 +92,44 @@ func Validate(schema *catalog.PreparedCatalog, query string) Result {
return true
})
seen := map[string]bool{}
- clickhouse.Walk(statement, func(node clickhouse.Expr) bool {
+ statement.Walk(func(node clickhouse.Expr) bool {
switch typed := node.(type) {
case *clickhouse.NestedIdentifier:
if typed.DotIdent == nil {
return true
}
ignoredIdents[typed.DotIdent] = true
- bindings := visibleBindings(innermostScope(scopes, int(node.Pos()), int(node.End())))
- if binding, ok := bindings[strings.ToLower(typed.Ident.Name)]; ok {
+ bindings := statement.BindingsAt(int(node.Pos()), int(node.End()))
+ if binding, ok := bindings.Relation(typed.Ident.Name); ok {
ignoredIdents[typed.Ident] = true
if typed.DotIdent.Name != "*" {
- validateField(&diagnostics, seen, binding, typed.DotIdent, &budget)
+ validateField(&diagnostics, seen, binding, typed.DotIdent, document)
}
}
case *clickhouse.Path:
if len(typed.Fields) < 2 {
return true
}
- bindings := visibleBindings(innermostScope(scopes, int(node.Pos()), int(node.End())))
- if len(bindings) == 0 {
+ bindings := statement.BindingsAt(int(node.Pos()), int(node.End()))
+ if bindings.Len() == 0 {
return true
}
parts := make([]string, len(typed.Fields))
for index, field := range typed.Fields {
parts[index] = field.Name
}
- bindingNames := make(map[string]string, len(bindings))
- for name, binding := range bindings {
- bindingNames[name] = binding.name
- }
- if namespace, ok := propertyresolver.Resolve(parts, bindingNames); ok {
+ if namespace, ok := bindings.PropertyNamespace(parts); ok {
for _, field := range typed.Fields {
ignoredIdents[field] = true
}
validateProperty(&diagnostics, seen, schema.Properties(namespace), typed.Fields[len(typed.Fields)-1])
return true
}
- if binding, ok := bindings[strings.ToLower(typed.Fields[0].Name)]; ok {
+ if binding, ok := bindings.Relation(typed.Fields[0].Name); ok {
for _, field := range typed.Fields {
ignoredIdents[field] = true
}
- validateField(&diagnostics, seen, binding, typed.Fields[1], &budget)
+ validateField(&diagnostics, seen, binding, typed.Fields[1], document)
} else {
for _, field := range typed.Fields[1:] {
ignoredIdents[field] = true
@@ -196,18 +139,18 @@ func Validate(schema *catalog.PreparedCatalog, query string) Result {
if ignoredIdents[typed] || typed.Name == "*" {
return true
}
- bindings := visibleBindings(innermostScope(scopes, int(node.Pos()), int(node.End())))
- if len(bindings) > 0 {
- validateUnqualifiedField(&diagnostics, seen, bindings, typed, &budget)
+ bindings := statement.BindingsAt(int(node.Pos()), int(node.End()))
+ if bindings.Len() > 0 {
+ validateUnqualifiedField(&diagnostics, seen, bindings, typed, document)
}
}
return true
})
- if budget.exceeded {
+ if document.ProjectionLimitExceeded() {
break
}
}
- if budget.exceeded && len(diagnostics) < querylimits.MaxDiagnostics {
+ if document.ProjectionLimitExceeded() && len(diagnostics) < querylimits.MaxDiagnostics {
diagnostics = append(diagnostics, Diagnostic{
Code: "query_limit", Message: querylimits.ErrCTEProjectionTooLarge.Error(), Start: 0, End: len(query),
})
@@ -235,105 +178,6 @@ func ValidateWithEncoding(schema *catalog.PreparedCatalog, query string, encodin
return result, nil
}
-func queryScopes(statement clickhouse.Expr, budget *projectionBudget) []*queryScope {
- var scopes []*queryScope
- byQuery := map[*clickhouse.SelectQuery]*queryScope{}
- clickhouse.Walk(statement, func(node clickhouse.Expr) bool {
- if query, ok := node.(*clickhouse.SelectQuery); ok {
- scope := &queryScope{query: query, bindings: map[string]tableBinding{}}
- scopes = append(scopes, scope)
- byQuery[query] = scope
- }
- return true
- })
- for _, scope := range scopes {
- for _, candidate := range scopes {
- if scope == candidate || span(candidate.query) <= span(scope.query) || !contains(candidate.query, int(scope.query.Pos()), int(scope.query.End())) {
- continue
- }
- if scope.parent == nil || span(candidate.query) < span(scope.parent.query) {
- scope.parent = candidate
- }
- }
- }
- for _, scope := range scopes {
- if scope.query.With == nil {
- continue
- }
- for _, statement := range scope.query.With.CTEs {
- name, nameOK := statement.Expr.(*clickhouse.Ident)
- query, queryOK := statement.Alias.(*clickhouse.SelectQuery)
- if !nameOK || !queryOK {
- continue
- }
- cte := &cteBinding{name: name.Name, query: query, scope: byQuery[query], budget: budget}
- if cte.scope != nil {
- cte.scope.cteRoot = true
- }
- scope.ctes = append(scope.ctes, cte)
- }
- }
- return scopes
-}
-
-func addBinding(scope *queryScope, name, alias string, binding tableBinding) {
- scope.bindings[strings.ToLower(name)] = binding
- if alias != "" {
- scope.bindings[strings.ToLower(alias)] = binding
- }
-}
-
-func resolveCTE(scope *queryScope, name string, position int) *cteBinding {
- for current := scope; current != nil; current = current.parent {
- limit := len(current.ctes)
- for index, cte := range current.ctes {
- if contains(cte.query, position, position) {
- limit = index
- break
- }
- }
- for index := limit - 1; index >= 0; index-- {
- if strings.EqualFold(current.ctes[index].name, name) {
- return current.ctes[index]
- }
- }
- }
- return nil
-}
-
-func innermostScope(scopes []*queryScope, start, end int) *queryScope {
- var found *queryScope
- for _, scope := range scopes {
- if contains(scope.query, start, end) && (found == nil || span(scope.query) < span(found.query)) {
- found = scope
- }
- }
- return found
-}
-
-func contains(query *clickhouse.SelectQuery, start, end int) bool {
- return int(query.Pos()) <= start && end <= int(query.End())
-}
-
-func span(query *clickhouse.SelectQuery) int {
- return int(query.End() - query.Pos())
-}
-
-func visibleBindings(scope *queryScope) map[string]tableBinding {
- bindings := map[string]tableBinding{}
- for current := scope; current != nil; current = current.parent {
- for name, binding := range current.bindings {
- if _, exists := bindings[name]; !exists {
- bindings[name] = binding
- }
- }
- if current.cteRoot {
- break
- }
- }
- return bindings
-}
-
func validateProperty(diagnostics *[]Diagnostic, seen map[string]bool, properties *catalog.Index, ident *clickhouse.Ident) {
if len(*diagnostics) >= querylimits.MaxDiagnostics {
return
@@ -348,57 +192,18 @@ func validateProperty(diagnostics *[]Diagnostic, seen map[string]bool, propertie
seen[key] = true
*diagnostics = append(*diagnostics, Diagnostic{
Code: "unknown_property", Message: fmt.Sprintf("Unknown property %q", ident.Name), Start: int(ident.Pos()), End: int(ident.End()),
- Suggestions: closest(ident.Name, properties.Entries(), 5),
+ Suggestions: closest(ident.Name, slices.Values(properties.Entries()), 5),
})
}
-func normalizeHogQLTableReferences(query string) (string, map[string]string) {
- normalized := []byte(query)
- originalNames := map[string]string{}
- for _, indexes := range tableReferencePattern.FindAllStringSubmatchIndex(query, -1) {
- start, end := indexes[2], indexes[3]
- name := query[start:end]
- firstDot := strings.IndexByte(name, '.')
- if firstDot == -1 || !strings.Contains(name[firstDot+1:], ".") {
- continue
- }
- for index := start + firstDot + 1; index < end; index++ {
- if normalized[index] == '.' {
- normalized[index] = '_'
- }
- }
- originalNames[strings.ToLower(string(normalized[start:end]))] = name
- }
- return string(normalized), originalNames
-}
-
-func tableReference(expr *clickhouse.TableExpr) (name, alias string, start, end int, ok bool) {
- node := expr.Expr
- if aliased, isAlias := node.(*clickhouse.AliasExpr); isAlias {
- node = aliased.Expr
- if ident, isIdent := aliased.Alias.(*clickhouse.Ident); isIdent {
- alias = ident.Name
- }
- }
- identifier, isTable := node.(*clickhouse.TableIdentifier)
- if !isTable || identifier.Table == nil {
- return "", "", 0, 0, false
- }
- name = identifier.Table.Name
- if identifier.Database != nil {
- name = identifier.Database.Name + "." + name
- }
- return name, alias, int(identifier.Pos()), int(identifier.End()), true
-}
-
-func validateField(diagnostics *[]Diagnostic, seen map[string]bool, binding tableBinding, ident *clickhouse.Ident, budget *projectionBudget) {
- if len(*diagnostics) >= querylimits.MaxDiagnostics || budget.exceeded {
+func validateField(diagnostics *[]Diagnostic, seen map[string]bool, binding analysis.Relation, ident *clickhouse.Ident, document *analysis.Document) {
+ if len(*diagnostics) >= querylimits.MaxDiagnostics || document.ProjectionLimitExceeded() {
return
}
- if _, ok := bindingField(binding, ident.Name); ok {
+ if _, ok := binding.Field(ident.Name); ok {
return
}
- if budget.exceeded {
+ if document.ProjectionLimitExceeded() {
return
}
key := fmt.Sprintf("%d:%d", ident.Pos(), ident.End())
@@ -408,28 +213,28 @@ func validateField(diagnostics *[]Diagnostic, seen map[string]bool, binding tabl
seen[key] = true
*diagnostics = append(*diagnostics, Diagnostic{
Code: "unknown_field", Message: fmt.Sprintf("Unknown field %q", ident.Name), Start: int(ident.Pos()), End: int(ident.End()),
- Suggestions: closest(ident.Name, bindingFields(binding), 5),
+ Suggestions: closest(ident.Name, binding.Fields(), 5),
})
}
-func validateUnqualifiedField(diagnostics *[]Diagnostic, seen map[string]bool, bindings map[string]tableBinding, ident *clickhouse.Ident, budget *projectionBudget) {
- if len(*diagnostics) >= querylimits.MaxDiagnostics || budget.exceeded {
+func validateUnqualifiedField(diagnostics *[]Diagnostic, seen map[string]bool, bindings analysis.Bindings, ident *clickhouse.Ident, document *analysis.Document) {
+ if len(*diagnostics) >= querylimits.MaxDiagnostics || document.ProjectionLimitExceeded() {
return
}
- uniqueTables := map[string]tableBinding{}
- for _, binding := range bindings {
- uniqueTables[binding.name] = binding
- if _, ok := bindingField(binding, ident.Name); ok {
+ uniqueTables := map[string]analysis.Relation{}
+ for _, binding := range bindings.All() {
+ uniqueTables[binding.Name()] = binding
+ if _, ok := binding.Field(ident.Name); ok {
return
}
- if budget.exceeded {
+ if document.ProjectionLimitExceeded() {
return
}
}
candidates := make([]catalog.Entry, 0)
for _, binding := range uniqueTables {
- candidates = append(candidates, bindingFields(binding)...)
- if budget.exceeded {
+ candidates = slices.AppendSeq(candidates, binding.Fields())
+ if document.ProjectionLimitExceeded() {
return
}
}
@@ -440,147 +245,11 @@ func validateUnqualifiedField(diagnostics *[]Diagnostic, seen map[string]bool, b
seen[key] = true
*diagnostics = append(*diagnostics, Diagnostic{
Code: "unknown_field", Message: fmt.Sprintf("Unknown field %q", ident.Name), Start: int(ident.Pos()), End: int(ident.End()),
- Suggestions: closest(ident.Name, candidates, 5),
+ Suggestions: closest(ident.Name, slices.Values(candidates), 5),
})
}
-func bindingField(binding tableBinding, name string) (catalog.Entry, bool) {
- if binding.table != nil {
- return binding.table.Fields.Exact(name)
- }
- for _, field := range bindingFields(binding) {
- if strings.EqualFold(field.Name, name) {
- return field, true
- }
- }
- return catalog.Entry{}, false
-}
-
-func bindingFields(binding tableBinding) []catalog.Entry {
- if binding.table != nil {
- return binding.table.Fields.Entries()
- }
- if binding.cte == nil {
- return nil
- }
- return binding.cte.projectedFields()
-}
-
-func (c *cteBinding) projectedFields() []catalog.Entry {
- if c.fieldsDone || c.resolving || c.scope == nil || c.budget.exceeded {
- return c.fields
- }
- c.resolving = true
- for _, item := range c.query.SelectItems {
- if item.Alias != nil {
- c.appendField(catalog.Entry{Name: item.Alias.Name, Type: projectedType(c.scope, item.Expr)})
- if c.budget.exceeded {
- break
- }
- continue
- }
- switch expr := item.Expr.(type) {
- case *clickhouse.Ident:
- if expr.Name == "*" {
- c.appendWildcardFields(c.scope, "")
- } else {
- c.appendField(catalog.Entry{Name: expr.Name, Type: projectedType(c.scope, expr)})
- }
- case *clickhouse.Path:
- if len(expr.Fields) > 0 {
- c.appendField(catalog.Entry{Name: expr.Fields[len(expr.Fields)-1].Name, Type: projectedType(c.scope, expr)})
- }
- case *clickhouse.NestedIdentifier:
- if expr.DotIdent != nil && expr.DotIdent.Name == "*" {
- c.appendWildcardFields(c.scope, expr.Ident.Name)
- } else if expr.DotIdent != nil {
- c.appendField(catalog.Entry{Name: expr.DotIdent.Name, Type: projectedType(c.scope, expr)})
- } else {
- c.appendField(catalog.Entry{Name: expr.Ident.Name, Type: projectedType(c.scope, expr)})
- }
- default:
- c.appendField(catalog.Entry{Name: item.Expr.String()})
- }
- if c.budget.exceeded {
- break
- }
- }
- c.resolving = false
- c.fieldsDone = true
- return c.fields
-}
-
-func (c *cteBinding) appendField(field catalog.Entry) {
- if c.budget.take(1) == 1 {
- c.fields = append(c.fields, field)
- }
-}
-
-func (c *cteBinding) appendFields(fields []catalog.Entry) {
- count := c.budget.take(len(fields))
- c.fields = append(c.fields, fields[:count]...)
-}
-
-func (c *cteBinding) appendWildcardFields(scope *queryScope, qualifier string) {
- bindings := visibleBindings(scope)
- if qualifier != "" {
- c.appendFields(bindingFields(bindings[strings.ToLower(qualifier)]))
- return
- }
- seen := map[string]bool{}
- for _, binding := range bindings {
- if seen[binding.name] {
- continue
- }
- seen[binding.name] = true
- c.appendFields(bindingFields(binding))
- if c.budget.exceeded {
- return
- }
- }
-}
-
-func (b *projectionBudget) take(count int) int {
- if count <= b.remaining {
- b.remaining -= count
- return count
- }
- taken := b.remaining
- b.remaining = 0
- b.exceeded = true
- return taken
-}
-
-func projectedType(scope *queryScope, expr clickhouse.Expr) string {
- bindings := visibleBindings(scope)
- switch typed := expr.(type) {
- case *clickhouse.Ident:
- for _, binding := range bindings {
- if field, ok := bindingField(binding, typed.Name); ok {
- return field.Type
- }
- }
- case *clickhouse.Path:
- if len(typed.Fields) >= 2 {
- if binding, ok := bindings[strings.ToLower(typed.Fields[0].Name)]; ok {
- if field, exists := bindingField(binding, typed.Fields[1].Name); exists {
- return field.Type
- }
- }
- }
- case *clickhouse.NestedIdentifier:
- if typed.DotIdent != nil {
- if binding, ok := bindings[strings.ToLower(typed.Ident.Name)]; ok {
- if field, exists := bindingField(binding, typed.DotIdent.Name); exists {
- return field.Type
- }
- }
- }
- }
- return ""
-}
-
-func closest(input string, candidates []catalog.Entry, limit int) []Suggestion {
+func closest(input string, candidates iter.Seq[catalog.Entry], limit int) []Suggestion {
if len(input) > querylimits.MaxSuggestionInputBytes {
return nil
}
@@ -589,7 +258,7 @@ func closest(input string, candidates []catalog.Entry, limit int) []Suggestion {
threshold := min(4, max(2, leftLength/3))
best := make([]Suggestion, 0, limit)
workspace := levenshteinWorkspace{}
- for _, candidate := range candidates {
+ for candidate := range candidates {
if len(candidate.Name) > querylimits.MaxSuggestionInputBytes {
continue
}
diff --git a/services/hogql-language-service/internal/validation/validation_test.go b/services/hogql-language-service/internal/validation/validation_test.go
index 73c4f1069272..7b710ef7b728 100644
--- a/services/hogql-language-service/internal/validation/validation_test.go
+++ b/services/hogql-language-service/internal/validation/validation_test.go
@@ -222,9 +222,27 @@ func TestValidateBoundsCommonTableExpressionProjectionExpansion(t *testing.T) {
index, index-1, index-1,
))
}
- result := Validate(schema(), "WITH "+strings.Join(ctes, ", ")+" SELECT missing FROM c13")
- if result.Valid || len(result.Diagnostics) != 1 || result.Diagnostics[0].Code != "query_limit" {
- t.Fatalf("result = %#v", result)
+ withinBudget := "WITH " + strings.Join(ctes[:12], ", ") + " SELECT event FROM c11"
+ for _, test := range []struct {
+ name, query string
+ valid bool
+ }{
+ {name: "single statement within budget", query: withinBudget, valid: true},
+ {name: "single statement exceeds budget", query: "WITH " + strings.Join(ctes, ", ") + " SELECT missing FROM c13"},
+ {name: "shared budget stops before later statements", query: withinBudget + "; " + withinBudget + "; SELECT person_id FROM warehouse_people"},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ result := Validate(schema(), test.query)
+ if result.Valid != test.valid {
+ t.Fatalf("result = %#v", result)
+ }
+ if !test.valid && (len(result.Diagnostics) != 1 || result.Diagnostics[0].Code != "query_limit") {
+ t.Fatalf("result = %#v", result)
+ }
+ if strings.Join(result.TableNames, ",") != "events" {
+ t.Fatalf("table names = %#v", result.TableNames)
+ }
+ })
}
}