: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
fix(hogql): complete join clauses and boolean literals (#102865)
Paweł Szczurbb742e7c7ea3
diff --git a/docs/internal/hogql-language-service-demo.md b/docs/internal/hogql-language-service-demo.mdindex f4177aa0d3b4..1447f3b1b407 100644--- a/docs/internal/hogql-language-service-demo.md+++ b/docs/internal/hogql-language-service-demo.md@@ -93,6 +93,12 @@ The demo does not send feedback anywhere automatically.`services/hogql-language-service/cmd/demo/catalog.go` defines a hand-maintained subset of the public HogQL schema shapes for `events`, `persons`, `sessions`, and `groups`.It also defines invented `postgres.demo.orders` and `demo_customers` warehouse tables, event/person/session/group property namespaces, and 35 `demo_property_*` names for pagination.+The **CTE join and boolean filters** example joins daily event counts to an invented `demo_rules` table.+It exercises two CTEs, projected fields, and `TRUE` and `FALSE` filters.+Load it and validate, then complete after `counts.` or `rules.` to inspect the projected fields.+The starting cursor is before `day`, so selecting another suggestion replaces that field without making the initial query incomplete.+To test clause suggestions, add a blank line after the JOIN condition and before ORDER BY; completion there includes WHERE.+The catalog supplies physical field types only; computed result types may remain unknown, and the Go service does not return Python metadata notices.Only names and types are present; there are no event rows, person records, customer examples, or production schema exports.The sidebar and `/api/catalog` display the exact catalog published to the service.To change it, edit `catalog.go` and restart the command.diff --git a/docs/internal/hogql-language-service.md b/docs/internal/hogql-language-service.mdindex 063144c7f5d8..406f7da875fb 100644--- a/docs/internal/hogql-language-service.md+++ b/docs/internal/hogql-language-service.md@@ -43,8 +43,21 @@ Completion replaces the identifier at the cursor with a placeholder and resolvesAn 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.+After a completed JOIN ON condition, completion includes WHERE, including before an existing ORDER BY clause.+For example, `SELECT * FROM events AS e JOIN events AS other ON e.uuid = other.uuid |` offers WHERE at `|`.+Completion does not offer WHERE inside unfinished ON parentheses or between the bounds of BETWEEN.+Completion also keeps query clauses out of unfinished CASE expressions.+Before another JOIN at the same query scope, an ON condition offers only AND and OR as clause continuations while retaining applicable comparison operators.+For example, `SELECT * FROM events AS e JOIN events AS other ON e.uuid = other.uuid | JOIN persons AS p ON 1 = 1` offers AND and OR at `|`, but not WHERE, GROUP BY, ORDER BY, or LIMIT.+Nested JOINs, comments, strings, and later statements do not suppress a valid WHERE suggestion.+Other clauses already present after the cursor are not globally filtered from suggestions.+An incomplete cursor placeholder can still produce a `parseError` alongside these keyword suggestions.+Unquoted TRUE and FALSE are boolean literals, regardless of case, and validation does not look them up as fields.+For example, `SELECT uuid FROM events WHERE TRUE AND NOT FALSE` validates without unknown-field errors.+Expression completion offers TRUE and FALSE, including when typing `tr` or `fa` after a comparison operator.+Quoted or qualified names such as `events.TRUE` remain field references and require a matching catalog field.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.+Direct field projections retain catalog types, and boolean literals project as `boolean`; other 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`.diff --git a/services/hogql-language-service/cmd/demo/assets/app.js b/services/hogql-language-service/cmd/demo/assets/app.jsindex 48d39f4411c9..62dbc980511a 100644--- a/services/hogql-language-service/cmd/demo/assets/app.js+++ b/services/hogql-language-service/cmd/demo/assets/app.js@@ -16,6 +16,31 @@ const examples = [query: 'WITH recent AS (\n SELECT uuid, event AS event_name FROM events\n)\nSELECT recent.§ FROM recent',note: 'Probe CTE completion. Missing projected suggestions are a service limitation.',},+ {+ name: 'CTE join and boolean filters',+ query: `WITH counts AS (+ SELECT+ toDate(timestamp) AS day,+ count() AS event_count+ FROM events+ GROUP BY day+), rules AS (+ SELECT+ active_day,+ display_name+ FROM demo_rules+ WHERE is_enabled = TRUE+ AND is_archived = FALSE+)+SELECT+ counts.§day,+ counts.event_count,+ rules.display_name+FROM counts+LEFT JOIN rules ON counts.day = rules.active_day+ORDER BY counts.day`,+ note: 'Complete after counts. or rules. to inspect projected fields. Validate TRUE and FALSE boolean filters.',+ },{name: 'Subquery completion',query: 'SELECT nested.§\nFROM (SELECT person_id, count() AS event_count FROM events GROUP BY person_id) AS nested',diff --git a/services/hogql-language-service/cmd/demo/catalog.go b/services/hogql-language-service/cmd/demo/catalog.goindex 13d73bae7440..c225b34bc4f6 100644--- a/services/hogql-language-service/cmd/demo/catalog.go+++ b/services/hogql-language-service/cmd/demo/catalog.go@@ -45,6 +45,9 @@ func syntheticCatalog() catalogPublication {demoTable("demo_customers", "data_warehouse", map[string]string{"id": "integer", "email": "string", "plan": "string", "billing address": "string", "café": "string",}),+ demoTable("demo_rules", "data_warehouse", map[string]string{+ "active_day": "date", "display_name": "string", "is_enabled": "boolean", "is_archived": "boolean",+ }),} {tables[table.Name] = table}@@ -68,5 +71,5 @@ func syntheticCatalog() catalogPublication {for index := range 35 {properties["event"] = append(properties["event"], catalog.Property{Name: fmt.Sprintf("demo_property_%02d", index), ValueType: "String"})}- return catalogPublication{Revision: "synthetic-demo-v1", Catalog: catalog.Catalog{Tables: tables, Properties: properties}}+ return catalogPublication{Revision: "synthetic-demo-v2", Catalog: catalog.Catalog{Tables: tables, Properties: properties}}}diff --git a/services/hogql-language-service/internal/analysis/literals.go b/services/hogql-language-service/internal/analysis/literals.gonew file mode 100644index 000000000000..71608d2170cc--- /dev/null+++ b/services/hogql-language-service/internal/analysis/literals.go@@ -0,0 +1,11 @@+package analysis++import (+ "strings"++ clickhouse "github.com/orian/clickhouse-sql-parser/parser"+)++func IsBooleanLiteral(ident *clickhouse.Ident) bool {+ return ident.QuoteType == clickhouse.Unquoted && (strings.EqualFold(ident.Name, "TRUE") || strings.EqualFold(ident.Name, "FALSE"))+}diff --git a/services/hogql-language-service/internal/analysis/scopes.go b/services/hogql-language-service/internal/analysis/scopes.goindex 50eaf5e0f5d7..cc39dea14739 100644--- a/services/hogql-language-service/internal/analysis/scopes.go+++ b/services/hogql-language-service/internal/analysis/scopes.go@@ -565,6 +565,9 @@ func projectedPropertyNamespace(scope *queryScope, expr clickhouse.Expr, positiobindings := visibleBindings(scope)switch typed := expr.(type) {case *clickhouse.Ident:+ if IsBooleanLiteral(typed) {+ return "", false+ }if alias, ok := (Bindings{scope: scope, position: position}).selectAlias(typed.Name); ok {return alias.propertyNamespace, alias.propertyNamespace != ""}@@ -623,6 +626,9 @@ func projectedType(scope *queryScope, expr clickhouse.Expr) string {bindings := visibleBindings(scope)switch typed := expr.(type) {case *clickhouse.Ident:+ if IsBooleanLiteral(typed) {+ return "boolean"+ }if field, ok := (Bindings{scope: scope, position: int(expr.Pos())}).SelectAlias(typed.Name); ok {return field.Type}diff --git a/services/hogql-language-service/internal/completion/completion.go b/services/hogql-language-service/internal/completion/completion.goindex 601a392a6419..6c308ccef667 100644--- a/services/hogql-language-service/internal/completion/completion.go+++ b/services/hogql-language-service/internal/completion/completion.go@@ -46,6 +46,9 @@ var keywords = []string{"SELECT", "FROM", "WHERE", "GROUP BY", "ORDER BY", "LIMIvar queryStarters = []catalog.Entry{{Name: "SELECT"}, {Name: "WITH"}}var betweenSeparator = []string{"AND"}var predicateContinuations = []string{"AND", "OR", "GROUP BY", "ORDER BY", "LIMIT"}+var joinPredicateContinuations = []string{"AND", "OR", "WHERE", "GROUP BY", "ORDER BY", "LIMIT"}+var joinPredicateContinuationsBeforeJoin = []string{"AND", "OR"}+var caseExpressionKeywords = []string{"CASE", "WHEN", "THEN", "ELSE", "END", "NULL", "TRUE", "FALSE", "NOT"}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_$]*$`)@@ -140,18 +143,35 @@ func Complete(schema *catalog.PreparedCatalog, query string, position int, positsuggestions = appendNamed(suggestions, betweenSeparator, lowerPrefix, "keyword", "")} else if mode == completionModePredicateContinuation {suggestions = appendNamed(suggestions, predicateContinuations, lowerPrefix, "keyword", "")+ } else if mode == completionModeJoinPredicateContinuation {+ continuations := joinPredicateContinuations+ if laterJoinAtCursor(query, position) {+ continuations = joinPredicateContinuationsBeforeJoin+ }+ suggestions = appendNamed(suggestions, continuations, lowerPrefix, "keyword", "")} else if mode == completionModePostExpression {suggestions = appendNamed(suggestions, comparisonOperators, lowerPrefix, "operator", "")suggestions = appendNamed(suggestions, predicateContinuations, lowerPrefix, "keyword", "")+ } else if mode == completionModeJoinPostExpression {+ suggestions = appendNamed(suggestions, comparisonOperators, lowerPrefix, "operator", "")+ continuations := joinPredicateContinuations+ if laterJoinAtCursor(query, position) {+ continuations = joinPredicateContinuationsBeforeJoin+ }+ suggestions = appendNamed(suggestions, continuations, lowerPrefix, "keyword", "")} else {suggestions = fieldSuggestions(bindings, lowerPrefix)if document != nil && document.LimitError() != nil {return Result{}, document.LimitError()}- if mode == completionModeExpression {+ if mode == completionModeExpression || mode == completionModeCaseExpression {suggestions = appendFunctions(suggestions, lowerPrefix)}- for _, keyword := range keywords {+ availableKeywords := keywords+ if mode == completionModeCaseExpression {+ availableKeywords = caseExpressionKeywords+ }+ for _, keyword := range availableKeywords {if hasLowerPrefix(keyword, lowerPrefix) {suggestions = append(suggestions, Suggestion{Label: keyword, Kind: "keyword"})}@@ -191,6 +211,11 @@ func Complete(schema *catalog.PreparedCatalog, query string, position int, positreturn result, nil}+func laterJoinAtCursor(query string, position int) bool {+ _, cursorDepth, _ := scanSQLTokens(query[:position])+ return hasLaterJoinAtDepth(query[position:], cursorDepth)+}+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)) + "-"diff --git a/services/hogql-language-service/internal/completion/completion_test.go b/services/hogql-language-service/internal/completion/completion_test.goindex 8a5de80b772c..e76d92cc78e0 100644--- a/services/hogql-language-service/internal/completion/completion_test.go+++ b/services/hogql-language-service/internal/completion/completion_test.go@@ -405,6 +405,7 @@ func TestCompletesScopedProjections(t *testing.T) {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"}},+ {"boolean literal type", "WITH t AS (SELECT TRUE AS enabled FROM events) SELECT t.| FROM t", map[string]string{"enabled": "boolean"}},{"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"}},@@ -463,6 +464,7 @@ func TestCompletesScopedProjections(t *testing.T) {{"inner alias hides outer property source", "SELECT (SELECT properties.$geo| FROM persons AS e) FROM events AS e", map[string]string{"$geo_city": "String"}},{"duplicate projected properties", "WITH t AS (SELECT events.properties, events.properties FROM events) SELECT t.properties.$geo| FROM t", nil},{"scalar property leaf has no provenance", "WITH t AS (SELECT properties.$geo_city AS city FROM events) SELECT t.city.$geo| FROM t", nil},+ {"boolean literal does not inherit alias provenance", "WITH t AS (SELECT properties AS TRUE, TRUE AS enabled FROM events) SELECT t.enabled.$geo| FROM t", nil},{"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"}},@@ -834,6 +836,7 @@ func TestCompletesSQLSyntaxForCursorContext(t *testing.T) {label stringkind stringinsertText string+ required []stringexcluded []stringtotal int}{@@ -847,8 +850,36 @@ func TestCompletesSQLSyntaxForCursorContext(t *testing.T) {{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()"},+ {name: "true after operator", query: "SELECT * FROM orders WHERE amount = tr", position: len("SELECT * FROM orders WHERE amount = tr"), label: "TRUE", kind: "keyword"},+ {name: "false after operator", query: "SELECT * FROM orders WHERE amount = fa", position: len("SELECT * FROM orders WHERE amount = fa"), label: "FALSE", kind: "keyword"},{name: "operator after field", query: "SELECT * FROM orders WHERE amount ", position: len("SELECT * FROM orders WHERE amount "), label: "=", kind: "operator", insertText: "=", excluded: []string{"AND"}},- {name: "boolean after predicate", query: "SELECT * FROM orders WHERE amount > 0 ", position: len("SELECT * FROM orders WHERE amount > 0 "), label: "AND", kind: "keyword", insertText: "AND", excluded: []string{"="}},+ {name: "boolean after predicate", query: "SELECT * FROM orders WHERE amount > 0 ", position: len("SELECT * FROM orders WHERE amount > 0 "), label: "AND", kind: "keyword", insertText: "AND", excluded: []string{"=", "WHERE"}},+ {name: "where after join predicate", query: "SELECT * FROM events AS e JOIN events AS other ON e.uuid = other.uuid ", position: len("SELECT * FROM events AS e JOIN events AS other ON e.uuid = other.uuid "), label: "WHERE", kind: "keyword", insertText: "WHERE"},+ {name: "where prefix after join predicate", query: "SELECT * FROM events AS e JOIN events AS other ON e.uuid = other.uuid wh", position: len("SELECT * FROM events AS e JOIN events AS other ON e.uuid = other.uuid wh"), label: "WHERE", kind: "keyword", insertText: "WHERE", total: 1},+ {name: "where after parenthesized join predicate", query: "SELECT * FROM events AS e JOIN events AS other ON (e.uuid = other.uuid) ", position: len("SELECT * FROM events AS e JOIN events AS other ON (e.uuid = other.uuid) "), label: "WHERE", kind: "keyword", insertText: "WHERE"},+ {name: "no where inside join parentheses", query: "SELECT * FROM events AS e JOIN events AS other ON (e.uuid = other.uuid ", position: len("SELECT * FROM events AS e JOIN events AS other ON (e.uuid = other.uuid "), label: "AND", kind: "keyword", insertText: "AND", excluded: []string{"WHERE"}},+ {name: "no where within join between bounds", query: "SELECT * FROM orders AS a JOIN orders AS b ON a.amount BETWEEN 1 ", position: len("SELECT * FROM orders AS a JOIN orders AS b ON a.amount BETWEEN 1 "), label: "AND", kind: "keyword", insertText: "AND", total: 1},+ {name: "where after joined ctes before order by", query: "WITH a AS (SELECT uuid FROM events WHERE event = 'demo'), b AS (SELECT uuid FROM events) SELECT a.uuid FROM a LEFT JOIN b ON a.uuid = b.uuid\n\nORDER BY a.uuid", position: len("WITH a AS (SELECT uuid FROM events WHERE event = 'demo'), b AS (SELECT uuid FROM events) SELECT a.uuid FROM a LEFT JOIN b ON a.uuid = b.uuid\n"), label: "WHERE", kind: "keyword", insertText: "WHERE"},+ {name: "only boolean continuations after join predicate before later join", query: "SELECT * FROM events AS e JOIN events AS other ON e.uuid = other.uuid JOIN persons AS p ON 1 = 1", position: len("SELECT * FROM events AS e JOIN events AS other ON e.uuid = other.uuid "), label: "AND", kind: "keyword", insertText: "AND", required: []string{"OR"}, excluded: []string{"WHERE", "GROUP BY", "ORDER BY", "LIMIT"}, total: 2},+ {name: "comparison and boolean continuations after join expression before later join", query: "SELECT * FROM events AS e JOIN events AS other ON TRUE JOIN persons AS p ON 1 = 1", position: len("SELECT * FROM events AS e JOIN events AS other ON TRUE "), label: "=", kind: "operator", insertText: "=", required: []string{"AND", "OR"}, excluded: []string{"WHERE", "GROUP BY", "ORDER BY", "LIMIT"}},+ {name: "nested later join does not suppress where", query: "SELECT * FROM events AS e JOIN events AS other ON e.uuid = other.uuid ORDER BY (SELECT 1 FROM events JOIN persons ON 1 = 1)", position: len("SELECT * FROM events AS e JOIN events AS other ON e.uuid = other.uuid "), label: "WHERE", kind: "keyword", insertText: "WHERE"},+ {name: "join in comment does not suppress where", query: "SELECT * FROM events AS e JOIN events AS other ON e.uuid = other.uuid /* JOIN persons */ ORDER BY e.uuid", position: len("SELECT * FROM events AS e JOIN events AS other ON e.uuid = other.uuid "), label: "WHERE", kind: "keyword", insertText: "WHERE"},+ {name: "join in string does not suppress where", query: "SELECT * FROM events AS e JOIN events AS other ON e.uuid = other.uuid ORDER BY 'JOIN persons'", position: len("SELECT * FROM events AS e JOIN events AS other ON e.uuid = other.uuid "), label: "WHERE", kind: "keyword", insertText: "WHERE"},+ {name: "join in later statement does not suppress where", query: "SELECT * FROM events AS e JOIN events AS other ON e.uuid = other.uuid ; SELECT * FROM events JOIN persons ON 1 = 1", position: len("SELECT * FROM events AS e JOIN events AS other ON e.uuid = other.uuid "), label: "WHERE", kind: "keyword", insertText: "WHERE"},+ {name: "join in next union branch does not suppress where", query: "SELECT * FROM events AS e JOIN events AS other ON e.uuid = other.uuid UNION ALL SELECT * FROM events JOIN persons ON 1 = 1", position: len("SELECT * FROM events AS e JOIN events AS other ON e.uuid = other.uuid "), label: "WHERE", kind: "keyword", insertText: "WHERE"},+ {name: "no clauses inside unfinished join case", query: "SELECT * FROM orders AS a JOIN orders AS b ON a.amount = CASE WHEN b.amount > 0 ", position: len("SELECT * FROM orders AS a JOIN orders AS b ON a.amount = CASE WHEN b.amount > 0 "), label: "THEN", kind: "keyword", excluded: []string{"WHERE", "GROUP BY", "ORDER BY", "LIMIT"}},+ {name: "function inside unfinished join case", query: "SELECT * FROM orders AS a JOIN orders AS b ON a.amount = CASE WHEN b.amount > 0 THEN cou", position: len("SELECT * FROM orders AS a JOIN orders AS b ON a.amount = CASE WHEN b.amount > 0 THEN cou"), label: "count", kind: "function", insertText: "count()", excluded: []string{"WHERE"}},+ {name: "no clauses inside parenthesized join case condition", query: "SELECT * FROM orders AS a JOIN orders AS b ON CASE WHEN (", position: len("SELECT * FROM orders AS a JOIN orders AS b ON CASE WHEN ("), label: "count", kind: "function", insertText: "count()", excluded: []string{"WHERE", "GROUP BY", "ORDER BY", "LIMIT"}},+ {name: "no clauses inside join case function", query: "SELECT * FROM orders AS a JOIN orders AS b ON a.amount = CASE WHEN b.amount > 0 THEN coalesce(", position: len("SELECT * FROM orders AS a JOIN orders AS b ON a.amount = CASE WHEN b.amount > 0 THEN coalesce("), label: "count", kind: "function", insertText: "count()", excluded: []string{"WHERE", "GROUP BY", "ORDER BY", "LIMIT"}},+ {name: "inner select keeps its own where", query: "SELECT * FROM orders AS a JOIN orders AS b ON CASE WHEN (SELECT amount FROM orders )", position: len("SELECT * FROM orders AS a JOIN orders AS b ON CASE WHEN (SELECT amount FROM orders "), label: "WHERE", kind: "keyword"},+ {name: "else inside unfinished join case", query: "SELECT * FROM orders AS a JOIN orders AS b ON a.amount = CASE WHEN b.amount > 0 THEN 1 el", position: len("SELECT * FROM orders AS a JOIN orders AS b ON a.amount = CASE WHEN b.amount > 0 THEN 1 el"), label: "ELSE", kind: "keyword", excluded: []string{"WHERE"}, total: 1},+ {name: "end inside nested unfinished join case", query: "SELECT * FROM orders AS a JOIN orders AS b ON a.amount = CASE WHEN b.amount > 0 THEN CASE WHEN a.amount > 0 THEN 1 END ELSE 0 en", position: len("SELECT * FROM orders AS a JOIN orders AS b ON a.amount = CASE WHEN b.amount > 0 THEN CASE WHEN a.amount > 0 THEN 1 END ELSE 0 en"), label: "END", kind: "keyword", excluded: []string{"WHERE"}},+ {name: "where after closed join case", query: "SELECT * FROM orders AS a JOIN orders AS b ON a.amount = CASE WHEN b.amount > 0 THEN 1 ELSE 0 END ", position: len("SELECT * FROM orders AS a JOIN orders AS b ON a.amount = CASE WHEN b.amount > 0 THEN 1 ELSE 0 END "), label: "WHERE", kind: "keyword", insertText: "WHERE"},+ {name: "where after standalone closed join case", query: "SELECT * FROM events JOIN persons ON CASE WHEN TRUE THEN 1 ELSE 0 END ", position: len("SELECT * FROM events JOIN persons ON CASE WHEN TRUE THEN 1 ELSE 0 END "), label: "WHERE", kind: "keyword", insertText: "WHERE"},+ {name: "where after true join predicate", query: "SELECT * FROM events JOIN persons ON TRUE ", position: len("SELECT * FROM events JOIN persons ON TRUE "), label: "WHERE", kind: "keyword", insertText: "WHERE"},+ {name: "where after lowercase false join predicate", query: "SELECT * FROM events JOIN persons ON false ", position: len("SELECT * FROM events JOIN persons ON false "), label: "WHERE", kind: "keyword", insertText: "WHERE"},+ {name: "qualified true stays a field", query: "SELECT * FROM events AS e JOIN persons ON e.TRUE ", position: len("SELECT * FROM events AS e JOIN persons ON e.TRUE "), label: "=", kind: "operator", insertText: "=", excluded: []string{"WHERE"}},+ {name: "quoted true stays an identifier", query: `SELECT * FROM events JOIN persons ON "TRUE" `, position: len(`SELECT * FROM events JOIN persons ON "TRUE" `), label: "=", kind: "operator", insertText: "=", excluded: []string{"WHERE"}},{name: "between separator", query: "SELECT * FROM orders WHERE amount BETWEEN 1 ", position: len("SELECT * FROM orders WHERE amount BETWEEN 1 "), label: "AND", kind: "keyword", insertText: "AND", excluded: []string{"OR", "GROUP BY", "ORDER BY", "LIMIT"}, total: 1},{name: "between unfinished arithmetic expression", query: "SELECT * FROM orders WHERE amount BETWEEN 1 + cou", position: len("SELECT * FROM orders WHERE amount BETWEEN 1 + cou"), label: "count", kind: "function", insertText: "count()", excluded: []string{"AND"}},{name: "between unfinished function call", query: "SELECT * FROM orders WHERE amount BETWEEN toDate(amo", position: len("SELECT * FROM orders WHERE amount BETWEEN toDate(amo"), label: "amount", kind: "field", excluded: []string{"AND"}},@@ -878,6 +909,11 @@ func TestCompletesSQLSyntaxForCursorContext(t *testing.T) {if !ok || suggestion.Kind != test.kind || suggestion.InsertText != test.insertText {t.Fatalf("suggestion %q = %#v; all suggestions = %#v; parse error = %q", test.label, suggestion, result.Suggestions, result.ParseError)}+ for _, required := range test.required {+ if !hasSuggestion(result.Suggestions, required) {+ t.Fatalf("missing suggestion %q in %#v", required, result.Suggestions)+ }+ }for _, excluded := range test.excluded {if hasSuggestion(result.Suggestions, excluded) {t.Fatalf("unexpected suggestion %q in %#v", excluded, result.Suggestions)diff --git a/services/hogql-language-service/internal/completion/context.go b/services/hogql-language-service/internal/completion/context.goindex 7725f7484d32..3a9f2f2849d0 100644--- a/services/hogql-language-service/internal/completion/context.go+++ b/services/hogql-language-service/internal/completion/context.go@@ -16,7 +16,10 @@ const (completionModeComparisoncompletionModeBetweenSeparatorcompletionModePredicateContinuation+ completionModeJoinPredicateContinuationcompletionModePostExpression+ completionModeJoinPostExpression+ completionModeCaseExpressioncompletionModeStatementStart)@@ -55,8 +58,20 @@ func analyzeCursorContext(input string) completionMode {}case "SELECT", "GROUP BY", "ORDER BY":return completionModeExpression- case "WHERE", "PREWHERE", "HAVING", "ON":+ case "WHERE", "PREWHERE", "HAVING":return predicateMode(tokens[clauseIndex+1:], depth)+ case "ON":+ mode := predicateMode(tokens[clauseIndex+1:], depth)+ if tokens[clauseIndex].depth != depth {+ return mode+ }+ if mode == completionModePredicateContinuation {+ return completionModeJoinPredicateContinuation+ }+ if mode == completionModePostExpression {+ return completionModeJoinPostExpression+ }+ return mode}return completionModeGeneral}@@ -83,7 +98,19 @@ func predicateMode(tokens []sqlToken, depth int) completionMode {start := 0betweenPending := falsecaseDepth := 0+ openExpressionCases := 0+ closedCase := falsefor index, token := range tokens {+ if token.kind == sqlTokenWord {+ switch token.text {+ case "CASE":+ openExpressionCases+++ case "END":+ if openExpressionCases > 0 {+ openExpressionCases--+ }+ }+ }if token.kind == sqlTokenLeftParen && token.depth == depth-1 {start = index + 1betweenPending = false@@ -99,6 +126,7 @@ func predicateMode(tokens []sqlToken, depth int) completionMode {case "END":if caseDepth > 0 {caseDepth--+ closedCase = true}case "BETWEEN":if caseDepth == 0 {@@ -122,6 +150,9 @@ func predicateMode(tokens []sqlToken, depth int) completionMode {}segment := tokens[start:]last := lastTokenAtDepth(segment, depth)+ if openExpressionCases > 0 || caseDepth > 0 {+ return completionModeCaseExpression+ }if last.text == "" || last.text == "AND" || last.text == "OR" || last.kind == sqlTokenComma || last.kind == sqlTokenLeftParen {return completionModeExpression}@@ -149,12 +180,57 @@ func predicateMode(tokens []sqlToken, depth int) completionMode {}return completionModeExpression}- if last.kind == sqlTokenRightParen || last.kind == sqlTokenValue {+ if last.kind == sqlTokenRightParen || last.kind == sqlTokenValue || closedCase && last.text == "END" || isUnqualifiedBooleanToken(segment, depth) {return completionModePostExpression}return completionModeComparison}+func isUnqualifiedBooleanToken(tokens []sqlToken, depth int) bool {+ lastIndex := -1+ for index := len(tokens) - 1; index >= 0; index-- {+ if tokens[index].depth <= depth {+ lastIndex = index+ break+ }+ }+ if lastIndex < 0 {+ return false+ }+ last := tokens[lastIndex]+ if last.kind != sqlTokenWord || !strings.EqualFold(last.raw, "TRUE") && !strings.EqualFold(last.raw, "FALSE") {+ return false+ }+ for index := lastIndex - 1; index >= 0; index-- {+ if tokens[index].depth < depth {+ break+ }+ if tokens[index].depth == depth {+ return tokens[index].text != "."+ }+ }+ return true+}++func hasLaterJoinAtDepth(input string, depth int) bool {+ tokens, _, _ := scanSQLTokensAtDepth(input, depth)+ for _, token := range tokens {+ if token.depth < depth || token.depth == depth && token.text == ";" {+ return false+ }+ if token.depth != depth || token.kind != sqlTokenWord {+ continue+ }+ switch token.text {+ case "JOIN":+ return true+ case "WHERE", "PREWHERE", "GROUP", "ORDER", "HAVING", "QUALIFY", "LIMIT", "UNION", "EXCEPT", "INTERSECT":+ return false+ }+ }+ return false+}+func betweenLowerBoundComplete(tokens []sqlToken, depth int) bool {hasExpressionToken := falseopenCases := 0@@ -242,8 +318,12 @@ func isComparisonToken(token sqlToken) bool {}func scanSQLTokens(input string) ([]sqlToken, int, bool) {+ return scanSQLTokensAtDepth(input, 0)+}++func scanSQLTokensAtDepth(input string, initialDepth int) ([]sqlToken, int, bool) {var tokens []sqlToken- depth := 0+ depth := initialDepthfor index := 0; index < len(input); {character := input[index]r, size := utf8.DecodeRuneInString(input[index:])diff --git a/services/hogql-language-service/internal/validation/validation.go b/services/hogql-language-service/internal/validation/validation.goindex 94e1ad8301c1..bd6a4c9935a9 100644--- a/services/hogql-language-service/internal/validation/validation.go+++ b/services/hogql-language-service/internal/validation/validation.go@@ -146,7 +146,7 @@ func Validate(schema *catalog.PreparedCatalog, query string) Result {}}case *clickhouse.Ident:- if ignoredIdents[typed] || typed.Name == "*" {+ if ignoredIdents[typed] || typed.Name == "*" || analysis.IsBooleanLiteral(typed) {return true}bindings := statement.BindingsAt(int(node.Pos()), int(node.End()))diff --git a/services/hogql-language-service/internal/validation/validation_test.go b/services/hogql-language-service/internal/validation/validation_test.goindex 637bba64af51..6f410ace434b 100644--- a/services/hogql-language-service/internal/validation/validation_test.go+++ b/services/hogql-language-service/internal/validation/validation_test.go@@ -169,6 +169,9 @@ func TestValidateAcceptsKnownFieldsAndFunctions(t *testing.T) {{query: "SELECT event AS kind FROM events WHERE uuid IN (SELECT uuid AS kind FROM events WHERE kind != '') ORDER BY kind", tableName: "events"},{query: "SELECT s.subtotal FROM (SELECT amount AS total, total AS subtotal FROM warehouse_orders) AS s", tableName: "warehouse_orders"},{query: "SELECT amount AS amount FROM warehouse_orders ORDER BY amount", tableName: "warehouse_orders"},+ {query: "SELECT TRUE, false FROM events WHERE TRUE AND false = FALSE", tableName: "events"},+ {query: "SELECT CASE WHEN TRUE THEN false ELSE FALSE END AS enabled FROM events", tableName: "events"},+ {query: "WITH flags AS (SELECT TRUE AS enabled FROM events) SELECT enabled FROM flags WHERE enabled = FALSE", tableName: "events"},} {result := Validate(schema(), test.query)if !result.Valid || len(result.Diagnostics) != 0 {@@ -314,6 +317,8 @@ func TestValidateRejectsUnknownFields(t *testing.T) {"WITH t AS (SELECT total FROM warehouse_orders) SELECT amount AS total FROM warehouse_orders","SELECT event AS kind FROM events ORDER BY events.kind","SELECT amount AS Total FROM warehouse_orders ORDER BY total",+ `SELECT "TRUE" FROM events`,+ "SELECT events.FALSE FROM events",} {result := Validate(schema(), query)if result.Valid || len(result.Diagnostics) != 1 || result.Diagnostics[0].Code != "unknown_field" {