: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(hogql): recover CTE completions in unfinished outer clauses (#102820)
Paweł Szczurd83746239a4c
diff --git a/docs/internal/hogql-language-service-demo.md b/docs/internal/hogql-language-service-demo.mdindex 14a7de3914d0..f4177aa0d3b4 100644--- a/docs/internal/hogql-language-service-demo.md+++ b/docs/internal/hogql-language-service-demo.md@@ -55,6 +55,7 @@ Do not add the demo to deployment configuration or the production server's route- Select **Property pagination** and use **Load more** to retrieve all 35 matching names.- Select **Quoted identifiers** and insert `billing address` to inspect identifier quoting. The service supplies quoted insertion text; the page does not add quotes.- Use **CTE completion** and **Subquery completion** to inspect current derived-relation support. Empty suggestions are shown as returned by the service, without a browser fallback.+- Try `WITH recent AS (SELECT properties FROM events) SELECT recent.pro FROM recent WHERE (` with the cursor after `pro`. Completion should suggest `properties` and retain a parser error; validation should still reject the unfinished query.- Open raw responses to inspect parser errors, diagnostics, pagination cursors, physical table names, and catalog revisions.- Stop and restart the demo to confirm that the connection indicator changes to disconnected and recovers.@@ -104,7 +105,7 @@ They are not evidence that a query would succeed or fail in the full PostHog com| Area | Current boundary and reason | Follow-up and acceptance check || -------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || Full PostHog catalog parity | The fixture is a small, static subset so the demo runs without Django. Virtual joins and all product tables are not modeled completely. | Add an optional catalog generator using a synthetic local project. Compare its published schema with Django's catalog for that project and document required services. |-| Derived-relation completion | The service resolves CTE and aliased subquery fields through the shared analyzer. The page does not invent missing suggestions. | Use the examples to check projected fields, aliases, types, and direct property origins. Structured recovery for malformed queries remains separate work. |+| Derived-relation completion | The service resolves CTE and aliased subquery fields through the shared analyzer. Complete CTE definitions can retain outer-query completion through unfinished trailing clauses. | Check fields and property origins both before and inside an unfinished outer predicate. Broken CTE definitions, nested outer-query SELECTs, and incomplete sources still require separate recovery work. || Identifier quoting | The page uses the service's quoted `insertText`. Completion inside an already quoted identifier is not supported by the textarea adapter. | Add quote-aware token replacement before supporting completion inside existing quotes. Check escaped backticks and mid-token edits. || Alias and property semantics | The service preserves direct property origins through derived fields and visible SELECT aliases. Computed or ambiguous origins do not produce property suggestions. | Check event/person separation, renamed containers, and aliases in supported clauses. Computed-expression and nested JSON provenance require separate design and tests. || Other HogQL constructs | Examples do not establish coverage for unions, scalar `WITH` aliases, CTE column-name lists, recursive CTEs, or every dialect. | Decide supported constructs explicitly in the analyzer design; add examples and observable regression coverage for each supported construct. Retain the service's exclusion of recursive CTE support unless that scope changes. |diff --git a/docs/internal/hogql-language-service.md b/docs/internal/hogql-language-service.mdindex e67cbe1dfb1f..063144c7f5d8 100644--- a/docs/internal/hogql-language-service.md+++ b/docs/internal/hogql-language-service.md@@ -110,6 +110,41 @@ Aliases of the same relation share a cached field index and one candidate entryCompletion returns HTTP 400 when either limit is exceeded; validation returns a `query_limit` diagnostic.Derived qualified suggestions are sorted and deduplicated before pagination.+### Completion recovery++Completion first analyzes the query after replacing the identifier at the cursor.+If that parse fails, a query with complete CTE definitions can recover its outer scope when the SELECT list and FROM/JOIN sources remain parseable.+Recovery retains those source slices and discards the outer trailing clause, rather than guessing CTE fields or scanning aliases across scopes.+The shared analyzer still resolves projected fields, types, exact-case relation names, and known property origins.++With `|` marking the cursor, this incomplete query suggests `properties`:++```sql+WITH recent AS (SELECT uuid, properties FROM events)+SELECT recent.pro| FROM recent WHERE (+```++The cursor can also be inside the unfinished outer predicate:++```sql+WITH recent AS (SELECT properties AS props FROM events)+SELECT * FROM recent WHERE (recent.props.$br|+```++With `$browser` in the event property catalog, completion suggests that property.+A corresponding projection from `persons` uses the person property catalog instead.+The response keeps the original cursor-replaced `parseError`; validation still checks the original query and reports its syntax error.+Recovery never makes invalid SQL executable or changes the validation contract.+Supported trailing boundaries are WHERE, PREWHERE, GROUP BY, HAVING, ORDER BY, and LIMIT.++Recovery preserves SELECT aliases when their defining SELECT items survive parsing.+An outer predicate can see those aliases, but an earlier SELECT item cannot see a later alias.+The recovered cursor position preserves that distinction, including when the original cursor falls inside the discarded clause.+Recovered analysis uses the existing projection and field-lookup work limits.++For a single SELECT without WITH, the existing fallback recovers only a parseable FROM clause and does not reconstruct discarded SELECT aliases.+Neither fallback replaces successfully parsed bindings.+An unfinished block comment returns a parser error instead of blocking completion or validation.For example, `WITH recent AS (SELECT uuid FROM events) SELECT recent.uuid FROM recent WHERE /* unfinished` produces a `syntax_error` validation diagnostic.Completion before that comment returns a `parseError` without recovering CTE field suggestions; completion inside the comment remains disabled.@@ -119,16 +154,17 @@ Closed block comments and line comments at end of input remain valid.- Source-specific case-insensitive relation lookup remains unsupported. Python catalog nodes can opt in, for example for Snowflake, but the Go catalog payload does not carry that per-node flag. Supporting it requires publishing the metadata and implementing exact-match-first, opt-in fallback without merging distinct names. The service requires exact relation names until then; autocomplete prefix matching remains case-insensitive.- Physical field and property-key case sensitivity remain separate from relation-name resolution. This layer does not claim complete identifier-case parity with the Python resolver.-- 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.+- CTE recovery requires complete CTE definitions and a parseable outer SELECT/FROM prefix. Broken CTE bodies, missing CTE-closing parentheses, and incomplete SELECT or JOIN sources remain unsupported because they do not establish a reliable projected schema. Recovering those forms requires separate structural recovery for each damaged scope.+- Recovery does not target a cursor inside a CTE definition or FROM/JOIN source section. It also rejects queries with any nested SELECT in the outer query, including an intact FROM subquery or predicate subquery. Per-scope recovery must first preserve cursor ownership and alias visibility without importing sibling bindings.+- Set-operation and multi-statement recovery, scalar WITH declarations, and unterminated quoted tokens or comments remain excluded. These need separate statement/branch selection and lexical recovery rules before the service can infer bindings safely.- Property provenance covers direct containers only. Computed JSON expressions, nested JSON schemas, conflicting sources, and duplicate projected names do not establish a namespace. Completion suppresses property suggestions and validation skips property-name checks when the origin is unknown. Expression inference and ambiguous-column diagnostics remain follow-up work; duplicate source names produce `duplicate_table`.- Projecting a nested virtual container such as `e.person.properties AS props` does not retain provenance. Model virtual-table traversal before enabling those projected namespaces; existing direct physical property paths remain available.-- Select-alias recovery requires parseable cursor-replaced SQL. Single-SELECT recovery retains only FROM bindings and does not guess discarded aliases. Preserve SELECT items in a structured recovery pass before enabling those suggestions.+- Single-SELECT recovery without WITH retains only FROM bindings and does not guess discarded aliases. Extending SELECT-alias recovery there requires preserving its SELECT list and visibility positions as the CTE-aware path does.- SELECT-alias property provenance follows the existing visibility and case-sensitive precedence rules. An alias without a known container origin suppresses property-owner fallback; it does not inherit a namespace from a name such as `person` or `properties`.- Scalar WITH aliases, aliases inside expressions, ARRAY JOIN aliases, QUALIFY, and duplicate SELECT-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 field and type, but property provenance becomes unknown once the duplicate declaration is visible; earlier references retain their original provenance.- 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.- 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.+- CTE table-name suggestions in malformed FROM/JOIN clauses still require cursor replacement to produce parseable SQL. This recovery slice targets outer expression completion with intact sources; recovering incomplete source declarations needs its own scope and ambiguity checks.- 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.mdindex b4f2c39f7276..f16a3fbd34b4 100644--- a/services/hogql-language-service/README.md+++ b/services/hogql-language-service/README.md@@ -79,7 +79,10 @@ position with `"cursor":"<nextCursor>"` to retrieve it. The HTTP `Content-LengthThe parser currently accepts ClickHouse's `database.table` identifiers but not HogQL's three-part synced-table names.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.+Queries with complete CTE definitions can also retain their outer SELECT/FROM scope through unfinished trailing clauses, including completion inside an unfinished outer predicate.+This preserves derived fields, known property origins, and retained SELECT aliases.+Recovery excludes malformed CTE bodies, nested SELECTs in the outer query, FROM/JOIN cursor positions, and incomplete JOIN sources.+Validation still reports the original query's syntax errors.Completion and validation recognize explicit SELECT aliases in later SELECT items and clauses resolved after SELECT, including WHERE, GROUP BY, HAVING, and ORDER BY.Aliases stay within their defining query and do not appear in JOIN conditions.Computed and nested property provenance, additional alias forms, parser recovery, and other exclusions are tracked in [query analysis and remaining work](../../docs/internal/hogql-language-service.md#recovery-and-remaining-work).diff --git a/services/hogql-language-service/internal/completion/bindings.go b/services/hogql-language-service/internal/completion/bindings.goindex c8f7ee17458c..cfe9a999aa97 100644--- a/services/hogql-language-service/internal/completion/bindings.go+++ b/services/hogql-language-service/internal/completion/bindings.go@@ -12,7 +12,10 @@ func cursorBindings(schema *catalog.PreparedCatalog, query string, position int,document, parseErr := analysis.Analyze(schema, query)if parseErr != nil {parseErr = fmt.Errorf("parse incomplete SQL: %w", parseErr)- if recovered := recoverSingleSelect(query); recovered != "" {+ if recovered, recoveredPosition, ok := recoverCTEOuterSelect(query, position); ok {+ document, _ = analysis.Analyze(schema, recovered)+ position = recoveredPosition+ } else if recovered := recoverSingleSelect(query); recovered != "" {document, _ = analysis.Analyze(schema, recovered)position = len("SELECT ")}@@ -29,6 +32,108 @@ func cursorBindings(schema *catalog.PreparedCatalog, query string, position int,return document, analysis.Bindings{}, analysis.Relation{}, parseErr}+func recoverCTEOuterSelect(query string, position int) (string, int, bool) {+ tokens, _, incomplete := scanSQLTokens(query)+ if incomplete || len(tokens) == 0 || tokens[0].text != "WITH" || tokens[0].depth != 0 {+ return "", 0, false+ }+ outerSelect := -1+ from := -1+ boundary := -1+ for index, token := range tokens {+ if token.depth == 0 && (token.text == ";" || token.text == "UNION" || token.text == "EXCEPT" || token.text == "INTERSECT") {+ return "", 0, false+ }+ if token.kind != sqlTokenWord {+ continue+ }+ if token.text == "SELECT" {+ if token.depth == 0 {+ if outerSelect >= 0 {+ return "", 0, false+ }+ outerSelect = index+ } else if outerSelect >= 0 {+ return "", 0, false+ }+ }+ if outerSelect < 0 || token.depth != 0 {+ continue+ }+ if token.text == "FROM" && from < 0 {+ from = index+ continue+ }+ if from >= 0 && boundary < 0 {+ switch token.text {+ case "WHERE", "PREWHERE", "GROUP", "HAVING", "ORDER", "LIMIT":+ boundary = index+ }+ }+ }+ if outerSelect < 0 || from < 0 || boundary < 0 || position < tokens[outerSelect].start {+ return "", 0, false+ }+ if !hasCompleteTableCTEs(tokens[:outerSelect]) {+ return "", 0, false+ }++ retainedEnd := tokens[boundary].start+ if position >= tokens[from].start && position < retainedEnd {+ return "", 0, false+ }+ if position < retainedEnd {+ return query[:retainedEnd], position, true+ }+ recovered := query[:retainedEnd]+ if retainedEnd == 0 || !isSQLSpace(query[retainedEnd-1]) {+ recovered += " "+ }+ // Map discarded expressions into the outer predicate so SELECT aliases keep their normal visibility.+ recovered += "WHERE 0"+ return recovered, len(recovered) - 1, true+}++func isSQLSpace(value byte) bool {+ switch value {+ case ' ', '\t', '\r', '\n':+ return true+ }+ return false+}++func hasCompleteTableCTEs(tokens []sqlToken) bool {+ for index := 1; index < len(tokens); {+ if tokens[index].kind != sqlTokenWord || tokens[index].depth != 0 {+ return false+ }+ index+++ if index >= len(tokens) || tokens[index].text != "AS" || tokens[index].depth != 0 {+ return false+ }+ index+++ if index >= len(tokens) || tokens[index].kind != sqlTokenLeftParen || tokens[index].depth != 0 {+ return false+ }+ index+++ for index < len(tokens) && !(tokens[index].kind == sqlTokenRightParen && tokens[index].depth == 0) {+ index+++ }+ if index >= len(tokens) {+ return false+ }+ index+++ if index == len(tokens) {+ return true+ }+ if tokens[index].kind != sqlTokenComma || tokens[index].depth != 0 {+ return false+ }+ index+++ }+ return false+}+// Incomplete predicates can retain a parsed FROM clause only when no other query scope exists.func recoverSingleSelect(query string) string {tokens, _, incomplete := scanSQLTokens(query)diff --git a/services/hogql-language-service/internal/completion/completion_test.go b/services/hogql-language-service/internal/completion/completion_test.goindex 5e86a47cc323..8a5de80b772c 100644--- a/services/hogql-language-service/internal/completion/completion_test.go+++ b/services/hogql-language-service/internal/completion/completion_test.go@@ -9,6 +9,7 @@ import ("strings""testing""time"+ "unicode/utf16""github.com/PostHog/posthog/services/hogql-language-service/internal/catalog""github.com/PostHog/posthog/services/hogql-language-service/internal/querylimits"@@ -19,7 +20,7 @@ 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"},+ "properties": {Name: "properties", Type: "json"}, "timestamp": {Name: "timestamp", Type: "datetime"},}},"Events": {Name: "Events", Type: "data_warehouse", Fields: map[string]catalog.Field{"custom_field": {Name: "custom_field", Type: "string"}, "properties": {Name: "properties", Type: "json"},@@ -36,8 +37,8 @@ func testCatalog() *catalog.PreparedCatalog {"synced_id": {Name: "synced_id", Type: "string"},}},}, Properties: map[string][]catalog.Property{- "event": {{Name: "$geo_city", ValueType: "String"}, {Name: "$geo_country", ValueType: "String"}, {Name: "$Geo_Region", ValueType: "String"}},- "person": {{Name: "$geo_city", ValueType: "String"}},+ "event": {{Name: "$browser", ValueType: "String"}, {Name: "$geo_city", ValueType: "String"}, {Name: "$geo_country", ValueType: "String"}, {Name: "$Geo_Region", ValueType: "String"}},+ "person": {{Name: "$geo_city", ValueType: "String"}, {Name: "email", ValueType: "String"}},"session": {{Name: "$entry_current_url", ValueType: "String"}},"group:0": {{Name: "industry", ValueType: "String"}},}})@@ -256,12 +257,156 @@ func TestCompletesFieldsForAlias(t *testing.T) {}}+func TestRecoversCTEBindingsForIncompleteOuterClause(t *testing.T) {+ for _, test := range []struct {+ name, source, label, detail string+ encoding PositionEncoding+ }{+ {name: "cursor in select", source: "WITH recent AS (SELECT uuid, properties FROM events) SELECT recent.pro| FROM recent WHERE (", label: "properties", detail: "json"},+ {name: "cursor in predicate", source: "WITH recent AS (SELECT uuid, properties FROM events) SELECT uuid FROM recent WHERE (recent.pro|", label: "properties", detail: "json"},+ {name: "chain alias and renamed field", source: "WITH base AS (SELECT uuid, timestamp FROM events), recent AS (SELECT uuid, timestamp AS happened_at FROM base) SELECT r.hap| FROM recent AS r WHERE (", label: "happened_at", detail: "datetime"},+ {name: "wildcard", source: "WITH recent AS (SELECT * FROM events) SELECT recent.uu| FROM recent WHERE uuid =", label: "uuid", detail: "string"},+ {name: "unqualified chain field", source: "WITH base AS (SELECT uuid FROM events), recent AS (SELECT uuid FROM base) SELECT uu| FROM recent WHERE (", label: "uuid", detail: "string"},+ {name: "quoted exact case", source: "WITH `Recent` AS (SELECT uuid AS `EventID` FROM events) SELECT R.Eve| FROM `Recent` AS R WHERE (", label: "EventID", detail: "string"},+ {name: "prewhere", source: "WITH recent AS (SELECT uuid FROM events) SELECT recent.uu| FROM recent PREWHERE (", label: "uuid", detail: "string"},+ {name: "group by", source: "WITH recent AS (SELECT uuid FROM events) SELECT recent.uu| FROM recent GROUP BY (", label: "uuid", detail: "string"},+ {name: "having", source: "WITH recent AS (SELECT uuid FROM events) SELECT recent.uu| FROM recent HAVING (", label: "uuid", detail: "string"},+ {name: "order by", source: "WITH recent AS (SELECT uuid FROM events) SELECT recent.uu| FROM recent ORDER BY (", label: "uuid", detail: "string"},+ {name: "limit", source: "WITH recent AS (SELECT uuid FROM events) SELECT recent.uu| FROM recent LIMIT (", label: "uuid", detail: "string"},+ {name: "comments and keyword strings", source: "WITH recent AS (SELECT uuid FROM events WHERE event = 'FROM WHERE'), /* SELECT FROM */ next AS (SELECT uuid FROM recent) SELECT next.uu| FROM next WHERE (", label: "uuid", detail: "string"},+ {name: "unicode utf8", source: "WITH `Σ` AS (SELECT uuid FROM events) SELECT '😀', `Σ`.uu| FROM `Σ` WHERE (", label: "uuid", detail: "string", encoding: PositionEncodingUTF8},+ {name: "unicode utf16", source: "WITH `Σ` AS (SELECT uuid FROM events) SELECT '😀', `Σ`.uu| FROM `Σ` WHERE (", label: "uuid", detail: "string", encoding: PositionEncodingUTF16},+ } {+ t.Run(test.name, func(t *testing.T) {+ bytePosition := strings.IndexByte(test.source, '|')+ query := strings.Replace(test.source, "|", "", 1)+ position := bytePosition+ if test.encoding == "" {+ test.encoding = PositionEncodingUTF8+ }+ if test.encoding == PositionEncodingUTF16 {+ position = len(utf16.Encode([]rune(query[:bytePosition])))+ }+ result, err := Complete(testCatalog(), query, position, test.encoding, "")+ if err != nil {+ t.Fatal(err)+ }+ if result.ParseError == "" {+ t.Fatal("expected the original incomplete query to retain its parse error")+ }+ suggestion, ok := findSuggestion(result.Suggestions, test.label)+ if !ok || suggestion.Detail != test.detail {+ t.Fatalf("result = %#v", result)+ }+ })+ }+}++func TestIncompleteOuterQueryRemainsInvalidForValidation(t *testing.T) {+ for _, suffix := range []string{"(", "/* unfinished"} {+ t.Run(suffix, func(t *testing.T) {+ incomplete := "WITH recent AS (SELECT uuid FROM events) SELECT recent.uuid FROM recent WHERE " + suffix+ checked := validation.Validate(testCatalog(), incomplete)+ if checked.Valid || len(checked.Diagnostics) != 1 || checked.Diagnostics[0].Code != "syntax_error" {+ t.Fatalf("validation accepted the incomplete source: %#v", checked)+ }+ })+ }+}++func TestIncompleteOuterRecoveryKeepsSelectAliasVisibility(t *testing.T) {+ for _, test := range []struct {+ name, source, expected, excluded string+ }{+ {name: "where sees prior alias", source: "WITH recent AS (SELECT uuid FROM events) SELECT uuid AS event_id FROM recent WHERE (eve|", expected: "event_id"},+ {name: "earlier select item does not see later alias", source: "WITH recent AS (SELECT uuid FROM events) SELECT eve|, uuid AS event_id FROM recent WHERE (", excluded: "event_id"},+ {name: "from does not see select alias", source: "WITH recent AS (SELECT uuid FROM events) SELECT uuid AS event_id FROM eve| WHERE (", excluded: "event_id"},+ } {+ t.Run(test.name, func(t *testing.T) {+ position := strings.IndexByte(test.source, '|')+ query := strings.Replace(test.source, "|", "", 1)+ result, err := Complete(testCatalog(), query, position, PositionEncodingUTF8, "")+ if err != nil {+ t.Fatal(err)+ }+ if test.expected != "" {+ if _, ok := findSuggestion(result.Suggestions, test.expected); !ok {+ t.Fatalf("result = %#v", result)+ }+ }+ if test.excluded != "" {+ if _, ok := findSuggestion(result.Suggestions, test.excluded); ok {+ t.Fatalf("result leaked %q: %#v", test.excluded, result)+ }+ }+ })+ }+}++func TestRecoversPropertyOriginsForIncompleteOuterClause(t *testing.T) {+ for _, test := range []struct {+ name, source, expected, excluded string+ }{+ {name: "event property", source: "WITH unused AS (SELECT properties AS props FROM persons), recent AS (SELECT properties AS props FROM events) SELECT recent.props.$geo_c| FROM recent WHERE uuid =", expected: "$geo_country", excluded: "email"},+ {name: "person property", source: "WITH unused AS (SELECT properties AS props FROM events), recent AS (SELECT properties AS props FROM persons) SELECT recent.props.$geo_c| FROM recent WHERE id =", expected: "$geo_city", excluded: "$geo_country"},+ } {+ t.Run(test.name, func(t *testing.T) {+ position := strings.IndexByte(test.source, '|')+ query := strings.Replace(test.source, "|", "", 1)+ result, err := Complete(testCatalog(), query, position, PositionEncodingUTF8, "")+ if err != nil {+ t.Fatal(err)+ }+ if _, ok := findSuggestion(result.Suggestions, test.expected); result.ParseError == "" || !ok {+ t.Fatalf("result = %#v", result)+ }+ if _, ok := findSuggestion(result.Suggestions, test.excluded); ok {+ t.Fatalf("result leaked %q: %#v", test.excluded, result)+ }+ })+ }+}++func TestDoesNotRecoverUnsupportedIncompleteCTEScopes(t *testing.T) {+ for _, test := range []struct {+ name, source, excluded string+ }{+ {name: "damaged cte", source: "WITH recent AS (SELECT uuid FROM events WHERE ( SELECT recent.uu| FROM recent WHERE (", excluded: "uuid"},+ {name: "missing cte close", source: "WITH recent AS (SELECT uuid FROM events SELECT recent.uu| FROM recent WHERE (", excluded: "uuid"},+ {name: "cursor in cte", source: "WITH recent AS (SELECT uu| FROM events) SELECT * FROM recent WHERE (", excluded: "uuid"},+ {name: "nested outer select", source: "WITH recent AS (SELECT uuid FROM events) SELECT * FROM (SELECT recent.uu| FROM recent) AS nested WHERE (", excluded: "uuid"},+ {name: "incomplete join source", source: "WITH recent AS (SELECT uuid FROM events) SELECT recent.uu| FROM recent JOIN WHERE (", excluded: "uuid"},+ {name: "incomplete join condition", source: "WITH recent AS (SELECT uuid FROM events) SELECT recent.uu| FROM recent JOIN events ON ( WHERE (", excluded: "uuid"},+ {name: "set operation", source: "WITH recent AS (SELECT uuid FROM events) SELECT recent.uu| FROM recent UNION SELECT uuid FROM events WHERE (", excluded: "uuid"},+ {name: "multiple statements", source: "WITH recent AS (SELECT uuid FROM events) SELECT recent.uu| FROM recent; SELECT * FROM events WHERE (", excluded: "uuid"},+ {name: "scalar with alias", source: "WITH 1 AS recent SELECT events.uu| FROM events WHERE (", excluded: "uuid"},+ {name: "unterminated comment after cursor", source: "WITH recent AS (SELECT uuid FROM events) SELECT recent.uu| FROM recent WHERE /* unfinished", excluded: "uuid"},+ } {+ t.Run(test.name, func(t *testing.T) {+ position := strings.IndexByte(test.source, '|')+ query := strings.Replace(test.source, "|", "", 1)+ result, err := Complete(testCatalog(), query, position, PositionEncodingUTF8, "")+ if err != nil {+ t.Fatal(err)+ }+ if result.ParseError == "" {+ t.Fatalf("incomplete query lost its parse error: %#v", result)+ }+ if _, ok := findSuggestion(result.Suggestions, test.excluded); ok {+ t.Fatalf("result recovered unsupported scope: %#v", result)+ }+ })+ }+}+func TestCompletesScopedProjections(t *testing.T) {for _, test := range []struct {name, query stringfields 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"}},+ {"closed comment after cursor", "WITH t AS (SELECT uuid FROM events) SELECT t.uu| FROM t /* finished */", map[string]string{"uuid": "string"}},+ {"line comment at eof after cursor", "WITH t AS (SELECT uuid FROM events) SELECT t.uu| FROM t -- finished", map[string]string{"uuid": "string"}},{"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"}},@@ -425,6 +570,12 @@ func TestDerivedLookupWork(t *testing.T) {} else if known, ok := findSuggestion(result.Suggestions, "known"); err != nil || !ok || known.Detail != "float" {t.Fatalf("result = %#v, err = %v", result, err)}+ if test.limit {+ result, err = Complete(testCatalog(), query+" WHERE (", position, PositionEncodingUTF8, "")+ if !errors.Is(err, querylimits.ErrFieldLookupTooLarge) || len(result.Suggestions) != 0 {+ t.Fatalf("incomplete result = %#v, err = %v", result, err)+ }+ }})}}@@ -527,9 +678,11 @@ func TestProjectionPaginationAndLimits(t *testing.T) {}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)+ for _, suffix := range []string{" FROM c14", " FROM c14 WHERE ("} {+ _, err := Complete(testCatalog(), prefix+suffix, len(prefix), PositionEncodingUTF8, "")+ if !errors.Is(err, querylimits.ErrCTEProjectionTooLarge) {+ t.Fatalf("projection %q, suffix %q: err = %v", projection, suffix, err)+ }}}}diff --git a/services/hogql-language-service/internal/completion/context.go b/services/hogql-language-service/internal/completion/context.goindex 67d3aae7db03..7725f7484d32 100644--- a/services/hogql-language-service/internal/completion/context.go+++ b/services/hogql-language-service/internal/completion/context.go@@ -36,6 +36,7 @@ type sqlToken struct {raw stringkind sqlTokenKinddepth int+ start int}func analyzeCursorContext(input string) completionMode {@@ -275,7 +276,7 @@ func scanSQLTokens(input string) ([]sqlToken, int, bool) {if character != '\'' {kind = sqlTokenWord}- tokens = append(tokens, sqlToken{text: strings.ToUpper(input[index:end]), raw: input[index:end], kind: kind, depth: depth})+ tokens = append(tokens, sqlToken{text: strings.ToUpper(input[index:end]), raw: input[index:end], kind: kind, depth: depth, start: index})index = endcontinue}@@ -288,7 +289,7 @@ func scanSQLTokens(input string) ([]sqlToken, int, bool) {}end += size}- tokens = append(tokens, sqlToken{text: strings.ToUpper(input[index:end]), raw: input[index:end], kind: sqlTokenWord, depth: depth})+ tokens = append(tokens, sqlToken{text: strings.ToUpper(input[index:end]), raw: input[index:end], kind: sqlTokenWord, depth: depth, start: index})index = endcontinue}@@ -297,27 +298,27 @@ func scanSQLTokens(input string) ([]sqlToken, int, bool) {for end < len(input) && ((input[end] >= '0' && input[end] <= '9') || input[end] == '.') {end++}- tokens = append(tokens, sqlToken{text: input[index:end], raw: input[index:end], kind: sqlTokenValue, depth: depth})+ tokens = append(tokens, sqlToken{text: input[index:end], raw: input[index:end], kind: sqlTokenValue, depth: depth, start: index})index = endcontinue}switch character {case '(':- tokens = append(tokens, sqlToken{text: "(", raw: "(", kind: sqlTokenLeftParen, depth: depth})+ tokens = append(tokens, sqlToken{text: "(", raw: "(", kind: sqlTokenLeftParen, depth: depth, start: index})depth++index++case ')':if depth > 0 {depth--}- tokens = append(tokens, sqlToken{text: ")", raw: ")", kind: sqlTokenRightParen, depth: depth})+ tokens = append(tokens, sqlToken{text: ")", raw: ")", kind: sqlTokenRightParen, depth: depth, start: index})index++case ',':- tokens = append(tokens, sqlToken{text: ",", raw: ",", kind: sqlTokenComma, depth: depth})+ tokens = append(tokens, sqlToken{text: ",", raw: ",", kind: sqlTokenComma, depth: depth, start: index})index++default:end := operatorEnd(input, index)- tokens = append(tokens, sqlToken{text: strings.ToUpper(input[index:end]), raw: input[index:end], kind: sqlTokenOperator, depth: depth})+ tokens = append(tokens, sqlToken{text: strings.ToUpper(input[index:end]), raw: input[index:end], kind: sqlTokenOperator, depth: depth, start: index})index = end}}