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): disambiguate joined field completions (#101948)

Paweł Szczur444fb0e2e7fb
diff --git a/docs/internal/hogql-language-service.md b/docs/internal/hogql-language-service.md
index 0f1d6f1e2e7b..88a09982bb52 100644
--- a/docs/internal/hogql-language-service.md
+++ b/docs/internal/hogql-language-service.md
@@ -52,19 +52,29 @@ FROM and JOIN completion includes visible table CTEs before catalog tables, with
CTE names follow the same scope, definition-order, and shadowing rules as relation lookup; scalar WITH aliases are not tables.
A visible CTE hides a catalog table with the same name, and pagination counts that name once.
CTE insertion quotes the whole name when needed, including names with dots.
+When visible sources expose the same field name, unqualified completion returns one suggestion per source.
+The label remains the field name, the detail includes its type and source, and insertion uses the qualified field, for example `e.uuid`.
+An explicit table alias identifies its source, including separate aliases in a self-join; the table name and its alias do not create duplicate suggestions.
+CTEs and aliased subqueries use the same rules, with identifier quoting for both the source and field.
+Completion leaves `timestamp` unquoted, including qualified references such as `e.timestamp`; other keyword names still use conservative quoting.
+Multi-part physical table paths use HogQL's implicit double-underscore alias, for example `postgres__synced__orders.synced_id`; an explicit alias takes precedence.
+Equal field labels have a deterministic source order across completion pages.
+Unqualified completion uses fixed-width global ranks for `sortText`, so client sorting preserves server order across pages even for labels containing punctuation.
+Unique fields and already-qualified completion retain their existing details and insertion text.
Select aliases follow the resolution order in `posthog/hogql/resolver.py` (`visit_select_query` and `visit_alias`).
An explicit alias becomes visible after its defining SELECT item, so later items can reference it.
WHERE, PREWHERE, GROUP BY, HAVING, ORDER BY, named WINDOW definitions, and LIMIT expressions can reference all SELECT aliases in their query.
FROM and JOIN expressions cannot reference them, and aliases do not cross nested queries, CTE definitions, UNION branches, or statements.
Alias lookup is case-sensitive, as in the Python resolver; completion prefix matching remains case-insensitive.
+An alias named `UUID` does not hide a source field named `uuid`; they can refer to different values.
An alias takes precedence over an unqualified field with the same name, while qualified field lookup still uses the relation.
Direct alias chains retain catalog types, and validation typo suggestions include visible aliases.
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.
-Select-alias indexing, lookup, and suggestion scans share that work budget.
+Select-alias indexing, source enumeration, lookup, and field suggestion scans share that work budget.
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.
@@ -78,7 +88,7 @@ Derived qualified suggestions are sorted and deduplicated before pagination.
- Property provenance through select aliases is not available. A visible alias that shadows a property owner suppresses its property suggestions and property-name validation. Track the alias expression's owner before enabling property traversal; qualified physical properties remain available.
- Scalar WITH aliases, aliases inside expressions, ARRAY JOIN aliases, QUALIFY, and duplicate-alias diagnostics remain follow-up work. Model their resolver order and parser support before extending the top-level SELECT alias index. For duplicate declarations, the index retains the first declaration; it does not establish that the query is valid.
- Validation skips field checks when a query has no known FROM bindings, including SELECT without FROM. Completion can still suggest its aliases. Add explicit empty-source scopes and distinguish unknown relations before enabling strict validation there.
-- Joined relations can still produce equal field labels with no source in the suggestion detail. Add relation provenance and qualification-aware insertion text before resolving that ambiguity. References to the same relation already share one suggestion set.
+- JOIN USING output coalescing and ambiguous unqualified-field diagnostics remain follow-up work. Completion offers each source's qualified field; it does not choose a join-wide value or change validation's ambiguity rules.
- CTE table-name suggestions require cursor replacement to produce parseable SQL. Malformed WITH clauses fall back to catalog suggestions without guessing CTE scope. Structured recovery 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.
diff --git a/services/hogql-language-service/README.md b/services/hogql-language-service/README.md
index c5f87af16e8b..1f558d4cfa60 100644
--- a/services/hogql-language-service/README.md
+++ b/services/hogql-language-service/README.md
@@ -34,6 +34,8 @@ Completion and validation share scope analysis for table CTEs and aliased `FROM`
Completion suggests projected fields, including aliases and wildcard outputs, with catalog types for direct field projections.
FROM and JOIN completion suggests visible CTE names before catalog tables and respects CTE shadowing.
Empty queries offer SELECT and WITH; typed prefixes filter those starting keywords.
+Joined fields with the same name show their source and insert a qualified reference, including separate aliases in self-joins.
+Unique fields and already-qualified completion keep their existing insertion behavior.
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.
diff --git a/services/hogql-language-service/internal/analysis/document.go b/services/hogql-language-service/internal/analysis/document.go
index 0a241301c079..b7269a225047 100644
--- a/services/hogql-language-service/internal/analysis/document.go
+++ b/services/hogql-language-service/internal/analysis/document.go
@@ -97,7 +97,7 @@ func (s *Statement) analyze() {
if bindSubquery(expr, s.scopes, s.budget) {
return true
}
- name, alias, start, end, ok := tableReference(expr)
+ name, alias, implicitAlias, start, end, ok := tableReference(expr)
if !ok {
return true
}
@@ -111,10 +111,15 @@ func (s *Statement) analyze() {
}
if original, exists := s.originalTableNames[strings.ToLower(name)]; exists {
name = original
+ implicitAlias = strings.ReplaceAll(original, ".", "__")
}
table, exists := s.schema.Table(name)
s.tables = append(s.tables, TableReference{Name: name, Start: start, End: end, Known: exists})
if exists {
+ if alias == "" && implicitAlias != name {
+ // HogQL registers multi-part table paths under a double-underscore alias.
+ alias = implicitAlias
+ }
addBinding(scope, name, alias, Relation{name: name, table: table})
}
return true
diff --git a/services/hogql-language-service/internal/analysis/scopes.go b/services/hogql-language-service/internal/analysis/scopes.go
index 92df992a857e..d7cb6352cbda 100644
--- a/services/hogql-language-service/internal/analysis/scopes.go
+++ b/services/hogql-language-service/internal/analysis/scopes.go
@@ -38,6 +38,7 @@ type queryScope struct {
query *clickhouse.SelectQuery
parent *queryScope
bindings map[string]Relation
+ sources []Source
visible map[string]Relation
unique []Relation
budget *projectionBudget
@@ -91,9 +92,12 @@ func queryScopes(statement clickhouse.Expr, budget *projectionBudget) []*querySc
func addBinding(scope *queryScope, name, alias string, binding Relation) {
scope.bindings[strings.ToLower(name)] = binding
+ source := Source{name: name, relation: binding}
if alias != "" {
scope.bindings[strings.ToLower(alias)] = binding
+ source.name = alias
}
+ scope.sources = append(scope.sources, source)
}
func (s *queryScope) visibleCTEs(position int) []*cteBinding {
@@ -192,7 +196,7 @@ func normalizeHogQLTableReferences(query string) (string, map[string]string) {
return string(normalized), originalNames
}
-func tableReference(expr *clickhouse.TableExpr) (name, alias string, start, end int, ok bool) {
+func tableReference(expr *clickhouse.TableExpr) (name, alias, implicitAlias string, start, end int, ok bool) {
node := expr.Expr
if aliased, isAlias := node.(*clickhouse.AliasExpr); isAlias {
node = aliased.Expr
@@ -202,13 +206,15 @@ func tableReference(expr *clickhouse.TableExpr) (name, alias string, start, end
}
identifier, isTable := node.(*clickhouse.TableIdentifier)
if !isTable || identifier.Table == nil {
- return "", "", 0, 0, false
+ return "", "", "", 0, 0, false
}
name = identifier.Table.Name
+ implicitAlias = name
if identifier.Database != nil {
name = identifier.Database.Name + "." + name
+ implicitAlias = identifier.Database.Name + "__" + identifier.Table.Name
}
- return name, alias, int(identifier.Pos()), int(identifier.End()), true
+ return name, alias, implicitAlias, int(identifier.Pos()), int(identifier.End()), true
}
func bindSubquery(expr *clickhouse.TableExpr, scopes []*queryScope, budget *projectionBudget) bool {
diff --git a/services/hogql-language-service/internal/analysis/sources.go b/services/hogql-language-service/internal/analysis/sources.go
new file mode 100644
index 000000000000..281bfe3158d6
--- /dev/null
+++ b/services/hogql-language-service/internal/analysis/sources.go
@@ -0,0 +1,61 @@
+package analysis
+
+import (
+ "iter"
+ "strings"
+
+ "github.com/PostHog/posthog/services/hogql-language-service/internal/catalog"
+)
+
+type Source struct {
+ name string
+ relation Relation
+}
+
+func (s Source) Qualifier() string {
+ return s.name
+}
+
+func (b Bindings) sources() iter.Seq[Source] {
+ return func(yield func(Source) bool) {
+ seen := map[string]bool{}
+ for scope := b.scope; scope != nil; scope = scope.parent {
+ for index := len(scope.sources) - 1; index >= 0; index-- {
+ source := scope.sources[index]
+ if !scope.budget.lookup(len(source.name) + 1) {
+ return
+ }
+ name := strings.ToLower(source.name)
+ if seen[name] {
+ continue
+ }
+ seen[name] = true
+ if relation, ok := b.Relation(name); ok && relation == source.relation && !yield(source) {
+ return
+ }
+ }
+ if scope.cteRoot {
+ break
+ }
+ }
+ }
+}
+
+func (b Bindings) Fields(prefix string) iter.Seq2[Source, catalog.Entry] {
+ return func(yield func(Source, catalog.Entry) bool) {
+ // Self-joins share field indexes but need a suggestion for each visible source.
+ prefixes := map[Relation]iter.Seq[catalog.Entry]{}
+ for source := range b.sources() {
+ fields, ok := prefixes[source.relation]
+ if !ok {
+ fields = source.relation.Prefix(prefix)
+ prefixes[source.relation] = fields
+ }
+ for field := range fields {
+ if !b.scope.budget.lookup(len(field.Name)+len(source.name)+1) || !yield(source, field) {
+ return
+ }
+ }
+ }
+ }
+}
diff --git a/services/hogql-language-service/internal/completion/completion.go b/services/hogql-language-service/internal/completion/completion.go
index 6409362aea75..601a392a6419 100644
--- a/services/hogql-language-service/internal/completion/completion.go
+++ b/services/hogql-language-service/internal/completion/completion.go
@@ -49,7 +49,7 @@ var predicateContinuations = []string{"AND", "OR", "GROUP BY", "ORDER BY", "LIMI
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 simpleHogQLIdentifier = regexp.MustCompile(`^[A-Za-z_$][A-Za-z0-9_$]*$`)
-var hogQLKeywords = map[string]struct{}{
+var quotedHogQLKeywords = map[string]struct{}{
"ALL": {}, "AND": {}, "ANTI": {}, "ANY": {}, "ARRAY": {}, "AS": {}, "ASC": {}, "ASCENDING": {}, "ASOF": {},
"BETWEEN": {}, "BOTH": {}, "BY": {}, "CASE": {}, "CAST": {}, "CATCH": {}, "COHORT": {}, "COLLATE": {}, "COLUMNS": {},
"CROSS": {}, "CUBE": {}, "CURRENT": {}, "DATE": {}, "DAY": {}, "DESC": {}, "DESCENDING": {}, "DISTINCT": {},
@@ -63,7 +63,7 @@ var hogQLKeywords = map[string]struct{}{
"ORDER": {}, "OUTER": {}, "OVER": {}, "PARTITION": {}, "PIVOT": {}, "POSITIONAL": {}, "PRECEDING": {},
"PREWHERE": {}, "QUALIFY": {}, "QUARTER": {}, "RANGE": {}, "RECURSIVE": {}, "REPLACE": {}, "RETURN": {}, "RIGHT": {},
"ROLLUP": {}, "ROW": {}, "ROWS": {}, "SAMPLE": {}, "SELECT": {}, "SEMI": {}, "SETS": {}, "SETTINGS": {},
- "SECOND": {}, "STEP": {}, "SUBSTRING": {}, "THEN": {}, "THROW": {}, "TIES": {}, "TIME": {}, "TIMESTAMP": {},
+ "SECOND": {}, "STEP": {}, "SUBSTRING": {}, "THEN": {}, "THROW": {}, "TIES": {}, "TIME": {},
"TO": {}, "TOP": {}, "TOTALS": {}, "TRAILING": {}, "TRIM": {}, "TRUNCATE": {}, "TRY": {}, "TRY_CAST": {},
"UNBOUNDED": {}, "UNION": {}, "UNPIVOT": {}, "USING": {}, "VALUES": {}, "WEEK": {}, "WHEN": {},
"WHERE": {}, "WHILE": {}, "WINDOW": {}, "WITH": {}, "WITHIN": {}, "YEAR": {}, "YYYY": {}, "ZONE": {},
@@ -144,26 +144,7 @@ func Complete(schema *catalog.PreparedCatalog, query string, position int, posit
suggestions = appendNamed(suggestions, comparisonOperators, lowerPrefix, "operator", "")
suggestions = appendNamed(suggestions, predicateContinuations, lowerPrefix, "keyword", "")
} else {
- aliases := map[string]bool{}
- for alias := range bindings.SelectAliases(lowerPrefix) {
- aliases[alias.Name] = true
- suggestions = appendFields(suggestions, slices.Values([]catalog.Entry{alias}))
- }
- seen := map[analysis.Relation]bool{}
- for _, relation := range bindings.All() {
- if seen[relation] {
- continue
- }
- seen[relation] = true
- fields := func(yield func(catalog.Entry) bool) {
- for field := range relation.Prefix(lowerPrefix) {
- if !aliases[field.Name] && !yield(field) {
- return
- }
- }
- }
- suggestions = appendFields(suggestions, fields)
- }
+ suggestions = fieldSuggestions(bindings, lowerPrefix)
if document != nil && document.LimitError() != nil {
return Result{}, document.LimitError()
}
@@ -184,19 +165,23 @@ func Complete(schema *catalog.PreparedCatalog, query string, position int, posit
}
left, right := strings.ToLower(suggestions[i].Label), strings.ToLower(suggestions[j].Label)
if left == right {
+ if suggestions[i].Label == suggestions[j].Label {
+ return suggestions[i].InsertText < suggestions[j].InsertText
+ }
return suggestions[i].Label < suggestions[j].Label
}
return left < right
})
- for index := range suggestions {
- suggestions[index].SortText = strconv.Itoa(suggestionRank(suggestions[index].Kind)) + "-" + strings.ToLower(suggestions[index].Label)
- }
result := Result{Suggestions: suggestions, Total: len(suggestions)}
if offset > len(suggestions) {
offset = len(suggestions)
}
end := min(offset+PageSize, len(suggestions))
result.Suggestions = suggestions[offset:end]
+ for index := range result.Suggestions {
+ // Global ranks preserve client-side page order even when labels contain punctuation.
+ result.Suggestions[index].SortText = fmt.Sprintf("%020d", offset+index)
+ }
if end < len(suggestions) {
result.NextCursor = encodeCursor(end)
}
@@ -271,16 +256,6 @@ func encodeCursor(offset int) string {
return base64.RawURLEncoding.EncodeToString([]byte(strconv.Itoa(offset)))
}
-func appendFields(out []Suggestion, fields iter.Seq[catalog.Entry]) []Suggestion {
- for field := range fields {
- if !supportedHogQLIdentifier(field.Name) {
- continue
- }
- out = append(out, Suggestion{Label: field.Name, Kind: "field", Detail: field.Type, InsertText: suggestionInsertText("field", field.Name)})
- }
- return out
-}
-
func suggestionInsertText(kind, name string) string {
insertText := name
switch kind {
@@ -304,7 +279,7 @@ func supportedHogQLIdentifier(name string) bool {
}
func quoteHogQLFieldIdentifier(name string) string {
- if _, keyword := hogQLKeywords[strings.ToUpper(name)]; keyword {
+ if _, keyword := quotedHogQLKeywords[strings.ToUpper(name)]; keyword {
return "`" + hogQLIdentifierEscaper.Replace(name) + "`"
}
return quoteHogQLIdentifier(name)
diff --git a/services/hogql-language-service/internal/completion/completion_test.go b/services/hogql-language-service/internal/completion/completion_test.go
index a74bdd9ce55e..72cd05814e9c 100644
--- a/services/hogql-language-service/internal/completion/completion_test.go
+++ b/services/hogql-language-service/internal/completion/completion_test.go
@@ -12,6 +12,7 @@ import (
"github.com/PostHog/posthog/services/hogql-language-service/internal/catalog"
"github.com/PostHog/posthog/services/hogql-language-service/internal/querylimits"
+ "github.com/PostHog/posthog/services/hogql-language-service/internal/validation"
)
func testCatalog() *catalog.PreparedCatalog {
@@ -144,13 +145,107 @@ func TestCompletesTablesAfterFrom(t *testing.T) {
}
func TestCompletesFieldsForAlias(t *testing.T) {
- query := "SELECT o. FROM orders AS o"
- result, err := Complete(testCatalog(), query, len("SELECT o."), PositionEncodingUTF8, "")
- if err != nil {
- t.Fatal(err)
+ type testCase struct {
+ name, query string
+ fields []Suggestion
}
- if len(result.Suggestions) != 2 {
- t.Fatalf("suggestions = %#v; parse error = %q", result.Suggestions, result.ParseError)
+ tests := []testCase{
+ {"qualified", "SELECT o.| FROM orders AS o", []Suggestion{{Label: "amount", Detail: "float"}, {Label: "order_id", Detail: "string"}}},
+ {"alias is not another source", "SELECT uu| FROM events AS e", []Suggestion{{Label: "uuid", Detail: "string"}}},
+ {"self join", "SELECT uu| FROM events AS e JOIN events AS other ON e.uuid = other.uuid", []Suggestion{
+ {Label: "uuid", Detail: "string from e", InsertText: "e.uuid"}, {Label: "uuid", Detail: "string from other", InsertText: "other.uuid"},
+ }},
+ {"physical join", "SELECT prop| FROM events JOIN persons ON 1 = 1", []Suggestion{
+ {Label: "properties", Detail: "json from events", InsertText: "events.properties"}, {Label: "properties", Detail: "json from persons", InsertText: "persons.properties"},
+ }},
+ {"cte and subquery", "WITH recent AS (SELECT uuid FROM events) SELECT uu| FROM recent AS r JOIN (SELECT uuid FROM events) AS s ON 1 = 1", []Suggestion{
+ {Label: "uuid", Detail: "string from r", InsertText: "r.uuid"}, {Label: "uuid", Detail: "string from s", InsertText: "s.uuid"},
+ }},
+ {"cte self join", "WITH recent AS (SELECT uuid FROM events) SELECT uu| FROM recent AS r JOIN recent AS s ON 1 = 1", []Suggestion{
+ {Label: "uuid", Detail: "string from r", InsertText: "r.uuid"}, {Label: "uuid", Detail: "string from s", InsertText: "s.uuid"},
+ }},
+ {"quoted qualifier", "SELECT uu| FROM events AS `recent.items` JOIN events AS `FROM` ON 1 = 1", []Suggestion{
+ {Label: "uuid", Detail: "string from `FROM`", InsertText: "`FROM`.uuid"}, {Label: "uuid", Detail: "string from `recent.items`", InsertText: "`recent.items`.uuid"},
+ }},
+ {"dotted cte", "WITH `recent.items` AS (SELECT uuid FROM events) SELECT uu| FROM `recent.items` JOIN events AS e ON 1 = 1", []Suggestion{
+ {Label: "uuid", Detail: "string from `recent.items`", InsertText: "`recent.items`.uuid"}, {Label: "uuid", Detail: "string from e", InsertText: "e.uuid"},
+ }},
+ {"warehouse qualifier", "WITH recent AS (SELECT uuid AS synced_id FROM events) SELECT synced_| FROM postgres.synced.orders JOIN recent ON 1 = 1", []Suggestion{
+ {Label: "synced_id", Detail: "string from postgres__synced__orders", InsertText: "postgres__synced__orders.synced_id"}, {Label: "synced_id", Detail: "string from recent", InsertText: "recent.synced_id"},
+ }},
+ {"quoted warehouse segment", "WITH recent AS (SELECT uuid AS synced_id FROM events) SELECT synced_| FROM `postgres.synced`.orders JOIN recent ON 1 = 1", []Suggestion{
+ {Label: "synced_id", Detail: "string from `postgres.synced__orders`", InsertText: "`postgres.synced__orders`.synced_id"}, {Label: "synced_id", Detail: "string from recent", InsertText: "recent.synced_id"},
+ }},
+ {"quoted field", "WITH t AS (SELECT uuid AS `user id` FROM events) SELECT us| FROM t AS a JOIN t AS b ON 1 = 1", []Suggestion{
+ {Label: "user id", Detail: "string from a", InsertText: "a.`user id`"}, {Label: "user id", Detail: "string from b", InsertText: "b.`user id`"},
+ }},
+ {"unknown expression type", "WITH t AS (SELECT count() AS total FROM events) SELECT tot| FROM t AS a JOIN t AS b ON 1 = 1", []Suggestion{
+ {Label: "total", Detail: "from a", InsertText: "a.total"}, {Label: "total", Detail: "from b", InsertText: "b.total"},
+ }},
+ {"case-folded fields", "WITH a AS (SELECT uuid AS shared FROM events), b AS (SELECT uuid AS SHARED FROM events) SELECT sha| FROM a JOIN b ON 1 = 1", []Suggestion{
+ {Label: "SHARED", Detail: "string from b", InsertText: "b.SHARED"}, {Label: "shared", Detail: "string from a", InsertText: "a.shared"},
+ }},
+ {"select alias precedence", "SELECT e.event AS uuid FROM events AS e JOIN events AS other ON 1 = 1 ORDER BY uu|", []Suggestion{{Label: "uuid", Detail: "string"}}},
+ {"case-sensitive select alias precedence", "SELECT e.properties AS UUID FROM events AS e JOIN events AS other ON 1 = 1 ORDER BY uu|", []Suggestion{
+ {Label: "UUID", Detail: "json"}, {Label: "uuid", Detail: "string from e", InsertText: "e.uuid"}, {Label: "uuid", Detail: "string from other", InsertText: "other.uuid"},
+ }},
+ {"qualified join stays unqualified", "SELECT e.uu| FROM events AS e JOIN events AS other ON 1 = 1", []Suggestion{{Label: "uuid", Detail: "string"}}},
+ {"nested alias shadow", "SELECT * FROM events AS e WHERE uuid IN (SELECT uu| FROM events AS e)", []Suggestion{{Label: "uuid", Detail: "string"}}},
+ {"cte scope isolation", "WITH t AS (SELECT uu| FROM events AS e) SELECT * FROM t JOIN events AS other ON 1 = 1", []Suggestion{{Label: "uuid", Detail: "string"}}},
+ {"subquery scope isolation", "SELECT * FROM events AS e JOIN (SELECT uu| FROM events AS other) AS s ON 1 = 1", []Suggestion{{Label: "uuid", Detail: "string"}}},
+ }
+ var sources []string
+ var fields []Suggestion
+ for index := range PageSize + 2 {
+ alias := fmt.Sprintf("source_%02d", index)
+ sources = append(sources, "events AS "+alias)
+ fields = append(fields, Suggestion{Label: "uuid", Detail: "string from " + alias, InsertText: alias + ".uuid"})
+ }
+ tests = append(tests, testCase{"joined pagination", "SELECT uu| FROM " + strings.Join(sources, " CROSS JOIN "), fields})
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ position := strings.IndexByte(test.query, '|')
+ query := strings.Replace(test.query, "|", "", 1)
+ var fields []Suggestion
+ cursor := ""
+ for {
+ result, err := Complete(testCatalog(), query, position, PositionEncodingUTF8, cursor)
+ if err != nil || result.ParseError != "" || len(result.Suggestions) > PageSize {
+ t.Fatalf("result = %#v, err = %v", result, err)
+ }
+ for _, suggestion := range result.Suggestions {
+ if suggestion.Kind == "field" {
+ fields = append(fields, suggestion)
+ }
+ }
+ cursor = result.NextCursor
+ if cursor == "" {
+ break
+ }
+ if len(fields) >= len(test.fields) {
+ t.Fatalf("unexpected next page: %#v", result)
+ }
+ }
+ if len(fields) != len(test.fields) {
+ t.Fatalf("fields = %#v, want %#v", fields, test.fields)
+ }
+ for index, expected := range test.fields {
+ actual := fields[index]
+ if actual.Label != expected.Label || actual.Detail != expected.Detail || actual.InsertText != expected.InsertText {
+ t.Errorf("field = %#v, want %#v", actual, expected)
+ }
+ if actual.InsertText != "" {
+ start := strings.LastIndexByte(query[:position], ' ') + 1
+ completed := query[:start] + actual.InsertText + query[position:]
+ if checked := validation.Validate(testCatalog(), completed); !checked.Valid {
+ t.Errorf("inserted query %q is invalid: %#v", completed, checked)
+ }
+ }
+ if index > 0 && fields[index-1].SortText >= actual.SortText {
+ t.Errorf("sort keys disagree with page order: %#v", fields)
+ }
+ }
+ })
}
}
@@ -297,29 +392,44 @@ func BenchmarkCompleteDerivedLookups(b *testing.B) {
}
}
-func TestSelectAliasLookupWorkBudget(t *testing.T) {
+func TestCompletionFieldLookupWorkBudget(t *testing.T) {
tables := map[string]catalog.Table{}
var sources []string
for index := range 128 {
name := fmt.Sprintf("source_%d", index)
- tables[name] = catalog.Table{Name: name, Fields: map[string]catalog.Field{"amount": {Name: "amount", Type: "float"}}}
+ tables[name] = catalog.Table{Name: name, Fields: map[string]catalog.Field{
+ "amount": {Name: "amount", Type: "float"},
+ "field_" + strings.Repeat("x", 8192): {Type: "float"},
+ }}
sources = append(sources, name)
}
schema := catalog.Prepare(&catalog.Catalog{Tables: tables})
- query := "SELECT " + strings.Repeat("x", 8192) + " AS total FROM " + strings.Join(sources, " CROSS JOIN ") + " ORDER BY tot"
- if err := querylimits.Validate(query); err != nil {
- t.Fatal(err)
- }
- result, err := Complete(schema, query, len(query), PositionEncodingUTF8, "")
- if !errors.Is(err, querylimits.ErrFieldLookupTooLarge) || len(result.Suggestions) != 0 {
- t.Fatalf("result = %#v, err = %v", result, err)
+ for _, query := range []string{
+ "SELECT " + strings.Repeat("x", 8192) + " AS total FROM " + strings.Join(sources, " CROSS JOIN ") + " ORDER BY tot|",
+ "SELECT field_| FROM " + strings.Join(sources, " CROSS JOIN "),
+ } {
+ position := strings.IndexByte(query, '|')
+ query = strings.Replace(query, "|", "", 1)
+ if err := querylimits.Validate(query); err != nil {
+ t.Fatal(err)
+ }
+ result, err := Complete(schema, query, position, PositionEncodingUTF8, "")
+ if !errors.Is(err, querylimits.ErrFieldLookupTooLarge) || len(result.Suggestions) != 0 {
+ t.Fatalf("result = %#v, err = %v", result, err)
+ }
}
}
func TestProjectionPaginationAndLimits(t *testing.T) {
var items []string
+ var names []string
for index := 0; index < PageSize+2; index++ {
- items = append(items, fmt.Sprintf("amount AS field_%02d", index))
+ name := fmt.Sprintf("field_%02d", index)
+ if index == PageSize {
+ name = names[index-1] + "$x"
+ }
+ names = append(names, name)
+ items = append(items, "amount AS "+name)
}
items = append(items, "amount AS field_00")
for _, source := range []string{
@@ -331,12 +441,17 @@ func TestProjectionPaginationAndLimits(t *testing.T) {
query := strings.Replace(source, "|", "", 1)
cursor := ""
var fields []string
+ previousSortText := ""
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 {
+ if suggestion.SortText <= previousSortText {
+ t.Fatalf("query %q: sort key %q does not follow %q", query, suggestion.SortText, previousSortText)
+ }
+ previousSortText = suggestion.SortText
fields = append(fields, suggestion.Label)
}
cursor = result.NextCursor
@@ -351,7 +466,7 @@ func TestProjectionPaginationAndLimits(t *testing.T) {
t.Fatalf("fields = %#v", fields)
}
for index, name := range fields {
- if name != fmt.Sprintf("field_%02d", index) {
+ if name != names[index] {
t.Fatalf("fields = %#v", fields)
}
}
@@ -381,6 +496,7 @@ func TestCompletionQuotesIdentifierInsertionText(t *testing.T) {
"order-total": {Name: "order-total", Type: "float"},
"percent%field": {Name: "percent%field", Type: "string"},
"tick`value": {Name: "tick`value", Type: "string"},
+ "timestamp": {Name: "timestamp", Type: "datetime"},
}},
}, Properties: map[string][]catalog.Property{}})
@@ -422,6 +538,7 @@ func TestCompletionQuotesIdentifierInsertionText(t *testing.T) {
{result: fieldResult, label: "FROM", insertText: "`FROM`"},
{result: fieldResult, label: "order-total", insertText: "`order-total`"},
{result: fieldResult, label: "tick`value", insertText: "`tick``value`"},
+ {result: fieldResult, label: "timestamp", insertText: ""},
{result: aliasResult, label: "billing total", insertText: "`billing total`"},
{result: cteResult, label: "recent.items", insertText: "`recent.items`"},
{result: cteResult, label: "recent items", insertText: "`recent items`"},
@@ -431,6 +548,32 @@ func TestCompletionQuotesIdentifierInsertionText(t *testing.T) {
t.Fatalf("suggestion %q = %#v, want insert text %q", test.label, suggestion, test.insertText)
}
}
+ for _, test := range []struct {
+ query, insertText string
+ }{
+ {"SELECT * FROM orders WHERE 1 = 1 AND tim| > now()", "timestamp"},
+ {"SELECT o.tim| FROM orders AS o", "timestamp"},
+ {"SELECT tim| FROM orders AS a JOIN orders AS b ON 1 = 1", "a.timestamp"},
+ } {
+ position := strings.IndexByte(test.query, '|')
+ query := strings.Replace(test.query, "|", "", 1)
+ result, err := Complete(schema, query, position, PositionEncodingUTF8, "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ suggestion, ok := findSuggestion(result.Suggestions, "timestamp")
+ insertText := suggestion.InsertText
+ if insertText == "" {
+ insertText = suggestion.Label
+ }
+ if !ok || insertText != test.insertText {
+ t.Fatalf("query %q: suggestion = %#v, want insertion %q", query, suggestion, test.insertText)
+ }
+ completed := query[:position-len("tim")] + insertText + query[position:]
+ if checked := validation.Validate(schema, completed); !checked.Valid {
+ t.Errorf("inserted query %q is invalid: %#v", completed, checked)
+ }
+ }
for _, test := range []struct {
result Result
label string
@@ -657,6 +800,7 @@ func TestCompleteContextualCatalogStaysWithinLatencyBudget(t *testing.T) {
callsPerSample int
}{
{name: "contextual catalog", query: "SELECT countD FROM table_0500", position: len("SELECT countD"), callsPerSample: 100},
+ {name: "joined fields", query: "SELECT column_ FROM table_0500 AS a JOIN table_0500 AS b ON 1 = 1", position: len("SELECT column_"), callsPerSample: 100},
{name: "adversarial interval expression", query: intervalQuery, position: len(intervalQuery), callsPerSample: 20},
} {
t.Run(test.name, func(t *testing.T) {
@@ -709,6 +853,7 @@ func BenchmarkCompleteContextualCatalog(b *testing.B) {
}{
{name: "operator", query: "SELECT * FROM table_0500 WHERE column_10 ", position: len("SELECT * FROM table_0500 WHERE column_10 ")},
{name: "function prefix", query: "SELECT countD FROM table_0500", position: len("SELECT countD")},
+ {name: "joined fields", query: "SELECT column_ FROM table_0500 AS a JOIN table_0500 AS b ON 1 = 1", position: len("SELECT column_")},
{name: "repeated interval", query: "SELECT * FROM table_0500 WHERE column_10 BETWEEN " + strings.Repeat("INTERVAL ", 1000) + "1 DAY ", position: len("SELECT * FROM table_0500 WHERE column_10 BETWEEN ") + len("INTERVAL ")*1000 + len("1 DAY ")},
} {
b.Run(benchmark.name, func(b *testing.B) {
diff --git a/services/hogql-language-service/internal/completion/fields.go b/services/hogql-language-service/internal/completion/fields.go
new file mode 100644
index 000000000000..ad92fcc99845
--- /dev/null
+++ b/services/hogql-language-service/internal/completion/fields.go
@@ -0,0 +1,62 @@
+package completion
+
+import (
+ "strings"
+ "unicode"
+
+ "github.com/PostHog/posthog/services/hogql-language-service/internal/analysis"
+)
+
+func fieldSuggestions(bindings analysis.Bindings, prefix string) []Suggestion {
+ var suggestions []Suggestion
+ // HogQL alias precedence is case-sensitive (resolver_utils.lookup_field_by_name).
+ aliases := map[string]bool{}
+ for alias := range bindings.SelectAliases(prefix) {
+ aliases[alias.Name] = true
+ if supportedHogQLIdentifier(alias.Name) {
+ suggestions = append(suggestions, Suggestion{Label: alias.Name, Kind: "field", Detail: alias.Type, InsertText: suggestionInsertText("field", alias.Name)})
+ }
+ }
+ type candidate struct {
+ field Suggestion
+ qualifier string
+ key string
+ }
+ var candidates []candidate
+ counts := map[string]int{}
+ qualifiers := map[analysis.Source]string{}
+ for source, field := range bindings.Fields(prefix) {
+ if aliases[field.Name] || !supportedHogQLIdentifier(field.Name) {
+ continue
+ }
+ qualifier, ok := qualifiers[source]
+ if !ok {
+ qualifier = quoteHogQLFieldIdentifier(source.Qualifier())
+ qualifiers[source] = qualifier
+ }
+ key := 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
+ }, field.Name)
+ counts[key]++
+ candidates = append(candidates, candidate{
+ field: Suggestion{Label: field.Name, Kind: "field", Detail: field.Type, InsertText: suggestionInsertText("field", field.Name)},
+ qualifier: qualifier, key: key,
+ })
+ }
+ for _, candidate := range candidates {
+ field := candidate.field
+ if counts[candidate.key] > 1 {
+ if !supportedHogQLIdentifier(candidate.qualifier) {
+ continue
+ }
+ field.InsertText = candidate.qualifier + "." + quoteHogQLFieldIdentifier(field.Label)
+ field.Detail = strings.TrimSpace(field.Detail + " from " + candidate.qualifier)
+ }
+ suggestions = append(suggestions, field)
+ }
+ return suggestions
+}