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.

fix(hogql): resolve CTEs in language service validation (#101408)

Paweł Szczur93538036e9f7
diff --git a/services/hogql-language-service/README.md b/services/hogql-language-service/README.md
index c238420960a6..c950d33a1f26 100644
--- a/services/hogql-language-service/README.md
+++ b/services/hogql-language-service/README.md
@@ -30,6 +30,11 @@ curl -sS -X POST http://localhost:8091/teams/2/users/1/validate \
-d '{"query":"SELECT amuont FROM warehouse_0420"}'
```
+Validation resolves table CTEs in the language service, validates their projected fields, and reports only the
+underlying catalog tables in `tableNames`.
+Each validation request can expand up to 16,384 projected CTE fields. Larger projections return a `query_limit`
+diagnostic and ask the user to select fewer fields.
+
Diagnostics contain byte offsets and up to five visible typo suggestions ranked by case-insensitive Levenshtein
distance. Dynamic properties use the same cached namespaces as autocomplete.
diff --git a/services/hogql-language-service/internal/querylimits/limits.go b/services/hogql-language-service/internal/querylimits/limits.go
index 609c3a75f557..d832e329de2c 100644
--- a/services/hogql-language-service/internal/querylimits/limits.go
+++ b/services/hogql-language-service/internal/querylimits/limits.go
@@ -6,9 +6,11 @@ const MaxQueryBytes = 64 << 10
const MaxNestingDepth = 128
const MaxSuggestionInputBytes = 128
const MaxDiagnostics = 25
+const MaxCTEProjectedFields = 16 << 10
var ErrQueryTooLarge = errors.New("query exceeds maximum size")
var ErrQueryTooDeep = errors.New("query exceeds maximum nesting depth")
+var ErrCTEProjectionTooLarge = errors.New("query expands too many CTE fields; select fewer fields in each CTE")
func Validate(query string) error {
if len(query) > MaxQueryBytes {
diff --git a/services/hogql-language-service/internal/validation/validation.go b/services/hogql-language-service/internal/validation/validation.go
index 1f80bed62f76..2b82889604e3 100644
--- a/services/hogql-language-service/internal/validation/validation.go
+++ b/services/hogql-language-service/internal/validation/validation.go
@@ -38,12 +38,30 @@ type Result struct {
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_.$]*)`)
@@ -64,8 +82,9 @@ func Validate(schema *catalog.PreparedCatalog, query string) Result {
var diagnostics []Diagnostic
var referencedTableNames []string
seenTableNames := map[string]bool{}
+ budget := projectionBudget{remaining: querylimits.MaxCTEProjectedFields}
for _, statement := range statements {
- scopes := queryScopes(statement)
+ scopes := queryScopes(statement, &budget)
ignoredIdents := map[*clickhouse.Ident]bool{}
clickhouse.Walk(statement, func(node clickhouse.Expr) bool {
switch typed := node.(type) {
@@ -74,6 +93,14 @@ func Validate(schema *catalog.PreparedCatalog, query string) Result {
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
}
@@ -93,17 +120,14 @@ func Validate(schema *catalog.PreparedCatalog, query string) Result {
return true
}
binding := tableBinding{name: name, table: table}
- scope := innermostScope(scopes, start, end)
- if scope == nil {
- return true
- }
- scope.bindings[strings.ToLower(name)] = binding
- if alias != "" {
- scope.bindings[strings.ToLower(alias)] = binding
- }
+ addBinding(scope, name, alias, binding)
case *clickhouse.TableIdentifier:
ignoredIdents[typed.Database] = true
ignoredIdents[typed.Table] = true
+ case *clickhouse.CTEStmt:
+ if ident, ok := typed.Expr.(*clickhouse.Ident); ok {
+ ignoredIdents[ident] = true
+ }
case *clickhouse.FunctionExpr:
ignoredIdents[typed.Name] = true
case *clickhouse.IntervalExpr:
@@ -122,10 +146,19 @@ func Validate(schema *catalog.PreparedCatalog, query string) Result {
seen := map[string]bool{}
clickhouse.Walk(statement, func(node clickhouse.Expr) bool {
switch typed := node.(type) {
- case *clickhouse.Path:
- for _, field := range typed.Fields {
- ignoredIdents[field] = true
+ 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 {
+ ignoredIdents[typed.Ident] = true
+ if typed.DotIdent.Name != "*" {
+ validateField(&diagnostics, seen, binding, typed.DotIdent, &budget)
+ }
}
+ case *clickhouse.Path:
if len(typed.Fields) < 2 {
return true
}
@@ -142,32 +175,53 @@ func Validate(schema *catalog.PreparedCatalog, query string) Result {
bindingNames[name] = binding.name
}
if namespace, ok := propertyresolver.Resolve(parts, bindingNames); 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 {
- validateField(&diagnostics, seen, binding.table, typed.Fields[1])
+ for _, field := range typed.Fields {
+ ignoredIdents[field] = true
+ }
+ validateField(&diagnostics, seen, binding, typed.Fields[1], &budget)
+ } else {
+ for _, field := range typed.Fields[1:] {
+ ignoredIdents[field] = true
+ }
}
case *clickhouse.Ident:
- if ignoredIdents[typed] {
+ 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)
+ validateUnqualifiedField(&diagnostics, seen, bindings, typed, &budget)
}
}
return true
})
+ if budget.exceeded {
+ break
+ }
+ }
+ if budget.exceeded && len(diagnostics) < querylimits.MaxDiagnostics {
+ diagnostics = append(diagnostics, Diagnostic{
+ Code: "query_limit", Message: querylimits.ErrCTEProjectionTooLarge.Error(), Start: 0, End: len(query),
+ })
}
return result(diagnostics, referencedTableNames, started)
}
-func queryScopes(statement clickhouse.Expr) []*queryScope {
+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 {
- scopes = append(scopes, &queryScope{query: query, bindings: map[string]tableBinding{}})
+ scope := &queryScope{query: query, bindings: map[string]tableBinding{}}
+ scopes = append(scopes, scope)
+ byQuery[query] = scope
}
return true
})
@@ -181,9 +235,51 @@ func queryScopes(statement clickhouse.Expr) []*queryScope {
}
}
}
+ 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 {
@@ -210,6 +306,9 @@ func visibleBindings(scope *queryScope) map[string]tableBinding {
bindings[name] = binding
}
}
+ if current.cteRoot {
+ break
+ }
}
return bindings
}
@@ -271,11 +370,14 @@ func tableReference(expr *clickhouse.TableExpr) (name, alias string, start, end
return name, alias, int(identifier.Pos()), int(identifier.End()), true
}
-func validateField(diagnostics *[]Diagnostic, seen map[string]bool, table *catalog.PreparedTable, ident *clickhouse.Ident) {
- if len(*diagnostics) >= querylimits.MaxDiagnostics {
+func validateField(diagnostics *[]Diagnostic, seen map[string]bool, binding tableBinding, ident *clickhouse.Ident, budget *projectionBudget) {
+ if len(*diagnostics) >= querylimits.MaxDiagnostics || budget.exceeded {
+ return
+ }
+ if _, ok := bindingField(binding, ident.Name); ok {
return
}
- if hasField(table, ident.Name) {
+ if budget.exceeded {
return
}
key := fmt.Sprintf("%d:%d", ident.Pos(), ident.End())
@@ -285,24 +387,30 @@ func validateField(diagnostics *[]Diagnostic, seen map[string]bool, table *catal
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, table.Fields.Entries(), 5),
+ Suggestions: closest(ident.Name, bindingFields(binding), 5),
})
}
-func validateUnqualifiedField(diagnostics *[]Diagnostic, seen map[string]bool, bindings map[string]tableBinding, ident *clickhouse.Ident) {
- if len(*diagnostics) >= querylimits.MaxDiagnostics {
+func validateUnqualifiedField(diagnostics *[]Diagnostic, seen map[string]bool, bindings map[string]tableBinding, ident *clickhouse.Ident, budget *projectionBudget) {
+ if len(*diagnostics) >= querylimits.MaxDiagnostics || budget.exceeded {
return
}
- uniqueTables := map[string]*catalog.PreparedTable{}
+ uniqueTables := map[string]tableBinding{}
for _, binding := range bindings {
- uniqueTables[binding.name] = binding.table
- if hasField(binding.table, ident.Name) {
+ uniqueTables[binding.name] = binding
+ if _, ok := bindingField(binding, ident.Name); ok {
+ return
+ }
+ if budget.exceeded {
return
}
}
candidates := make([]catalog.Entry, 0)
- for _, table := range uniqueTables {
- candidates = append(candidates, table.Fields.Entries()...)
+ for _, binding := range uniqueTables {
+ candidates = append(candidates, bindingFields(binding)...)
+ if budget.exceeded {
+ return
+ }
}
key := fmt.Sprintf("%d:%d", ident.Pos(), ident.End())
if seen[key] {
@@ -315,9 +423,140 @@ func validateUnqualifiedField(diagnostics *[]Diagnostic, seen map[string]bool, b
})
}
-func hasField(table *catalog.PreparedTable, name string) bool {
- _, ok := table.Fields.Exact(name)
- return ok
+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 {
diff --git a/services/hogql-language-service/internal/validation/validation_test.go b/services/hogql-language-service/internal/validation/validation_test.go
index fc4287a06b95..73c4f1069272 100644
--- a/services/hogql-language-service/internal/validation/validation_test.go
+++ b/services/hogql-language-service/internal/validation/validation_test.go
@@ -1,6 +1,7 @@
package validation
import (
+ "fmt"
"strings"
"testing"
@@ -129,6 +130,104 @@ func TestValidateAcceptsHogQLQualifiedTable(t *testing.T) {
}
}
+func TestValidateCommonTableExpressions(t *testing.T) {
+ tests := []struct {
+ name string
+ query string
+ tableNames []string
+ }{
+ {
+ name: "basic",
+ query: "WITH x AS (SELECT event FROM events) SELECT * FROM x",
+ tableNames: []string{"events"},
+ },
+ {
+ name: "projected alias",
+ query: "WITH x AS (SELECT event AS kind FROM events) SELECT x.kind FROM x",
+ tableNames: []string{"events"},
+ },
+ {
+ name: "wildcard projection",
+ query: "WITH x AS (SELECT * FROM events) SELECT x.uuid FROM x",
+ tableNames: []string{"events"},
+ },
+ {
+ name: "qualified wildcard projection",
+ query: "WITH x AS (SELECT e.* FROM events AS e) SELECT x.uuid FROM x",
+ tableNames: []string{"events"},
+ },
+ {
+ name: "chained",
+ query: "WITH x AS (SELECT event AS kind FROM events), y AS (SELECT kind FROM x) SELECT y.kind FROM y",
+ tableNames: []string{"events"},
+ },
+ {
+ name: "shadows physical table",
+ query: "WITH events AS (SELECT person_id FROM warehouse_people) SELECT events.person_id FROM events",
+ tableNames: []string{"warehouse_people"},
+ },
+ {
+ name: "definition does not reference itself",
+ query: "WITH events AS (SELECT event FROM events) SELECT events.event FROM events",
+ tableNames: []string{"events"},
+ },
+ {
+ name: "nested definition shadows outer definition",
+ query: "WITH x AS (SELECT event AS outer_field FROM events), y AS (WITH x AS (SELECT person_id AS inner_field FROM warehouse_people) SELECT inner_field FROM x) SELECT y.inner_field FROM y",
+ tableNames: []string{"events", "warehouse_people"},
+ },
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ result := Validate(schema(), test.query)
+ if !result.Valid || len(result.Diagnostics) != 0 {
+ t.Fatalf("result = %#v", result)
+ }
+ if strings.Join(result.TableNames, ",") != strings.Join(test.tableNames, ",") {
+ t.Fatalf("table names = %#v", result.TableNames)
+ }
+ })
+ }
+}
+
+func TestValidateRejectsUnknownCommonTableExpressionField(t *testing.T) {
+ result := Validate(schema(), "WITH x AS (SELECT event AS kind FROM events) SELECT x.timestamp FROM x")
+ if result.Valid || len(result.Diagnostics) != 1 || result.Diagnostics[0].Code != "unknown_field" {
+ t.Fatalf("result = %#v", result)
+ }
+ if len(result.TableNames) != 1 || result.TableNames[0] != "events" {
+ t.Fatalf("table names = %#v", result.TableNames)
+ }
+}
+
+func TestValidateRejectsUnknownQualifiedFields(t *testing.T) {
+ for _, query := range []string{
+ "SELECT missing.event FROM events",
+ "SELECT missing.properties.value FROM events",
+ "SELECT missing.* FROM events",
+ } {
+ result := Validate(schema(), query)
+ if result.Valid || len(result.Diagnostics) != 1 || result.Diagnostics[0].Code != "unknown_field" {
+ t.Fatalf("query %q returned %#v", query, result)
+ }
+ }
+}
+
+func TestValidateBoundsCommonTableExpressionProjectionExpansion(t *testing.T) {
+ ctes := []string{"c0 AS (SELECT * FROM events)"}
+ for index := 1; index < 14; index++ {
+ ctes = append(ctes, fmt.Sprintf(
+ "c%d AS (SELECT left_side.*, right_side.* FROM c%d AS left_side JOIN c%d AS right_side ON 1 = 1)",
+ 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)
+ }
+}
+
func TestValidatePropertiesAcrossGenericNamespaces(t *testing.T) {
tests := []struct {
query string