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): suggest cte tables and query-start keywords (#101907)

Paweł Szczuradb65308b261
diff --git a/docs/internal/hogql-language-service-demo.md b/docs/internal/hogql-language-service-demo.md
index 1ec75afa42e6..eba5b201132d 100644
--- a/docs/internal/hogql-language-service-demo.md
+++ b/docs/internal/hogql-language-service-demo.md
@@ -59,7 +59,8 @@ Ctrl+Space is left available for the operating system's input-source shortcut.
Enable **Analyze as you type** to run both operations after a 300 ms typing pause.
The checkbox is off by default. Enabling it also analyzes the current query; loading an example or inserting a suggestion schedules analysis too.
Turning it off cancels scheduled analysis and in-flight requests. Manual buttons and shortcuts remain available.
-Empty queries and unfinished input-method composition do not trigger automatic requests.
+Empty queries trigger completion for SELECT and WITH, but not validation.
+Unfinished input-method composition does not trigger automatic requests.
Completion requests use UTF-16 offsets, matching the textarea selection API.
Validation requests explicitly select UTF-8 offsets; the page converts those byte ranges to UTF-16 for diagnostic selection.
Raw responses and copied exchanges keep the service's original offsets.
diff --git a/docs/internal/hogql-language-service.md b/docs/internal/hogql-language-service.md
index 2cad45c8ac19..0f1d6f1e2e7b 100644
--- a/docs/internal/hogql-language-service.md
+++ b/docs/internal/hogql-language-service.md
@@ -40,11 +40,18 @@ Statements initialize on demand, while CTE and aliased subquery projections shar
Validation retains diagnostic formatting, typo suggestions, and position-encoding conversion.
Completion replaces the identifier at the cursor with a placeholder and resolves the containing scope.
+An empty query, whitespace, or the start of a statement offers SELECT and WITH, filtered by the typed prefix.
+Completed comments can precede these starters; completion remains disabled inside strings and unfinished comments.
+These suggestions do not carry a parser error for the unfinished statement.
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`.
+FROM and JOIN completion includes visible table CTEs before catalog tables, with `CTE` in the suggestion detail.
+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.
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.
@@ -72,7 +79,7 @@ Derived qualified suggestions are sorted and deduplicated before pagination.
- 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.
-- Table-name suggestions still use the catalog; adding visible CTE names to `FROM` and `JOIN` suggestions remains follow-up work.
+- 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 7189640de252..c5f87af16e8b 100644
--- a/services/hogql-language-service/README.md
+++ b/services/hogql-language-service/README.md
@@ -32,6 +32,8 @@ curl -sS -X POST http://localhost:8091/teams/2/users/1/validate \
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.
+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.
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/cmd/demo/assets/app.js b/services/hogql-language-service/cmd/demo/assets/app.js
index 57461e61ff28..ce24067473fa 100644
--- a/services/hogql-language-service/cmd/demo/assets/app.js
+++ b/services/hogql-language-service/cmd/demo/assets/app.js
@@ -146,12 +146,14 @@ function cancelScheduledAnalysis() {
function scheduleAnalysis() {
cancelScheduledAnalysis()
- if (!byId('auto-analyze').checked || composing || !editor.value.trim()) {
+ if (!byId('auto-analyze').checked || composing) {
return
}
analysisTimer = setTimeout(() => {
analysisTimer = null
- validate()
+ if (editor.value.trim()) {
+ validate()
+ }
complete()
}, 300)
}
diff --git a/services/hogql-language-service/internal/analysis/document.go b/services/hogql-language-service/internal/analysis/document.go
index e00dcabbcfd1..0a241301c079 100644
--- a/services/hogql-language-service/internal/analysis/document.go
+++ b/services/hogql-language-service/internal/analysis/document.go
@@ -160,6 +160,30 @@ func (b Bindings) Len() int {
return len(b.relations)
}
+func (b Bindings) CTENames(prefix string) iter.Seq[catalog.Entry] {
+ return func(yield func(catalog.Entry) bool) {
+ seen := map[string]bool{}
+ prefix = foldedFieldName(prefix)
+ for scope := b.scope; scope != nil; scope = scope.parent {
+ ctes := scope.visibleCTEs(b.position)
+ for index := len(ctes) - 1; index >= 0; index-- {
+ name := ctes[index].name
+ if !scope.budget.lookup(len(name) + 1) {
+ return
+ }
+ folded := foldedFieldName(name)
+ if seen[folded] {
+ continue
+ }
+ seen[folded] = true
+ if strings.HasPrefix(folded, prefix) && !yield(catalog.Entry{Name: name, Type: "CTE"}) {
+ return
+ }
+ }
+ }
+ }
+}
+
func (b Bindings) Relation(name string) (Relation, bool) {
relation, ok := b.relations[strings.ToLower(name)]
return relation, ok
diff --git a/services/hogql-language-service/internal/analysis/scopes.go b/services/hogql-language-service/internal/analysis/scopes.go
index 42174aeda1ac..92df992a857e 100644
--- a/services/hogql-language-service/internal/analysis/scopes.go
+++ b/services/hogql-language-service/internal/analysis/scopes.go
@@ -96,18 +96,21 @@ func addBinding(scope *queryScope, name, alias string, binding Relation) {
}
}
+func (s *queryScope) visibleCTEs(position int) []*cteBinding {
+ for index, cte := range s.ctes {
+ if contains(cte.query, position, position) {
+ return s.ctes[:index]
+ }
+ }
+ return s.ctes
+}
+
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]
+ ctes := current.visibleCTEs(position)
+ for index := len(ctes) - 1; index >= 0; index-- {
+ if strings.EqualFold(ctes[index].name, name) {
+ return ctes[index]
}
}
}
diff --git a/services/hogql-language-service/internal/completion/completion.go b/services/hogql-language-service/internal/completion/completion.go
index 41c6d87054a2..6409362aea75 100644
--- a/services/hogql-language-service/internal/completion/completion.go
+++ b/services/hogql-language-service/internal/completion/completion.go
@@ -43,6 +43,7 @@ const (
)
var keywords = []string{"SELECT", "FROM", "WHERE", "GROUP BY", "ORDER BY", "LIMIT", "JOIN", "AS", "CASE", "NULL", "TRUE", "FALSE", "NOT"}
+var queryStarters = []catalog.Entry{{Name: "SELECT"}, {Name: "WITH"}}
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"}
@@ -101,6 +102,16 @@ func Complete(schema *catalog.PreparedCatalog, query string, position int, posit
if mode == completionModeNone {
return Result{Suggestions: []Suggestion{}}, nil
}
+ if mode == completionModeStatementStart {
+ entries := func(yield func(catalog.Entry) bool) {
+ for _, entry := range queryStarters {
+ if hasLowerPrefix(entry.Name, lowerPrefix) && !yield(entry) {
+ return
+ }
+ }
+ }
+ return indexedResult(entries, "keyword", offset, nil), nil
+ }
repaired := query[:start] + "__posthog_cursor__" + query[position:]
document, bindings, qualified, parseErr := cursorBindings(schema, repaired, start, qualifier)
@@ -118,7 +129,11 @@ func Complete(schema *catalog.PreparedCatalog, query string, position int, posit
}
return indexedResult(entries, "field", offset, parseErr), nil
} else if mode == completionModeTable {
- return indexedResult(slices.Values(schema.Tables().Prefix(lowerPrefix)), "table", offset, parseErr), nil
+ result := tableResult(schema, bindings, lowerPrefix, offset, parseErr)
+ if document != nil && document.LimitError() != nil {
+ return Result{}, document.LimitError()
+ }
+ return result, nil
} else if mode == completionModeComparison {
suggestions = appendNamed(suggestions, comparisonOperators, lowerPrefix, "operator", "")
} else if mode == completionModeBetweenSeparator {
diff --git a/services/hogql-language-service/internal/completion/completion_test.go b/services/hogql-language-service/internal/completion/completion_test.go
index ef73e54948e8..a74bdd9ce55e 100644
--- a/services/hogql-language-service/internal/completion/completion_test.go
+++ b/services/hogql-language-service/internal/completion/completion_test.go
@@ -101,12 +101,45 @@ func TestCompletesFieldsForHogQLQualifiedTable(t *testing.T) {
}
func TestCompletesTablesAfterFrom(t *testing.T) {
- result, err := Complete(testCatalog(), "SELECT * FROM ord", len("SELECT * FROM ord"), PositionEncodingUTF8, "")
- if err != nil {
- t.Fatal(err)
- }
- if len(result.Suggestions) != 1 || result.Suggestions[0].Label != "orders" {
- t.Fatalf("suggestions = %#v; parse error = %q", result.Suggestions, result.ParseError)
+ for _, test := range []struct {
+ name, query string
+ tables map[string]string
+ }{
+ {"catalog", "SELECT * FROM ord|", map[string]string{"orders": "data_warehouse"}},
+ {"cte from", "WITH recent AS (SELECT event FROM events) SELECT * FROM rec|", map[string]string{"recent": "CTE"}},
+ {"cte join", "WITH recent AS (SELECT event FROM events) SELECT * FROM events JOIN rec| ON 1 = 1", map[string]string{"recent": "CTE"}},
+ {"cte comma", "WITH recent AS (SELECT event FROM events) SELECT * FROM events, rec|", map[string]string{"recent": "CTE"}},
+ {"catalog and cte", "WITH order_summary AS (SELECT event FROM events) SELECT * FROM ord|", map[string]string{"orders": "data_warehouse", "order_summary": "CTE"}},
+ {"catalog shadow", "WITH Orders AS (SELECT event FROM events) SELECT * FROM ord|", map[string]string{"Orders": "CTE"}},
+ {"unicode prefix", "WITH `Σ` AS (SELECT event FROM events) SELECT * FROM ς|", map[string]string{"Σ": "CTE"}},
+ {"inner shadow", "WITH recent AS (SELECT event FROM events) SELECT * FROM (WITH Recent AS (SELECT uuid FROM events) SELECT * FROM rec|) AS s", map[string]string{"Recent": "CTE"}},
+ {"outer visible", "WITH recent AS (SELECT event FROM events) SELECT * FROM (SELECT * FROM rec|) AS s", map[string]string{"recent": "CTE"}},
+ {"previous cte", "WITH recent AS (SELECT event FROM events), recent_next AS (SELECT * FROM rec|) SELECT * FROM recent_next", map[string]string{"recent": "CTE"}},
+ {"no self or later cte", "WITH recent AS (SELECT * FROM rec|), recent_next AS (SELECT event FROM events) SELECT * FROM recent", nil},
+ {"no sibling cte", "SELECT * FROM (WITH recent AS (SELECT event FROM events) SELECT * FROM recent) AS a JOIN (SELECT * FROM rec|) AS b ON 1 = 1", nil},
+ {"no previous statement", "WITH recent AS (SELECT event FROM events) SELECT * FROM recent; SELECT * FROM rec|", nil},
+ {"no scalar alias", "WITH 1 AS recent SELECT * FROM rec|", nil},
+ {"malformed cte", "WITH recent AS (SELECT event FROM events SELECT * FROM rec|", nil},
+ } {
+ 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)
+ }
+ if len(result.Suggestions) != len(test.tables) || result.Total != len(test.tables) {
+ t.Fatalf("result = %#v, want tables %#v", result, test.tables)
+ }
+ seen := map[string]bool{}
+ for _, suggestion := range result.Suggestions {
+ detail, exists := test.tables[suggestion.Label]
+ if !exists || seen[suggestion.Label] || suggestion.Kind != "table" || suggestion.Detail != detail {
+ t.Fatalf("unexpected suggestion %#v, want tables %#v", suggestion, test.tables)
+ }
+ seen[suggestion.Label] = true
+ }
+ })
}
}
@@ -372,6 +405,11 @@ func TestCompletionQuotesIdentifierInsertionText(t *testing.T) {
if err != nil {
t.Fatal(err)
}
+ cteQuery := "WITH `recent.items` AS (SELECT * FROM orders), `recent items` AS (SELECT * FROM orders) SELECT * FROM rec"
+ cteResult, err := Complete(schema, cteQuery, len(cteQuery), PositionEncodingUTF8, "")
+ if err != nil {
+ t.Fatal(err)
+ }
for _, test := range []struct {
result Result
@@ -385,6 +423,8 @@ func TestCompletionQuotesIdentifierInsertionText(t *testing.T) {
{result: fieldResult, label: "order-total", insertText: "`order-total`"},
{result: fieldResult, label: "tick`value", insertText: "`tick``value`"},
{result: aliasResult, label: "billing total", insertText: "`billing total`"},
+ {result: cteResult, label: "recent.items", insertText: "`recent.items`"},
+ {result: cteResult, label: "recent items", insertText: "`recent items`"},
} {
suggestion, ok := findSuggestion(test.result.Suggestions, test.label)
if !ok || suggestion.InsertText != test.insertText {
@@ -452,6 +492,13 @@ func TestCompletesSQLSyntaxForCursorContext(t *testing.T) {
excluded []string
total int
}{
+ {name: "empty query select", query: "", position: 0, label: "SELECT", kind: "keyword", total: 2},
+ {name: "empty query with", query: "", position: 0, label: "WITH", kind: "keyword", total: 2},
+ {name: "whitespace query", query: " \n\t\u2003", position: len(" \n\t\u2003"), label: "SELECT", kind: "keyword", total: 2},
+ {name: "select prefix", query: "sel", position: 3, label: "SELECT", kind: "keyword", total: 1},
+ {name: "with prefix", query: "wi", position: 2, label: "WITH", kind: "keyword", total: 1},
+ {name: "after comment", query: "-- example\n", position: len("-- example\n"), label: "WITH", kind: "keyword", total: 2},
+ {name: "after statement", query: "SELECT 1; ", position: len("SELECT 1; "), label: "SELECT", kind: "keyword", total: 2},
{name: "function in select", query: "SELECT cou FROM orders", position: len("SELECT cou"), label: "count", kind: "function", insertText: "count()"},
{name: "embedded function in select", query: "SELECT geoD FROM orders", position: len("SELECT geoD"), label: "geoDistance", kind: "function", insertText: "geoDistance()"},
{name: "function in where", query: "SELECT * FROM orders WHERE coa", position: len("SELECT * FROM orders WHERE coa"), label: "coalesce", kind: "function", insertText: "coalesce()"},
@@ -497,6 +544,8 @@ func TestCompletesSQLSyntaxForCursorContext(t *testing.T) {
func TestCompletionReturnsNoSuggestionsInsideStringOrComment(t *testing.T) {
for _, query := range []string{
+ "-- sel",
+ "/* wi",
"SELECT * FROM orders WHERE order_id = 'cou",
"SELECT * FROM orders -- cou",
"SELECT * FROM orders /* cou",
@@ -519,25 +568,38 @@ func TestCompletionPagesWithoutSkippingOrRepeatingTables(t *testing.T) {
}
prepared := catalog.Prepare(schema)
query := "SELECT * FROM table_"
- first, err := Complete(prepared, query, len(query), PositionEncodingUTF8, "")
- if err != nil {
- t.Fatal(err)
- }
- if len(first.Suggestions) != PageSize || first.NextCursor == "" {
- t.Fatalf("first page has %d suggestions and cursor %q", len(first.Suggestions), first.NextCursor)
- }
- if first.Total != 30 {
- t.Fatalf("total = %d", first.Total)
- }
- second, err := Complete(prepared, query, len(query), PositionEncodingUTF8, first.NextCursor)
- if err != nil {
- t.Fatal(err)
- }
- if len(second.Suggestions) != 5 || second.NextCursor != "" {
- t.Fatalf("second page has %d suggestions and cursor %q", len(second.Suggestions), second.NextCursor)
- }
- if first.Suggestions[24].Label != "table_24" || second.Suggestions[0].Label != "table_25" {
- t.Fatalf("page boundary is %q then %q", first.Suggestions[24].Label, second.Suggestions[0].Label)
+ for _, ctePrefix := range []string{"", "WITH table_05 AS (SELECT 1), table_30 AS (SELECT 2) "} {
+ t.Run(ctePrefix, func(t *testing.T) {
+ input := ctePrefix + query
+ var expected []string
+ if ctePrefix != "" {
+ expected = append(expected, "table_05", "table_30")
+ }
+ for index := range 30 {
+ if ctePrefix == "" || index != 5 {
+ expected = append(expected, fmt.Sprintf("table_%02d", index))
+ }
+ }
+ first, err := Complete(prepared, input, len(input), PositionEncodingUTF8, "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(first.Suggestions) != PageSize || first.NextCursor == "" || first.Total != len(expected) {
+ t.Fatalf("first page = %#v", first)
+ }
+ second, err := Complete(prepared, input, len(input), PositionEncodingUTF8, first.NextCursor)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(second.Suggestions) != len(expected)-PageSize || second.NextCursor != "" || second.Total != len(expected) {
+ t.Fatalf("second page = %#v", second)
+ }
+ for index, suggestion := range append(first.Suggestions, second.Suggestions...) {
+ if suggestion.Label != expected[index] {
+ t.Fatalf("suggestion %d = %#v, want %s", index, suggestion, expected[index])
+ }
+ }
+ })
}
if _, err := Complete(prepared, query, len(query), PositionEncodingUTF8, "not-a-cursor"); err == nil {
t.Fatal("invalid cursor was accepted")
diff --git a/services/hogql-language-service/internal/completion/context.go b/services/hogql-language-service/internal/completion/context.go
index c264ba346f87..9ecc5a616279 100644
--- a/services/hogql-language-service/internal/completion/context.go
+++ b/services/hogql-language-service/internal/completion/context.go
@@ -17,6 +17,7 @@ const (
completionModeBetweenSeparator
completionModePredicateContinuation
completionModePostExpression
+ completionModeStatementStart
)
type sqlTokenKind uint8
@@ -41,6 +42,9 @@ func analyzeCursorContext(input string) completionMode {
if incomplete {
return completionModeNone
}
+ if len(tokens) == 0 || tokens[len(tokens)-1].text == ";" && depth == 0 {
+ return completionModeStatementStart
+ }
clauseIndex, clause := activeClause(tokens, depth)
switch clause {
case "FROM", "JOIN":
@@ -240,8 +244,9 @@ func scanSQLTokens(input string) ([]sqlToken, int, bool) {
depth := 0
for index := 0; index < len(input); {
character := input[index]
- if unicode.IsSpace(rune(character)) {
- index++
+ r, size := utf8.DecodeRuneInString(input[index:])
+ if unicode.IsSpace(r) {
+ index += size
continue
}
if character == '-' && index+1 < len(input) && input[index+1] == '-' {
diff --git a/services/hogql-language-service/internal/completion/tables.go b/services/hogql-language-service/internal/completion/tables.go
new file mode 100644
index 000000000000..24fff09e7f09
--- /dev/null
+++ b/services/hogql-language-service/internal/completion/tables.go
@@ -0,0 +1,49 @@
+package completion
+
+import (
+ "slices"
+ "strings"
+
+ "github.com/PostHog/posthog/services/hogql-language-service/internal/analysis"
+ "github.com/PostHog/posthog/services/hogql-language-service/internal/catalog"
+)
+
+func tableResult(schema *catalog.PreparedCatalog, bindings analysis.Bindings, prefix string, offset int, parseErr error) Result {
+ ctes := slices.Collect(bindings.CTENames(prefix))
+ if len(ctes) == 0 {
+ return indexedResult(slices.Values(schema.Tables().Prefix(prefix)), "table", offset, parseErr)
+ }
+ slices.SortFunc(ctes, func(left, right catalog.Entry) int {
+ return strings.Compare(strings.ToLower(left.Name), strings.ToLower(right.Name))
+ })
+ cteNames := map[string]bool{}
+ shadowed := map[string]bool{}
+ for _, cte := range ctes {
+ cteNames[cte.Name] = true
+ if table, ok := schema.Table(cte.Name); ok {
+ shadowed[table.Name] = true
+ }
+ }
+ entries := func(yield func(catalog.Entry) bool) {
+ for _, cte := range ctes {
+ if !yield(cte) {
+ return
+ }
+ }
+ for _, table := range schema.Tables().Prefix(prefix) {
+ if !shadowed[table.Name] && !yield(table) {
+ return
+ }
+ }
+ }
+ result := indexedResult(entries, "table", offset, parseErr)
+ for index := range result.Suggestions {
+ suggestion := &result.Suggestions[index]
+ if cteNames[suggestion.Label] {
+ // A dotted CTE name is one identifier, unlike a qualified catalog table name.
+ suggestion.InsertText = suggestionInsertText("field", suggestion.Label)
+ suggestion.SortText = "0-" + strings.ToLower(suggestion.Label)
+ }
+ }
+ return result
+}