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.

feat(hogql): complete cte and subquery projected fields (#101638)

Paweł Szczura914374b2b39
diff --git a/docs/internal/hogql-language-service.md b/docs/internal/hogql-language-service.md
index 1306f12e4b71..a756abcca52a 100644
--- a/docs/internal/hogql-language-service.md
+++ b/docs/internal/hogql-language-service.md
@@ -34,15 +34,34 @@ authenticated internal request.
## Query analysis
-`internal/analysis` owns validation's parsed statements, nested scopes, table and CTE bindings, and projected fields.
+`internal/analysis` owns parsed statements, nested scopes, table and CTE bindings, and projected fields for validation and completion.
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.
+Statements initialize on demand, while CTE and aliased subquery 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.
+Completion replaces the identifier at the cursor with a placeholder and resolves the containing scope.
+CTE and aliased `FROM` subquery suggestions contain their projected output names, including aliases and wildcard expansion.
+Direct field projections retain catalog types; expression types remain unknown.
+Qualified CTE completion also works before `FROM`, for example `WITH t AS (SELECT event FROM events) SELECT t.`.
+Inner bindings take precedence, and sibling queries and statements do not contribute suggestions.
+Validation checks aliased subquery output fields and continues to report only underlying catalog tables in `tableNames`.
+
+Physical field completion borrows the catalog prefix index.
+Derived projections have a shared limit of 16,384 fields before deduplication.
+Field resolution also has a request-wide budget of 1,048,576 work units, counting relation visits and identifier bytes used for lookups and derived-field indexes.
+Aliases of the same relation share a cached field index and one candidate entry for unqualified type resolution.
+Completion returns HTTP 400 when either limit is exceeded; validation returns a `query_limit` diagnostic.
+Derived qualified suggestions are sorted and deduplicated before pagination.
+
+### Recovery and remaining work
+
+- Cursor replacement must produce parseable SQL to resolve CTE and subquery fields. Recovery for missing parentheses or incomplete predicates in multi-scope queries remains follow-up work.
+- For an incomplete single `SELECT` without `WITH`, completion can recover a parseable `FROM` clause before an unfinished predicate. The response retains `parseError`. Recovery never overlays parsed bindings or scans aliases from sibling scopes.
+- Property provenance through derived projections is not available. Completion suppresses property suggestions for derived owners, including CTEs that shadow built-in names such as `events`. Unqualified physical properties remain available when joined derived relations do not project `properties`; a derived `properties` field makes the namespace ambiguous. Add provenance before enabling those ambiguous suggestions.
+- Select-alias visibility within the same query remains a separate layer. A projected alias is available to consumers of a CTE or subquery, not automatically to its defining query.
+- Table-name suggestions still use the catalog; adding visible CTE names to `FROM` and `JOIN` suggestions remains follow-up work.
+- Unaliased `FROM` subquery outputs, completion inside quoted identifiers, expression type inference, and complete set-operation semantics remain follow-up work.
+- Recursive CTEs, lateral subqueries, and full HogQL compiler parity are outside this layer. The service does not execute queries or fetch metadata during analysis.
## Isolation boundary
diff --git a/services/hogql-language-service/README.md b/services/hogql-language-service/README.md
index 45ba67abfa65..b2db30afdd92 100644
--- a/services/hogql-language-service/README.md
+++ b/services/hogql-language-service/README.md
@@ -30,10 +30,16 @@ 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.
+Completion and validation share scope analysis for table CTEs and aliased `FROM` subqueries.
+Completion suggests projected fields, including aliases and wildcard outputs, with catalog types for direct field projections.
+For example, `WITH t AS (SELECT event AS kind FROM events) SELECT t.` suggests `kind`, even before typing `FROM t`.
+Validation checks those output fields and reports only underlying catalog tables in `tableNames`.
+Each request can expand up to 16,384 projected fields before deduplication.
+Larger projections return HTTP 400 for completion or a `query_limit` validation diagnostic.
+Select fewer fields to stay within the limit.
+Field lookup work has a separate request-wide budget.
+Queries that exceed it return HTTP 400 for completion or a `query_limit` validation diagnostic; reduce the number of sources or qualify field names.
+Joining a CTE or subquery without a `properties` output does not suppress the physical table's property suggestions or validation.
Validation diagnostic offsets use `positionEncoding`, which defaults to UTF-16. Diagnostics include up to five visible
typo suggestions ranked by case-insensitive Levenshtein distance. Dynamic properties use the same cached namespaces as
@@ -60,8 +66,10 @@ suggestions, the total match count, and an opaque `nextCursor` when another page
position with `"cursor":"<nextCursor>"` to retrieve it. The HTTP `Content-Length` is the encoded response size.
The parser currently accepts ClickHouse's `database.table` identifiers but not HogQL's three-part synced-table names.
-Completion retains the parser error for diagnostics and uses a catalog-aware table-reference fallback for those names.
-Validation normalizes those table references before parsing while preserving byte offsets.
+Shared analysis normalizes those table references before parsing while preserving byte offsets.
+For incomplete SQL, completion can recover a single query's `FROM` clause and keeps the parser error in `parseError`.
+It does not recover bindings from malformed CTEs or nested queries.
+Derived-property provenance, select-alias visibility, and other exclusions are tracked in [query analysis and remaining work](../../docs/internal/hogql-language-service.md#recovery-and-remaining-work).
## Multitenant catalogs
diff --git a/services/hogql-language-service/internal/analysis/document.go b/services/hogql-language-service/internal/analysis/document.go
index 60160065929a..bb781987d225 100644
--- a/services/hogql-language-service/internal/analysis/document.go
+++ b/services/hogql-language-service/internal/analysis/document.go
@@ -3,6 +3,7 @@ package analysis
import (
"iter"
"slices"
+ "sort"
"strings"
clickhouse "github.com/orian/clickhouse-sql-parser/parser"
@@ -36,6 +37,8 @@ type TableReference struct {
type Bindings struct {
relations map[string]Relation
+ scope *queryScope
+ position int
}
func Analyze(schema *catalog.PreparedCatalog, query string) (*Document, error) {
@@ -47,7 +50,9 @@ func Analyze(schema *catalog.PreparedCatalog, query string) (*Document, error) {
if err != nil {
return nil, err
}
- document := &Document{budget: projectionBudget{remaining: querylimits.MaxCTEProjectedFields}}
+ document := &Document{budget: projectionBudget{
+ remaining: querylimits.MaxCTEProjectedFields, lookupRemaining: querylimits.MaxFieldLookupWork,
+ }}
for _, expr := range statements {
document.statements = append(document.statements, &Statement{
expr: expr, schema: schema, originalTableNames: originalTableNames, budget: &document.budget,
@@ -68,8 +73,14 @@ func (d *Document) Statements() iter.Seq[*Statement] {
}
}
-func (d *Document) ProjectionLimitExceeded() bool {
- return d.budget.exceeded
+func (d *Document) LimitError() error {
+ if d.budget.exceeded {
+ return querylimits.ErrCTEProjectionTooLarge
+ }
+ if d.budget.lookupExceeded {
+ return querylimits.ErrFieldLookupTooLarge
+ }
+ return nil
}
func (s *Statement) analyze() {
@@ -83,6 +94,9 @@ func (s *Statement) analyze() {
if !ok {
return true
}
+ if bindSubquery(expr, s.scopes, s.budget) {
+ return true
+ }
name, alias, start, end, ok := tableReference(expr)
if !ok {
return true
@@ -116,6 +130,10 @@ func (s *Statement) Tables() iter.Seq[TableReference] {
return slices.Values(s.tables)
}
+func (s *Statement) ContainsPosition(position int) bool {
+ return int(s.expr.Pos()) <= position && position <= int(s.expr.End())
+}
+
func (s *Statement) BindingsAt(start, end int) Bindings {
scope := innermostScope(s.scopes, start, end)
if scope == nil {
@@ -124,7 +142,18 @@ func (s *Statement) BindingsAt(start, end int) Bindings {
if scope.visible == nil {
scope.visible = visibleBindings(scope)
}
- return Bindings{relations: scope.visible}
+ return Bindings{relations: scope.visible, scope: scope, position: start}
+}
+
+// Qualified completion can refer to a visible CTE before the user has typed FROM.
+func (s *Statement) RelationAt(name string, position int) (Relation, bool) {
+ if relation, ok := s.BindingsAt(position, position).Relation(name); ok {
+ return relation, true
+ }
+ if cte := resolveCTE(innermostScope(s.scopes, position, position), name, position); cte != nil {
+ return Relation{name: cte.name, cte: cte}, true
+ }
+ return Relation{}, false
}
func (b Bindings) Len() int {
@@ -146,9 +175,32 @@ func (b Bindings) All() iter.Seq2[string, Relation] {
}
}
+func (b Bindings) UniqueRelations() iter.Seq[Relation] {
+ if b.scope == nil {
+ return slices.Values([]Relation(nil))
+ }
+ return slices.Values(b.scope.uniqueBindings())
+}
+
func (b Bindings) PropertyNamespace(parts []string) (string, bool) {
+ if len(parts) > 2 {
+ if _, bound := b.Relation(parts[0]); !bound && resolveCTE(b.scope, parts[0], b.position) != nil {
+ return "", false
+ }
+ }
names := make(map[string]string, len(b.relations))
for name, relation := range b.relations {
+ if relation.cte != nil {
+ if len(parts) > 2 && strings.EqualFold(parts[0], name) {
+ return "", false
+ }
+ if len(parts) == 2 {
+ if _, hasProperties := relation.Field("properties"); hasProperties || relation.cte.budget.exceeded || relation.cte.budget.lookupExceeded {
+ return "", false
+ }
+ }
+ continue
+ }
names[name] = relation.name
}
return propertyresolver.Resolve(parts, names)
@@ -166,3 +218,21 @@ func (r Relation) Field(name string) (catalog.Entry, bool) {
func (r Relation) Fields() iter.Seq[catalog.Entry] {
return slices.Values(bindingFields(r))
}
+
+// Physical prefixes borrow the catalog index; derived projections have a request-wide size bound.
+func (r Relation) Prefix(prefix string) iter.Seq[catalog.Entry] {
+ if r.table != nil {
+ return slices.Values(r.table.Fields.Prefix(prefix))
+ }
+ var fields []catalog.Entry
+ seen := map[string]bool{}
+ for field := range r.Fields() {
+ name := strings.ToLower(field.Name)
+ if strings.HasPrefix(name, prefix) && !seen[name] {
+ fields = append(fields, field)
+ seen[name] = true
+ }
+ }
+ sort.Slice(fields, func(i, j int) bool { return strings.ToLower(fields[i].Name) < strings.ToLower(fields[j].Name) })
+ return slices.Values(fields)
+}
diff --git a/services/hogql-language-service/internal/analysis/scopes.go b/services/hogql-language-service/internal/analysis/scopes.go
index e4998d60a9e0..2de1e6cab09a 100644
--- a/services/hogql-language-service/internal/analysis/scopes.go
+++ b/services/hogql-language-service/internal/analysis/scopes.go
@@ -3,6 +3,7 @@ package analysis
import (
"regexp"
"strings"
+ "unicode"
clickhouse "github.com/orian/clickhouse-sql-parser/parser"
@@ -21,13 +22,16 @@ type cteBinding struct {
scope *queryScope
budget *projectionBudget
fields []catalog.Entry
+ fieldIndex map[string]catalog.Entry
fieldsDone bool
resolving bool
}
type projectionBudget struct {
- remaining int
- exceeded bool
+ remaining int
+ exceeded bool
+ lookupRemaining int
+ lookupExceeded bool
}
type queryScope struct {
@@ -35,6 +39,8 @@ type queryScope struct {
parent *queryScope
bindings map[string]Relation
visible map[string]Relation
+ unique []Relation
+ budget *projectionBudget
ctes []*cteBinding
cteRoot bool
}
@@ -46,7 +52,7 @@ func queryScopes(statement clickhouse.Expr, budget *projectionBudget) []*querySc
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{}}
+ scope := &queryScope{query: query, bindings: map[string]Relation{}, budget: budget}
scopes = append(scopes, scope)
byQuery[query] = scope
}
@@ -126,6 +132,9 @@ func span(query *clickhouse.SelectQuery) int {
}
func visibleBindings(scope *queryScope) map[string]Relation {
+ if scope.visible != nil {
+ return scope.visible
+ }
bindings := map[string]Relation{}
for current := scope; current != nil; current = current.parent {
for name, binding := range current.bindings {
@@ -137,9 +146,28 @@ func visibleBindings(scope *queryScope) map[string]Relation {
break
}
}
+ scope.visible = bindings
return bindings
}
+func (s *queryScope) uniqueBindings() []Relation {
+ if s.unique != nil {
+ return s.unique
+ }
+ s.unique = make([]Relation, 0)
+ seen := map[Relation]bool{}
+ for _, relation := range visibleBindings(s) {
+ if !s.budget.lookup(1) {
+ return nil
+ }
+ if !seen[relation] {
+ seen[relation] = true
+ s.unique = append(s.unique, relation)
+ }
+ }
+ return s.unique
+}
+
func normalizeHogQLTableReferences(query string) (string, map[string]string) {
normalized := []byte(query)
originalNames := map[string]string{}
@@ -179,16 +207,67 @@ func tableReference(expr *clickhouse.TableExpr) (name, alias string, start, end
return name, alias, int(identifier.Pos()), int(identifier.End()), true
}
+func bindSubquery(expr *clickhouse.TableExpr, scopes []*queryScope, budget *projectionBudget) bool {
+ node := expr.Expr
+ var alias string
+ if aliased, ok := node.(*clickhouse.AliasExpr); ok {
+ node = aliased.Expr
+ if ident, ok := aliased.Alias.(*clickhouse.Ident); ok {
+ alias = ident.Name
+ }
+ }
+ subquery, ok := node.(*clickhouse.SubQuery)
+ if !ok {
+ return false
+ }
+ inner := innermostScope(scopes, int(subquery.Select.Pos()), int(subquery.Select.End()))
+ if inner != nil && inner.parent != nil {
+ // FROM subqueries do not inherit the containing query's table bindings.
+ inner.cteRoot = true
+ if alias != "" {
+ derived := &cteBinding{name: alias, query: subquery.Select, scope: inner, budget: budget}
+ addBinding(inner.parent, alias, "", Relation{name: alias, cte: derived})
+ }
+ }
+ return true
+}
+
+func foldedFieldName(name string) string {
+ return strings.Map(func(r rune) rune {
+ first := r
+ for next := unicode.SimpleFold(r); next != r; next = unicode.SimpleFold(next) {
+ first = min(first, next)
+ }
+ return first
+ }, name)
+}
+
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
+ if binding.cte == nil {
+ return catalog.Entry{}, false
+ }
+ c := binding.cte
+ fields := c.projectedFields()
+ if !c.fieldsDone || !c.budget.lookup(len(name)+1) {
+ return catalog.Entry{}, false
+ }
+ if c.fieldIndex == nil {
+ c.fieldIndex = make(map[string]catalog.Entry, len(fields))
+ for _, field := range fields {
+ if !c.budget.lookup(len(field.Name) + 1) {
+ return catalog.Entry{}, false
+ }
+ key := foldedFieldName(field.Name)
+ if _, exists := c.fieldIndex[key]; !exists {
+ c.fieldIndex[key] = field
+ }
}
}
- return catalog.Entry{}, false
+ field, ok := c.fieldIndex[foldedFieldName(name)]
+ return field, ok
}
func bindingFields(binding Relation) []catalog.Entry {
@@ -202,14 +281,14 @@ func bindingFields(binding Relation) []catalog.Entry {
}
func (c *cteBinding) projectedFields() []catalog.Entry {
- if c.fieldsDone || c.resolving || c.scope == nil || c.budget.exceeded {
+ if c.fieldsDone || c.resolving || c.scope == nil || c.budget.exceeded || c.budget.lookupExceeded {
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 {
+ if c.budget.exceeded || c.budget.lookupExceeded {
break
}
continue
@@ -236,7 +315,7 @@ func (c *cteBinding) projectedFields() []catalog.Entry {
default:
c.appendField(catalog.Entry{Name: item.Expr.String()})
}
- if c.budget.exceeded {
+ if c.budget.exceeded || c.budget.lookupExceeded {
break
}
}
@@ -276,6 +355,9 @@ func (c *cteBinding) appendWildcardFields(scope *queryScope, qualifier string) {
}
func (b *projectionBudget) take(count int) int {
+ if b.lookupExceeded || b.exceeded {
+ return 0
+ }
if count <= b.remaining {
b.remaining -= count
return count
@@ -286,11 +368,27 @@ func (b *projectionBudget) take(count int) int {
return taken
}
+// Count names as bytes so long identifiers cannot hide expensive work behind one lookup.
+func (b *projectionBudget) lookup(work int) bool {
+ if b.exceeded || b.lookupExceeded {
+ return false
+ }
+ if work > b.lookupRemaining {
+ b.lookupExceeded = true
+ return false
+ }
+ b.lookupRemaining -= work
+ return true
+}
+
func projectedType(scope *queryScope, expr clickhouse.Expr) string {
bindings := visibleBindings(scope)
switch typed := expr.(type) {
case *clickhouse.Ident:
- for _, binding := range bindings {
+ for _, binding := range scope.uniqueBindings() {
+ if !scope.budget.lookup(len(typed.Name) + 1) {
+ return ""
+ }
if field, ok := bindingField(binding, typed.Name); ok {
return field.Type
}
diff --git a/services/hogql-language-service/internal/completion/bindings.go b/services/hogql-language-service/internal/completion/bindings.go
new file mode 100644
index 000000000000..a27743aa5912
--- /dev/null
+++ b/services/hogql-language-service/internal/completion/bindings.go
@@ -0,0 +1,76 @@
+package completion
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/PostHog/posthog/services/hogql-language-service/internal/analysis"
+ "github.com/PostHog/posthog/services/hogql-language-service/internal/catalog"
+)
+
+func cursorBindings(schema *catalog.PreparedCatalog, query string, position int, qualifier string) (*analysis.Document, analysis.Bindings, analysis.Relation, error) {
+ document, parseErr := analysis.Analyze(schema, query)
+ if parseErr != nil {
+ parseErr = fmt.Errorf("parse incomplete SQL: %w", parseErr)
+ if recovered := recoverSingleSelect(query); recovered != "" {
+ document, _ = analysis.Analyze(schema, recovered)
+ position = len("SELECT ")
+ }
+ }
+ if document != nil {
+ for statement := range document.Statements() {
+ if statement.ContainsPosition(position) {
+ bindings := statement.BindingsAt(position, position)
+ relation, _ := statement.RelationAt(qualifier, position)
+ return document, bindings, relation, parseErr
+ }
+ }
+ }
+ return document, analysis.Bindings{}, analysis.Relation{}, parseErr
+}
+
+// Incomplete predicates can retain a parsed FROM clause only when no other query scope exists.
+func recoverSingleSelect(query string) string {
+ tokens, _, incomplete := scanSQLTokens(query)
+ if incomplete {
+ return ""
+ }
+ selects := 0
+ from := -1
+ end := len(tokens)
+ for index, token := range tokens {
+ if token.text == ";" || token.text == "WITH" {
+ return ""
+ }
+ if token.kind != sqlTokenWord {
+ continue
+ }
+ if token.text == "SELECT" {
+ selects++
+ if token.depth != 0 || selects > 1 {
+ return ""
+ }
+ }
+ if token.depth == 0 {
+ if token.text == "FROM" && from == -1 {
+ from = index
+ }
+ switch token.text {
+ case "WHERE", "PREWHERE", "GROUP", "ORDER", "HAVING", "LIMIT", "SETTINGS":
+ if from >= 0 && end == len(tokens) {
+ end = index
+ }
+ }
+ }
+ }
+ if selects != 1 || from < 0 {
+ return ""
+ }
+ var recovered strings.Builder
+ recovered.WriteString("SELECT * ")
+ for _, token := range tokens[from:end] {
+ recovered.WriteString(token.text)
+ recovered.WriteByte(' ')
+ }
+ return recovered.String()
+}
diff --git a/services/hogql-language-service/internal/completion/completion.go b/services/hogql-language-service/internal/completion/completion.go
index 1c5f3ed77240..4feddfb9159c 100644
--- a/services/hogql-language-service/internal/completion/completion.go
+++ b/services/hogql-language-service/internal/completion/completion.go
@@ -3,16 +3,17 @@ package completion
import (
"encoding/base64"
"fmt"
+ "iter"
"regexp"
+ "slices"
"sort"
"strconv"
"strings"
"unicode"
+ "unicode/utf8"
- 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"
)
@@ -46,7 +47,6 @@ var betweenSeparator = []string{"AND"}
var predicateContinuations = []string{"AND", "OR", "GROUP BY", "ORDER BY", "LIMIT"}
var comparisonOperators = []string{"=", "!=", "<", "<=", ">", ">=", "LIKE", "ILIKE", "IN", "NOT IN", "IS NULL", "IS NOT NULL", "BETWEEN", "NOT BETWEEN"}
var commonFunctions = []string{"avg", "coalesce", "count", "countDistinct", "countIf", "if", "max", "min", "now", "sum", "sumIf", "toDate", "toDateTime", "uniq", "uniqExact"}
-var tableReference = regexp.MustCompile(`(?i)\b(?:FROM|JOIN)\s+([A-Za-z_][A-Za-z0-9_.$]*)(?:\s+(?:AS\s+)?([A-Za-z_][A-Za-z0-9_]*))?`)
var simpleHogQLIdentifier = regexp.MustCompile(`^[A-Za-z_$][A-Za-z0-9_$]*$`)
var hogQLKeywords = map[string]struct{}{
"ALL": {}, "AND": {}, "ANTI": {}, "ANY": {}, "ARRAY": {}, "AS": {}, "ASC": {}, "ASCENDING": {}, "ASOF": {},
@@ -102,28 +102,23 @@ func Complete(schema *catalog.PreparedCatalog, query string, position int, posit
return Result{Suggestions: []Suggestion{}}, nil
}
repaired := query[:start] + "__posthog_cursor__" + query[position:]
- bindings, parseErr := tableBindings(repaired)
- for binding, tableName := range bindings {
- if table, ok := schema.Table(tableName); ok {
- bindings[binding] = table.Name
- }
- }
- for binding, tableName := range fallbackBindings(repaired, schema) {
- bindings[binding] = tableName
- }
+ document, bindings, qualified, parseErr := cursorBindings(schema, repaired, start, qualifier)
var suggestions []Suggestion
- if namespace, propertyPrefix, ok := propertyContext(query[:position], bindings); ok {
- return indexedResult(schema.Properties(namespace).Prefix(propertyPrefix), "property", offset, parseErr), nil
+ namespace, propertyPrefix, propertyOK := propertyContext(query[:position], bindings)
+ if document != nil && document.LimitError() != nil {
+ return Result{}, document.LimitError()
+ }
+ if propertyOK {
+ return indexedResult(slices.Values(schema.Properties(namespace).Prefix(propertyPrefix)), "property", offset, parseErr), nil
} else if qualifier != "" {
- if tableName, ok := bindings[strings.ToLower(qualifier)]; ok {
- if table, exists := schema.Table(tableName); exists {
- return indexedResult(table.Fields.Prefix(lowerPrefix), "field", offset, parseErr), nil
- }
+ entries := qualified.Prefix(lowerPrefix)
+ if document != nil && document.LimitError() != nil {
+ return Result{}, document.LimitError()
}
- return indexedResult(nil, "field", offset, parseErr), nil
+ return indexedResult(entries, "field", offset, parseErr), nil
} else if mode == completionModeTable {
- return indexedResult(schema.Tables().Prefix(lowerPrefix), "table", offset, parseErr), nil
+ return indexedResult(slices.Values(schema.Tables().Prefix(lowerPrefix)), "table", offset, parseErr), nil
} else if mode == completionModeComparison {
suggestions = appendNamed(suggestions, comparisonOperators, lowerPrefix, "operator", "")
} else if mode == completionModeBetweenSeparator {
@@ -134,15 +129,16 @@ func Complete(schema *catalog.PreparedCatalog, query string, position int, posit
suggestions = appendNamed(suggestions, comparisonOperators, lowerPrefix, "operator", "")
suggestions = appendNamed(suggestions, predicateContinuations, lowerPrefix, "keyword", "")
} else {
- seen := map[string]bool{}
- for _, tableName := range bindings {
- if seen[tableName] {
+ seen := map[analysis.Relation]bool{}
+ for _, relation := range bindings.All() {
+ if seen[relation] {
continue
}
- seen[tableName] = true
- if table, ok := schema.Table(tableName); ok {
- suggestions = appendFields(suggestions, table, lowerPrefix)
- }
+ seen[relation] = true
+ suggestions = appendFields(suggestions, relation.Prefix(lowerPrefix))
+ }
+ if document != nil && document.LimitError() != nil {
+ return Result{}, document.LimitError()
}
if mode == completionModeExpression {
suggestions = appendFunctions(suggestions, lowerPrefix)
@@ -179,10 +175,10 @@ func Complete(schema *catalog.PreparedCatalog, query string, position int, posit
return result, nil
}
-func indexedResult(entries []catalog.Entry, kind string, offset int, parseErr error) Result {
- result := Result{Suggestions: make([]Suggestion, 0, min(PageSize, len(entries)))}
+func indexedResult(entries iter.Seq[catalog.Entry], kind string, offset int, parseErr error) Result {
+ result := Result{Suggestions: make([]Suggestion, 0, PageSize)}
rank := strconv.Itoa(suggestionRank(kind)) + "-"
- for _, entry := range entries {
+ for entry := range entries {
if !supportedHogQLIdentifier(entry.Name) {
continue
}
@@ -208,20 +204,20 @@ func utf16OffsetToByteOffset(value string, offset int) int {
return byteOffset
}
-func propertyContext(input string, bindings map[string]string) (string, string, bool) {
+func propertyContext(input string, bindings analysis.Bindings) (string, string, bool) {
start := len(input)
for start > 0 {
- character := input[start-1]
- if character != '.' && character != '$' && !isIdentifier(rune(character)) {
+ character, size := utf8.DecodeLastRuneInString(input[:start])
+ if character != '.' && !isIdentifier(character) {
break
}
- start--
+ start -= size
}
parts := strings.Split(input[start:], ".")
if len(parts) < 2 {
return "", "", false
}
- namespace, ok := propertyresolver.Resolve(parts, bindings)
+ namespace, ok := bindings.PropertyNamespace(parts)
return namespace, parts[len(parts)-1], ok
}
@@ -244,25 +240,8 @@ func encodeCursor(offset int) string {
return base64.RawURLEncoding.EncodeToString([]byte(strconv.Itoa(offset)))
}
-// The ClickHouse grammar accepts database.table while HogQL warehouse names may have more segments.
-// Keep parser-derived bindings as the primary path and fill that syntax gap until the grammar supports it.
-func fallbackBindings(query string, schema *catalog.PreparedCatalog) map[string]string {
- bindings := map[string]string{}
- for _, match := range tableReference.FindAllStringSubmatch(query, -1) {
- table, ok := schema.Table(match[1])
- if !ok {
- continue
- }
- bindings[strings.ToLower(table.Name)] = table.Name
- if match[2] != "" && !strings.EqualFold(match[2], "FINAL") {
- bindings[strings.ToLower(match[2])] = table.Name
- }
- }
- return bindings
-}
-
-func appendFields(out []Suggestion, table *catalog.PreparedTable, lowerPrefix string) []Suggestion {
- for _, field := range table.Fields.Prefix(lowerPrefix) {
+func appendFields(out []Suggestion, fields iter.Seq[catalog.Entry]) []Suggestion {
+ for field := range fields {
if !supportedHogQLIdentifier(field.Name) {
continue
}
@@ -344,15 +323,23 @@ func suggestionRank(kind string) int {
func cursorWord(input string) (prefix, qualifier string, start int) {
start = len(input)
- for start > 0 && isIdentifier(rune(input[start-1])) {
- start--
+ for start > 0 {
+ character, size := utf8.DecodeLastRuneInString(input[:start])
+ if !isIdentifier(character) {
+ break
+ }
+ start -= size
}
prefix = input[start:]
if start > 0 && input[start-1] == '.' {
qualifierEnd := start - 1
qualifierStart := qualifierEnd
- for qualifierStart > 0 && isIdentifier(rune(input[qualifierStart-1])) {
- qualifierStart--
+ for qualifierStart > 0 {
+ character, size := utf8.DecodeLastRuneInString(input[:qualifierStart])
+ if !isIdentifier(character) {
+ break
+ }
+ qualifierStart -= size
}
qualifier = input[qualifierStart:qualifierEnd]
}
@@ -366,41 +353,3 @@ func isIdentifier(r rune) bool {
func hasLowerPrefix(value, lowerPrefix string) bool {
return strings.HasPrefix(strings.ToLower(value), lowerPrefix)
}
-
-func tableBindings(query string) (map[string]string, error) {
- statements, err := clickhouse.NewParser(query).ParseStmts()
- if err != nil {
- return map[string]string{}, fmt.Errorf("parse incomplete SQL: %w", err)
- }
- bindings := map[string]string{}
- for _, statement := range statements {
- clickhouse.Walk(statement, func(node clickhouse.Expr) bool {
- tableExpr, ok := node.(*clickhouse.TableExpr)
- if !ok {
- return true
- }
- tableNode := tableExpr.Expr
- var aliasName string
- if aliased, ok := tableNode.(*clickhouse.AliasExpr); ok {
- tableNode = aliased.Expr
- if alias, ok := aliased.Alias.(*clickhouse.Ident); ok {
- aliasName = alias.Name
- }
- }
- identifier, ok := tableNode.(*clickhouse.TableIdentifier)
- if !ok || identifier.Table == nil {
- return true
- }
- name := identifier.Table.Name
- if identifier.Database != nil {
- name = identifier.Database.Name + "." + name
- }
- bindings[strings.ToLower(name)] = name
- if aliasName != "" {
- bindings[strings.ToLower(aliasName)] = name
- }
- return false
- })
- }
- return bindings, nil
-}
diff --git a/services/hogql-language-service/internal/completion/completion_test.go b/services/hogql-language-service/internal/completion/completion_test.go
index e8b1a2288d26..77886370d097 100644
--- a/services/hogql-language-service/internal/completion/completion_test.go
+++ b/services/hogql-language-service/internal/completion/completion_test.go
@@ -2,6 +2,7 @@ package completion
import (
"encoding/json"
+ "errors"
"fmt"
"math"
"os"
@@ -10,10 +11,18 @@ import (
"time"
"github.com/PostHog/posthog/services/hogql-language-service/internal/catalog"
+ "github.com/PostHog/posthog/services/hogql-language-service/internal/querylimits"
)
func testCatalog() *catalog.PreparedCatalog {
return catalog.Prepare(&catalog.Catalog{Tables: map[string]catalog.Table{
+ "events": {Name: "events", Type: "posthog", Fields: map[string]catalog.Field{
+ "uuid": {Name: "uuid", Type: "string"}, "event": {Name: "event", Type: "string"},
+ "properties": {Name: "properties", Type: "json"},
+ }},
+ "persons": {Name: "persons", Type: "posthog", Fields: map[string]catalog.Field{
+ "id": {Name: "id", Type: "string"}, "properties": {Name: "properties", Type: "json"},
+ }},
"orders": {Name: "orders", Type: "data_warehouse", Fields: map[string]catalog.Field{
"order_id": {Name: "order_id", Type: "string"},
"amount": {Name: "amount", Type: "float"},
@@ -112,6 +121,174 @@ func TestCompletesFieldsForAlias(t *testing.T) {
}
}
+func TestCompletesScopedProjections(t *testing.T) {
+ for _, test := range []struct {
+ name, query string
+ fields map[string]string
+ }{
+ {"cte", "WITH t AS (SELECT order_id, amount AS total FROM orders) SELECT t.| FROM t", map[string]string{"order_id": "string", "total": "float"}},
+ {"before from", "WITH t AS (SELECT amount AS total FROM orders) SELECT t.|", map[string]string{"total": "float"}},
+ {"unqualified", "WITH t AS (SELECT amount AS total FROM orders) SELECT tot| FROM t", map[string]string{"total": "float"}},
+ {"chained", "WITH a AS (SELECT amount AS total FROM orders), b AS (SELECT * FROM a) SELECT b.| FROM b", map[string]string{"total": "float"}},
+ {"shadow catalog", "WITH orders AS (SELECT event FROM events) SELECT orders.| FROM orders", map[string]string{"event": "string"}},
+ {"nested shadow", "WITH t AS (SELECT amount FROM orders) SELECT * FROM (WITH t AS (SELECT event FROM events) SELECT t.| FROM t) AS s", map[string]string{"event": "string"}},
+ {"subquery", "SELECT s.| FROM (SELECT order_id, amount AS total FROM orders) AS s", map[string]string{"order_id": "string", "total": "float"}},
+ {"nested subquery", "SELECT s.| FROM (SELECT x.total FROM (SELECT amount AS total FROM orders) AS x) AS s", map[string]string{"total": "float"}},
+ {"warehouse", "WITH t AS (SELECT * FROM postgres.synced.orders) SELECT t.| FROM t", map[string]string{"synced_id": "string"}},
+ {"no sibling alias", "SELECT x.| FROM (SELECT amount FROM orders AS x) AS s", nil},
+ {"no sibling cte", "WITH t AS (SELECT amount FROM orders), u AS (SELECT x.| FROM events) SELECT * FROM orders AS x", nil},
+ {"no later cte", "WITH a AS (SELECT b.| FROM orders), b AS (SELECT event FROM events) SELECT * FROM a", nil},
+ {"no self cte", "WITH a AS (SELECT a.| FROM orders) SELECT * FROM a", nil},
+ {"no sibling statement", "SELECT * FROM orders AS x; SELECT x.| FROM events", nil},
+ {"no sibling union", "SELECT * FROM orders AS x UNION ALL SELECT x.| FROM events", nil},
+ {"malformed scopes", "WITH t AS (SELECT amount FROM orders AS x) SELECT x.| FROM (", nil},
+ {"malformed literal", "SELECT 'FROM orders AS x' WHERE x.| =", nil},
+ {"property shadow", "WITH events AS (SELECT amount AS properties FROM orders) SELECT events.properties.| FROM events", nil},
+ {"property shadow before from", "WITH events AS (SELECT amount AS properties FROM orders) SELECT events.properties.|", nil},
+ {"unrelated cte preserves properties", "WITH t AS (SELECT 1 AS x) SELECT properties.$geo_ci| FROM events JOIN t ON 1 = 1", map[string]string{"$geo_city": "String"}},
+ {"unrelated subquery preserves properties", "SELECT properties.$geo_ci| FROM events JOIN (SELECT 1 AS x) AS t ON 1 = 1", map[string]string{"$geo_city": "String"}},
+ {"renamed properties are unrelated", "WITH t AS (SELECT properties AS attrs FROM events) SELECT properties.$geo_ci| FROM events JOIN t ON 1 = 1", map[string]string{"$geo_city": "String"}},
+ {"derived properties are ambiguous", "WITH t AS (SELECT properties FROM events) SELECT properties.$geo_ci| FROM events JOIN t ON 1 = 1", nil},
+ {"qualified physical properties remain available", "WITH t AS (SELECT properties FROM events) SELECT e.properties.$geo_ci| FROM events AS e JOIN t ON 1 = 1", map[string]string{"$geo_city": "String"}},
+ {"derived body isolation", "SELECT * FROM orders AS x JOIN (SELECT x.| FROM events) AS s ON 1 = 1", nil},
+ {"joined derived sources", "WITH t AS (SELECT event FROM events) SELECT s.| FROM t JOIN (SELECT amount AS total FROM orders) AS s ON 1 = 1", map[string]string{"total": "float"}},
+ {"unicode prefix", "WITH t AS (SELECT amount AS `数額` FROM orders) SELECT t.数| FROM t", map[string]string{"数額": "float"}},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ position := strings.IndexByte(test.query, '|')
+ query := strings.Replace(test.query, "|", "", 1)
+ result, err := Complete(testCatalog(), query, position, PositionEncodingUTF8, "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ fields := map[string]string{}
+ for _, suggestion := range result.Suggestions {
+ if suggestion.Kind == "field" || suggestion.Kind == "property" {
+ fields[suggestion.Label] = suggestion.Detail
+ }
+ }
+ if len(fields) != len(test.fields) {
+ t.Fatalf("fields = %#v, want %#v; parse error = %s", fields, test.fields, result.ParseError)
+ }
+ for name, detail := range test.fields {
+ if actual, ok := fields[name]; !ok || actual != detail {
+ t.Errorf("field %q = %q (%t), want %q", name, actual, ok, detail)
+ }
+ }
+ })
+ }
+}
+
+func derivedLookupQuery(sources, aliases, fields, missing int) (string, int) {
+ items := make([]string, fields)
+ for index := range items {
+ items[index] = fmt.Sprintf("amount AS field_%03d", index)
+ }
+ ctes := []string{"c0 AS (SELECT " + strings.Join(items, ", ") + " FROM orders)"}
+ for index := 1; index < sources; index++ {
+ ctes = append(ctes, fmt.Sprintf("c%d AS (SELECT * FROM c0)", index))
+ }
+ from := "c0 AS a0"
+ for index := 1; index < aliases; index++ {
+ from += fmt.Sprintf(" JOIN c%d AS a%d ON 1 = 1", index%sources, index)
+ }
+ projections := strings.Repeat("unknown_identifier, ", missing) + "a0.field_000 AS known"
+ ctes = append(ctes, "result AS (SELECT "+projections+" FROM "+from+")")
+ prefix := "WITH " + strings.Join(ctes, ", ") + " SELECT result."
+ return prefix + " FROM result", len(prefix)
+}
+
+func TestDerivedLookupWork(t *testing.T) {
+ for _, test := range []struct {
+ name string
+ sources, aliases, fields, missing int
+ limit bool
+ }{
+ {name: "repeated aliases share one field index", sources: 1, aliases: 512, fields: 256, missing: 256},
+ {name: "distinct sources exhaust lookup budget", sources: 128, aliases: 128, fields: 8, missing: 512, limit: true},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ query, position := derivedLookupQuery(test.sources, test.aliases, test.fields, test.missing)
+ if err := querylimits.Validate(query); err != nil {
+ t.Fatal(err)
+ }
+ result, err := Complete(testCatalog(), query, position, PositionEncodingUTF8, "")
+ if test.limit {
+ if !errors.Is(err, querylimits.ErrFieldLookupTooLarge) || len(result.Suggestions) != 0 {
+ t.Fatalf("result = %#v, err = %v", result, err)
+ }
+ } else if known, ok := findSuggestion(result.Suggestions, "known"); err != nil || !ok || known.Detail != "float" {
+ t.Fatalf("result = %#v, err = %v", result, err)
+ }
+ })
+ }
+}
+
+func BenchmarkCompleteDerivedLookups(b *testing.B) {
+ query, position := derivedLookupQuery(1, 512, 256, 256)
+ schema := testCatalog()
+ b.ReportAllocs()
+ b.ResetTimer()
+ for range b.N {
+ if _, err := Complete(schema, query, position, PositionEncodingUTF8, ""); err != nil {
+ b.Fatal(err)
+ }
+ }
+}
+
+func TestDerivedProjectionPaginationAndLimits(t *testing.T) {
+ var items []string
+ for index := 0; index < PageSize+2; index++ {
+ items = append(items, fmt.Sprintf("amount AS field_%02d", index))
+ }
+ items = append(items, "amount AS field_00")
+ for _, source := range []string{
+ "WITH t AS (SELECT " + strings.Join(items, ", ") + " FROM orders) SELECT t.| FROM t",
+ "SELECT t.| FROM (SELECT " + strings.Join(items, ", ") + " FROM orders) AS t",
+ } {
+ position := strings.IndexByte(source, '|')
+ query := strings.Replace(source, "|", "", 1)
+ cursor := ""
+ var fields []string
+ for {
+ result, err := Complete(testCatalog(), query, position, PositionEncodingUTF8, cursor)
+ if err != nil || result.Total != PageSize+2 || len(result.Suggestions) > PageSize {
+ t.Fatalf("result = %#v, err = %v", result, err)
+ }
+ for _, suggestion := range result.Suggestions {
+ fields = append(fields, suggestion.Label)
+ }
+ cursor = result.NextCursor
+ if cursor == "" {
+ break
+ }
+ if len(fields) > PageSize+2 {
+ t.Fatal("pagination did not terminate")
+ }
+ }
+ if len(fields) != PageSize+2 {
+ t.Fatalf("fields = %#v", fields)
+ }
+ for index, name := range fields {
+ if name != fmt.Sprintf("field_%02d", index) {
+ t.Fatalf("fields = %#v", fields)
+ }
+ }
+ }
+
+ ctes := []string{"c0 AS (SELECT * FROM orders)"}
+ for index := 1; index < 15; index++ {
+ ctes = append(ctes, fmt.Sprintf("c%d AS (SELECT a.*, b.* FROM c%d AS a JOIN c%d AS b ON 1 = 1)", index, index-1, index-1))
+ }
+ for _, projection := range []string{"c14.", ""} {
+ prefix := "WITH " + strings.Join(ctes, ", ") + " SELECT " + projection
+ _, err := Complete(testCatalog(), prefix+" FROM c14", len(prefix), PositionEncodingUTF8, "")
+ if !errors.Is(err, querylimits.ErrCTEProjectionTooLarge) {
+ t.Fatalf("projection %q: err = %v", projection, err)
+ }
+ }
+}
+
func TestCompletionQuotesIdentifierInsertionText(t *testing.T) {
schema := catalog.Prepare(&catalog.Catalog{Tables: map[string]catalog.Table{
"from": {Name: "from", Type: "data_warehouse", Fields: map[string]catalog.Field{}},
diff --git a/services/hogql-language-service/internal/querylimits/limits.go b/services/hogql-language-service/internal/querylimits/limits.go
index d832e329de2c..8c2b1afc4425 100644
--- a/services/hogql-language-service/internal/querylimits/limits.go
+++ b/services/hogql-language-service/internal/querylimits/limits.go
@@ -7,10 +7,12 @@ const MaxNestingDepth = 128
const MaxSuggestionInputBytes = 128
const MaxDiagnostics = 25
const MaxCTEProjectedFields = 16 << 10
+const MaxFieldLookupWork = 1 << 20
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")
+var ErrFieldLookupTooLarge = errors.New("query requires too much field lookup work; use fewer sources or qualify field names")
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 5fae52e02209..738353d706c4 100644
--- a/services/hogql-language-service/internal/validation/validation.go
+++ b/services/hogql-language-service/internal/validation/validation.go
@@ -146,13 +146,13 @@ func Validate(schema *catalog.PreparedCatalog, query string) Result {
}
return true
})
- if document.ProjectionLimitExceeded() {
+ if document.LimitError() != nil {
break
}
}
- if document.ProjectionLimitExceeded() && len(diagnostics) < querylimits.MaxDiagnostics {
+ if err := document.LimitError(); err != nil && len(diagnostics) < querylimits.MaxDiagnostics {
diagnostics = append(diagnostics, Diagnostic{
- Code: "query_limit", Message: querylimits.ErrCTEProjectionTooLarge.Error(), Start: 0, End: len(query),
+ Code: "query_limit", Message: err.Error(), Start: 0, End: len(query),
})
}
return result(diagnostics, referencedTableNames, started)
@@ -197,13 +197,13 @@ func validateProperty(diagnostics *[]Diagnostic, seen map[string]bool, propertie
}
func validateField(diagnostics *[]Diagnostic, seen map[string]bool, binding analysis.Relation, ident *clickhouse.Ident, document *analysis.Document) {
- if len(*diagnostics) >= querylimits.MaxDiagnostics || document.ProjectionLimitExceeded() {
+ if len(*diagnostics) >= querylimits.MaxDiagnostics || document.LimitError() != nil {
return
}
if _, ok := binding.Field(ident.Name); ok {
return
}
- if document.ProjectionLimitExceeded() {
+ if document.LimitError() != nil {
return
}
key := fmt.Sprintf("%d:%d", ident.Pos(), ident.End())
@@ -218,23 +218,23 @@ func validateField(diagnostics *[]Diagnostic, seen map[string]bool, binding anal
}
func validateUnqualifiedField(diagnostics *[]Diagnostic, seen map[string]bool, bindings analysis.Bindings, ident *clickhouse.Ident, document *analysis.Document) {
- if len(*diagnostics) >= querylimits.MaxDiagnostics || document.ProjectionLimitExceeded() {
+ if len(*diagnostics) >= querylimits.MaxDiagnostics || document.LimitError() != nil {
return
}
uniqueTables := map[string]analysis.Relation{}
- for _, binding := range bindings.All() {
+ for binding := range bindings.UniqueRelations() {
uniqueTables[binding.Name()] = binding
if _, ok := binding.Field(ident.Name); ok {
return
}
- if document.ProjectionLimitExceeded() {
+ if document.LimitError() != nil {
return
}
}
candidates := make([]catalog.Entry, 0)
for _, binding := range uniqueTables {
candidates = slices.AppendSeq(candidates, binding.Fields())
- if document.ProjectionLimitExceeded() {
+ if document.LimitError() != nil {
return
}
}
diff --git a/services/hogql-language-service/internal/validation/validation_test.go b/services/hogql-language-service/internal/validation/validation_test.go
index 7b710ef7b728..acaf06b62830 100644
--- a/services/hogql-language-service/internal/validation/validation_test.go
+++ b/services/hogql-language-service/internal/validation/validation_test.go
@@ -6,6 +6,7 @@ import (
"testing"
"github.com/PostHog/posthog/services/hogql-language-service/internal/catalog"
+ "github.com/PostHog/posthog/services/hogql-language-service/internal/querylimits"
)
func schema() *catalog.PreparedCatalog {
@@ -112,6 +113,9 @@ func TestValidateAcceptsKnownFieldsAndFunctions(t *testing.T) {
{query: "SELECT uuid FROM events WHERE event = '$pageview' AND timestamp > now() - interval 1 month", tableName: "events"},
{query: "SELECT extract(month FROM timestamp) FROM events", tableName: "events"},
{query: "SELECT properties.$GEO_CITY FROM events", tableName: "events"},
+ {query: "SELECT s.kind FROM (SELECT event AS kind FROM events) AS s", tableName: "events"},
+ {query: "WITH t AS (SELECT event AS `Σ` FROM events) SELECT t.`ς` FROM t", tableName: "events"},
+ {query: "WITH t AS (SELECT event AS kind FROM events) SELECT s.kind FROM (SELECT * FROM t) AS s", tableName: "events"},
} {
result := Validate(schema(), test.query)
if !result.Valid || len(result.Diagnostics) != 0 {
@@ -192,12 +196,18 @@ func TestValidateCommonTableExpressions(t *testing.T) {
}
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)
+ for _, query := range []string{
+ "WITH x AS (SELECT event AS kind FROM events) SELECT x.timestamp FROM x",
+ "SELECT x.timestamp FROM (SELECT event AS kind FROM events) AS x",
+ "SELECT timestamp FROM (SELECT event AS kind FROM events) AS x",
+ } {
+ result := Validate(schema(), query)
+ if result.Valid || len(result.Diagnostics) != 1 || result.Diagnostics[0].Code != "unknown_field" {
+ t.Fatalf("query %q: result = %#v", query, result)
+ }
+ if len(result.TableNames) != 1 || result.TableNames[0] != "events" {
+ t.Fatalf("table names = %#v", result.TableNames)
+ }
}
}
@@ -246,6 +256,23 @@ func TestValidateBoundsCommonTableExpressionProjectionExpansion(t *testing.T) {
}
}
+func TestValidateBoundsFieldLookupWork(t *testing.T) {
+ ctes := make([]string, 128)
+ from := "c0"
+ for index := range ctes {
+ ctes[index] = fmt.Sprintf("c%d AS (SELECT event FROM events)", index)
+ if index > 0 {
+ from += fmt.Sprintf(" JOIN c%d ON 1 = 1", index)
+ }
+ }
+ ctes = append(ctes, "result AS (SELECT "+strings.Repeat("unknown", 1500)+", c0.event FROM "+from+")")
+ query := "WITH " + strings.Join(ctes, ", ") + " SELECT result.event FROM result"
+ result := Validate(schema(), query)
+ if result.Valid || len(result.Diagnostics) != 1 || result.Diagnostics[0].Code != "query_limit" || result.Diagnostics[0].Message != querylimits.ErrFieldLookupTooLarge.Error() {
+ t.Fatalf("result = %#v", result)
+ }
+}
+
func TestValidatePropertiesAcrossGenericNamespaces(t *testing.T) {
tests := []struct {
query string
@@ -256,6 +283,9 @@ func TestValidatePropertiesAcrossGenericNamespaces(t *testing.T) {
{query: "SELECT session.properties.$entry_curent_url FROM events", suggestion: "$entry_current_url"},
{query: "SELECT group_0.properties.indstry FROM events", suggestion: "industry"},
{query: "SELECT properties.cafe FROM events", suggestion: "café"},
+ {query: "WITH t AS (SELECT 1 AS x) SELECT properties.$geo_cty FROM events JOIN t ON 1 = 1", suggestion: "$geo_city"},
+ {query: "SELECT properties.$geo_cty FROM events JOIN (SELECT 1 AS x) AS t ON 1 = 1", suggestion: "$geo_city"},
+ {query: "WITH t AS (SELECT properties AS attrs FROM events) SELECT properties.$geo_cty FROM events JOIN t ON 1 = 1", suggestion: "$geo_city"},
}
for _, test := range tests {
result := Validate(schema(), test.query)