: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): preserve case-sensitive relation names (#102358)
Paweł Szczur0f05863da04e
diff --git a/docs/internal/hogql-language-service.md b/docs/internal/hogql-language-service.mdindex badf8a263d46..cd0969cabea1 100644--- a/docs/internal/hogql-language-service.md+++ b/docs/internal/hogql-language-service.md@@ -52,6 +52,12 @@ Validation reports `duplicate_table` when a FROM or JOIN source reuses a table nUse distinct aliases for self-joins, for example `events AS e JOIN events AS other`.This follows HogQL's resolver even when raw ClickHouse accepts an unaliased self-join.The duplicate-name check is case-sensitive; separate nested queries and set-operation branches can reuse names.+Catalog table names, table aliases, and CTE names resolve by exact case, as in the Python resolver for ordinary tables.+Catalogs can contain both `events` and `Events`; each name retains its own fields, and validation lists both names when both are used.+With only `events` in the catalog, `SELECT properties FROM Events` reports `unknown_table`.+The same query is valid when an exact `Events` entry exists and exposes `properties`.+Table completion still matches prefixes without regard to case, so typing `EV` can suggest both names and inserts the selected name with its original case.+CTE shadowing and table-suggestion deduplication use exact names, so a CTE named `Events` does not hide the catalog table `events`.Duplicate qualifiers do not establish property provenance, including inside CTE projections and qualified wildcards.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.@@ -83,6 +89,19 @@ For example, `WITH recent AS (SELECT properties FROM events) SELECT recent.propeA CTE named `events` that projects `persons.properties` uses the person property catalog, not the event catalog.Renaming a container to `props` preserves its origin; projecting an individual property value does not preserve the whole container's namespace.+Case-variant aliases keep separate property origins:++```sql+SELECT e.properties.$browser, E.properties.email+FROM events AS e JOIN persons AS E ON 1 = 1+```++With those properties in the supplied catalog, both references validate.+Completion after `e.properties.$br` suggests the event property `$browser`, while `E.properties.em` suggests the person property `email`.+A reference to `E` does not resolve an alias declared only as `e`.+CTEs named `t` and `T` also retain separate projected fields and property origins.+An unrelated custom table named `Events` does not inherit the built-in event property catalog from its spelling.+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.@@ -93,6 +112,8 @@ Derived qualified suggestions are sorted and deduplicated before pagination.### Recovery and remaining work+- 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.- 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`.diff --git a/services/hogql-language-service/README.md b/services/hogql-language-service/README.mdindex e993d7167e89..b4f2c39f7276 100644--- a/services/hogql-language-service/README.md+++ b/services/hogql-language-service/README.md@@ -48,6 +48,8 @@ Direct property containers retain their catalog namespace through CTEs, aliasedFor example, `WITH t AS (SELECT properties AS props FROM events) SELECT t.props.$br FROM t` suggests `$browser`.Computed or ambiguous property origins remain unknown; the service does not guess a namespace from a projected name.Validation reports `duplicate_table` for repeated table names or explicit aliases in one query scope and asks for distinct aliases.+Table names, table aliases, and CTE names resolve by exact case; catalogs can contain distinct `events` and `Events` tables.+Autocomplete prefix matching remains case-insensitive and preserves the selected identifier's case.Duplicate qualifiers do not supply property provenance, even when raw ClickHouse accepts the corresponding unaliased self-join.Validation diagnostic offsets use `positionEncoding`, which defaults to UTF-16. Diagnostics include up to five visiblediff --git a/services/hogql-language-service/internal/analysis/document.go b/services/hogql-language-service/internal/analysis/document.goindex 27f5c258c8d7..fd9fcd4894f9 100644--- a/services/hogql-language-service/internal/analysis/document.go+++ b/services/hogql-language-service/internal/analysis/document.go@@ -109,7 +109,7 @@ func (s *Statement) analyze() {addBinding(scope, name, alias, Relation{name: cte.name, cte: cte}, start, end)return true}- if original, exists := s.originalTableNames[strings.ToLower(name)]; exists {+ if original, exists := s.originalTableNames[name]; exists {name = originalimplicitAlias = strings.ReplaceAll(original, ".", "__")}@@ -197,12 +197,11 @@ func (b Bindings) CTENames(prefix string) iter.Seq[catalog.Entry] {if !scope.budget.lookup(len(name) + 1) {return}- folded := foldedFieldName(name)- if seen[folded] {+ if seen[name] {continue}- seen[folded] = true- if strings.HasPrefix(folded, prefix) && !yield(catalog.Entry{Name: name, Type: "CTE"}) {+ seen[name] = true+ if strings.HasPrefix(foldedFieldName(name), prefix) && !yield(catalog.Entry{Name: name, Type: "CTE"}) {return}}@@ -211,7 +210,7 @@ func (b Bindings) CTENames(prefix string) iter.Seq[catalog.Entry] {}func (b Bindings) Relation(name string) (Relation, bool) {- relation, ok := b.relations[strings.ToLower(name)]+ relation, ok := b.relations[name]return relation, ok}@@ -268,14 +267,16 @@ func (b Bindings) PropertyNamespace(parts []string) (string, bool) {}}if len(parts) > 2 {- if _, bound := b.Relation(parts[0]); !bound && resolveCTE(b.scope, parts[0], b.position) != nil {- return "", false+ if _, bound := b.Relation(parts[0]); !bound {+ if resolveCTE(b.scope, parts[0], b.position) != nil || len(parts) > 3 {+ return "", false+ }}}names := make(map[string]string, len(b.relations))for name, relation := range b.relations {if relation.cte != nil {- if len(parts) > 2 && strings.EqualFold(parts[0], name) {+ if len(parts) > 2 && parts[0] == name {return "", false}if len(parts) == 2 {diff --git a/services/hogql-language-service/internal/analysis/scopes.go b/services/hogql-language-service/internal/analysis/scopes.goindex 50af32d2a7d7..50eaf5e0f5d7 100644--- a/services/hogql-language-service/internal/analysis/scopes.go+++ b/services/hogql-language-service/internal/analysis/scopes.go@@ -131,10 +131,10 @@ func walkIncludingExcept(expr clickhouse.Expr, visit func(clickhouse.Expr) bool)}func addBinding(scope *queryScope, name, alias string, binding Relation, start, end int) {- scope.bindings[strings.ToLower(name)] = binding+ scope.bindings[name] = bindingsource := Source{name: name, relation: binding, start: start, end: end}if alias != "" {- scope.bindings[strings.ToLower(alias)] = binding+ scope.bindings[alias] = bindingsource.name = alias}scope.sources = append(scope.sources, source)@@ -175,7 +175,7 @@ func resolveCTE(scope *queryScope, name string, position int) *cteBinding {for current := scope; current != nil; current = current.parent {ctes := current.visibleCTEs(position)for index := len(ctes) - 1; index >= 0; index-- {- if strings.EqualFold(ctes[index].name, name) {+ if ctes[index].name == name {return ctes[index]}}@@ -250,7 +250,7 @@ func (s *queryScope) provenanceSources(name string) []Relation {if !s.budget.lookup(len(name) + 1) {return nil}- key := strings.ToLower(source.name)+ key := source.nameif seen[key] {continue}@@ -314,7 +314,7 @@ func normalizeHogQLTableReferences(query string) (string, map[string]string) {normalized[index] = '_'}}- originalNames[strings.ToLower(string(normalized[start:end]))] = name+ originalNames[string(normalized[start:end])] = name}return string(normalized), originalNames}@@ -412,7 +412,7 @@ func bindingPropertyNamespace(binding Relation, name string) (string, bool) {if _, ok := binding.table.Fields.Exact(name); !ok {return "", false}- return propertyresolver.Resolve([]string{binding.name, name, "property"}, map[string]string{strings.ToLower(binding.name): binding.name})+ return propertyresolver.Resolve([]string{binding.name, name, "property"}, map[string]string{binding.name: binding.name})}if binding.cte == nil {return "", false@@ -512,13 +512,13 @@ func (c *cteBinding) appendFields(fields []projectedField) {func (c *cteBinding) appendWildcardFields(scope *queryScope, qualifier string) {bindings := visibleBindings(scope)if qualifier != "" {- c.appendBindingFields(bindings[strings.ToLower(qualifier)], scope.hasDuplicateSource(qualifier))+ c.appendBindingFields(bindings[qualifier], scope.hasDuplicateSource(qualifier))return}seen := map[string]bool{}for current := scope; current != nil; current = current.parent {for _, source := range current.sources {- key := strings.ToLower(source.name)+ key := source.nameif current != scope && seen[key] {continue}@@ -575,7 +575,7 @@ func projectedPropertyNamespace(scope *queryScope, expr clickhouse.Expr, positioif scope.hasDuplicateSource(typed.Fields[0].Name) {return "", false}- if binding, ok := bindings[strings.ToLower(typed.Fields[0].Name)]; ok {+ if binding, ok := bindings[typed.Fields[0].Name]; ok {return bindingPropertyNamespace(binding, typed.Fields[1].Name)}}@@ -584,7 +584,7 @@ func projectedPropertyNamespace(scope *queryScope, expr clickhouse.Expr, positioif scope.hasDuplicateSource(typed.Ident.Name) {return "", false}- if binding, ok := bindings[strings.ToLower(typed.Ident.Name)]; ok {+ if binding, ok := bindings[typed.Ident.Name]; ok {return bindingPropertyNamespace(binding, typed.DotIdent.Name)}}@@ -636,7 +636,7 @@ func projectedType(scope *queryScope, expr clickhouse.Expr) string {}case *clickhouse.Path:if len(typed.Fields) >= 2 {- if binding, ok := bindings[strings.ToLower(typed.Fields[0].Name)]; ok {+ if binding, ok := bindings[typed.Fields[0].Name]; ok {if field, exists := bindingField(binding, typed.Fields[1].Name); exists {return field.Type}@@ -644,7 +644,7 @@ func projectedType(scope *queryScope, expr clickhouse.Expr) string {}case *clickhouse.NestedIdentifier:if typed.DotIdent != nil {- if binding, ok := bindings[strings.ToLower(typed.Ident.Name)]; ok {+ if binding, ok := bindings[typed.Ident.Name]; ok {if field, exists := bindingField(binding, typed.DotIdent.Name); exists {return field.Type}diff --git a/services/hogql-language-service/internal/analysis/sources.go b/services/hogql-language-service/internal/analysis/sources.goindex 5b85007044a0..e74aaaff931e 100644--- a/services/hogql-language-service/internal/analysis/sources.go+++ b/services/hogql-language-service/internal/analysis/sources.go@@ -2,7 +2,6 @@ package analysisimport ("iter"- "strings""github.com/PostHog/posthog/services/hogql-language-service/internal/catalog")@@ -31,7 +30,7 @@ func (b Bindings) sources() iter.Seq[Source] {if !scope.budget.lookup(len(source.name) + 1) {return}- name := strings.ToLower(source.name)+ name := source.nameif seen[name] {continue}diff --git a/services/hogql-language-service/internal/catalog/catalog.go b/services/hogql-language-service/internal/catalog/catalog.goindex c9bca7d0329d..45890638f717 100644--- a/services/hogql-language-service/internal/catalog/catalog.go+++ b/services/hogql-language-service/internal/catalog/catalog.go@@ -81,12 +81,7 @@ func Prepare(value *Catalog) *PreparedCatalog {}tableType := intern(types, table.Type)preparedTable := PreparedTable{Name: name, Type: tableType, Fields: newIndex(fieldEntries[fieldStart:])}- foldedName := foldName(name)- if _, exists := prepared.tablesByName[foldedName]; exists {- prepared.valid = false- continue- }- prepared.tablesByName[foldedName] = len(prepared.tableValues)+ prepared.tablesByName[name] = len(prepared.tableValues)prepared.tableValues = append(prepared.tableValues, preparedTable)tableEntries = append(tableEntries, newEntry(name, tableType))}@@ -105,7 +100,7 @@ func Prepare(value *Catalog) *PreparedCatalog {}func (c *PreparedCatalog) Table(name string) (*PreparedTable, bool) {- index, ok := c.tablesByName[foldName(name)]+ index, ok := c.tablesByName[name]if !ok {return nil, false}@@ -200,7 +195,7 @@ func (c *PreparedCatalog) estimateSize() int64 {var size int64for _, entry := range c.tables.entries {size += entrySize(entry) + 64- table := &c.tableValues[c.tablesByName[foldName(entry.Name)]]+ table := &c.tableValues[c.tablesByName[entry.Name]]for _, field := range table.Fields.entries {size += entrySize(field)}diff --git a/services/hogql-language-service/internal/catalog/catalog_test.go b/services/hogql-language-service/internal/catalog/catalog_test.goindex c1bf714c30b6..6b44c9df465e 100644--- a/services/hogql-language-service/internal/catalog/catalog_test.go+++ b/services/hogql-language-service/internal/catalog/catalog_test.go@@ -11,7 +11,7 @@ func TestIndexExactUsesUnicodeCaseFolding(t *testing.T) {}}-func TestPreparedCatalogUsesUnicodeCaseFoldingForTableAndPrefixLookups(t *testing.T) {+func TestPreparedCatalogUsesExactTableNamesAndFoldedFieldPrefixes(t *testing.T) {prepared := Prepare(&Catalog{Tables: map[string]Table{"ς": {@@ -23,9 +23,12 @@ func TestPreparedCatalogUsesUnicodeCaseFoldingForTableAndPrefixLookups(t *testinProperties: map[string][]Property{},})- table, ok := prepared.Table("Σ")+ if _, ok := prepared.Table("Σ"); ok {+ t.Fatal("Table(\"Σ\") matched ς")+ }+ table, ok := prepared.Table("ς")if !ok {- t.Fatal("Table(\"Σ\") did not find ς")+ t.Fatal("Table(\"ς\") did not find ς")}entry, ok := table.Fields.Exact("Σuffix")if !ok || entry.Name != "ςuffix" {@@ -36,3 +39,23 @@ func TestPreparedCatalogUsesUnicodeCaseFoldingForTableAndPrefixLookups(t *testint.Fatalf("Prefix(\"Σ\") = %#v", prefix)}}++func TestPreparedCatalogRetainsCaseVariantTables(t *testing.T) {+ prepared := Prepare(&Catalog{+ Tables: map[string]Table{+ "Events": {Fields: map[string]Field{"upper": {Name: "upper", Type: "String"}}},+ "events": {Fields: map[string]Field{"lower": {Name: "lower", Type: "String"}}},+ },+ Properties: map[string][]Property{},+ })++ upper, upperOK := prepared.Table("Events")+ lower, lowerOK := prepared.Table("events")+ if !prepared.valid || !upperOK || !lowerOK || upper.Name != "Events" || lower.Name != "events" || prepared.TableCount() != 2 {+ t.Fatalf("prepared catalog = %#v", prepared)+ }+ prefix := prepared.Tables().Prefix("EV")+ if len(prefix) != 2 || prefix[0].Name != "Events" || prefix[1].Name != "events" {+ t.Fatalf("Prefix(\"EV\") = %#v", prefix)+ }+}diff --git a/services/hogql-language-service/internal/catalog/registry_test.go b/services/hogql-language-service/internal/catalog/registry_test.goindex 4e102b9bd97a..3418da213f24 100644--- a/services/hogql-language-service/internal/catalog/registry_test.go+++ b/services/hogql-language-service/internal/catalog/registry_test.go@@ -1,14 +1,13 @@package catalogimport (- "errors""testing""time""github.com/PostHog/posthog/services/hogql-language-service/internal/serviceauth")-func TestRegistryRejectsCaseInsensitiveDuplicateTables(t *testing.T) {+func TestRegistryAcceptsCaseVariantTables(t *testing.T) {registry := NewRegistry(1, 1<<20, time.Hour)value := Prepare(&Catalog{Tables: map[string]Table{@@ -18,9 +17,8 @@ func TestRegistryRejectsCaseInsensitiveDuplicateTables(t *testing.T) {Properties: map[string][]Property{},})- err := registry.Put(serviceauth.Authorization{TeamID: 1, UserID: 10}, "1", value)- if !errors.Is(err, ErrInvalidCatalog) {- t.Fatalf("Put() error = %v, want %v", err, ErrInvalidCatalog)+ if err := registry.Put(serviceauth.Authorization{TeamID: 1, UserID: 10}, "1", value); err != nil {+ t.Fatalf("Put() error = %v", err)}}diff --git a/services/hogql-language-service/internal/completion/bindings.go b/services/hogql-language-service/internal/completion/bindings.goindex a27743aa5912..c8f7ee17458c 100644--- a/services/hogql-language-service/internal/completion/bindings.go+++ b/services/hogql-language-service/internal/completion/bindings.go@@ -69,7 +69,7 @@ func recoverSingleSelect(query string) string {var recovered strings.Builderrecovered.WriteString("SELECT * ")for _, token := range tokens[from:end] {- recovered.WriteString(token.text)+ recovered.WriteString(token.raw)recovered.WriteByte(' ')}return recovered.String()diff --git a/services/hogql-language-service/internal/completion/completion_test.go b/services/hogql-language-service/internal/completion/completion_test.goindex fe2c7de953da..5e86a47cc323 100644--- a/services/hogql-language-service/internal/completion/completion_test.go+++ b/services/hogql-language-service/internal/completion/completion_test.go@@ -21,6 +21,9 @@ func testCatalog() *catalog.PreparedCatalog {"uuid": {Name: "uuid", Type: "string"}, "event": {Name: "event", Type: "string"},"properties": {Name: "properties", Type: "json"},}},+ "Events": {Name: "Events", Type: "data_warehouse", Fields: map[string]catalog.Field{+ "custom_field": {Name: "custom_field", Type: "string"}, "properties": {Name: "properties", Type: "json"},+ }},"persons": {Name: "persons", Type: "posthog", Fields: map[string]catalog.Field{"id": {Name: "id", Type: "string"}, "properties": {Name: "properties", Type: "json"},}},@@ -111,9 +114,10 @@ func TestCompletesTablesAfterFrom(t *testing.T) {{"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"}},+ {"case-variant catalog tables", "SELECT * FROM EV|", map[string]string{"Events": "data_warehouse", "events": "posthog"}},+ {"case-variant catalog and CTE", "WITH Orders AS (SELECT event FROM events) SELECT * FROM ord|", map[string]string{"Orders": "CTE", "orders": "data_warehouse"}},{"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"}},+ {"case-variant nested CTEs", "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", "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},@@ -189,6 +193,9 @@ func TestCompletesFieldsForAlias(t *testing.T) {{"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"},}},+ {"case-variant relation aliases", "SELECT prop| FROM events AS e JOIN persons AS E ON 1 = 1", []Suggestion{+ {Label: "properties", Detail: "json from E", InsertText: "E.properties"}, {Label: "properties", Detail: "json from e", InsertText: "e.properties"},+ }},{"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"}}},@@ -278,6 +285,12 @@ func TestCompletesScopedProjections(t *testing.T) {{"renamed properties are unrelated", "WITH t AS (SELECT properties AS attrs FROM events) SELECT properties.$geo_ci| FROM events JOIN t ON 1 = 1", map[string]string{"$geo_city": "String"}},{"derived properties are ambiguous", "WITH t AS (SELECT properties FROM events) SELECT properties.$geo_ci| FROM events JOIN t ON 1 = 1", nil},{"qualified physical properties remain available", "WITH t AS (SELECT properties FROM events) SELECT e.properties.$geo_ci| FROM events AS e JOIN t ON 1 = 1", map[string]string{"$geo_city": "String"}},+ {"lowercase alias keeps event properties", "SELECT e.properties.$geo_co| FROM events AS e JOIN persons AS E ON 1 = 1", map[string]string{"$geo_country": "String"}},+ {"uppercase alias keeps person properties", "SELECT E.properties.$geo| FROM events AS e JOIN persons AS E ON 1 = 1", map[string]string{"$geo_city": "String"}},+ {"wrong-case alias does not recover event properties", "SELECT E.properties.$geo| FROM events AS e", nil},+ {"exact custom table does not inherit event properties", "SELECT Events.properties.$geo| FROM Events", nil},+ {"nested virtual owner requires exact qualifier", "SELECT e.person.properties.$geo_ci| FROM events AS e", map[string]string{"$geo_city": "String"}},+ {"nested virtual owner rejects wrong-case qualifier", "SELECT E.person.properties.$geo| FROM events AS e", nil},{"cte property provenance", "WITH recent AS (SELECT properties FROM events) SELECT recent.properties.$geo_co| FROM recent", map[string]string{"$geo_country": "String"}},{"unqualified cte property provenance", "WITH recent AS (SELECT properties FROM events) SELECT properties.$geo_co| FROM recent", map[string]string{"$geo_country": "String"}},{"subquery property provenance", "SELECT recent.properties.$geo_co| FROM (SELECT properties FROM events) AS recent", map[string]string{"$geo_country": "String"}},@@ -291,6 +304,10 @@ func TestCompletesScopedProjections(t *testing.T) {{"property alias before duplicate", "SELECT properties AS props, props.$geo_co|, uuid AS props FROM events", map[string]string{"$geo_country": "String"}},{"property alias after duplicate", "SELECT properties AS props, uuid AS props, props.$geo| FROM events", nil},{"cte name does not determine provenance", "WITH events AS (SELECT properties FROM persons) SELECT events.properties.$geo| FROM events", map[string]string{"$geo_city": "String"}},+ {"case-variant CTE property provenance", "WITH t AS (SELECT properties FROM events), T AS (SELECT properties FROM persons) SELECT T.properties.$geo| FROM t JOIN T ON 1 = 1", map[string]string{"$geo_city": "String"}},+ {"lowercase case-variant CTE property provenance", "WITH t AS (SELECT properties FROM events), T AS (SELECT properties FROM persons) SELECT t.properties.$geo_co| FROM t JOIN T ON 1 = 1", map[string]string{"$geo_country": "String"}},+ {"wrong-case CTE has no fields", "WITH t AS (SELECT properties FROM events) SELECT T.| FROM T", nil},+ {"case-variant table fields stay isolated", "SELECT Events.| FROM Events", map[string]string{"custom_field": "string", "properties": "json"}},{"ambiguous joined properties", "WITH t AS (SELECT properties FROM events JOIN persons ON 1 = 1) SELECT t.properties.$geo| FROM t", nil},{"self join properties are ambiguous", "WITH t AS (SELECT properties FROM events AS e JOIN events AS other ON 1 = 1) SELECT t.properties.$geo| FROM t", nil},{"unaliased self join properties are ambiguous", "WITH t AS (SELECT properties FROM events JOIN events ON 1 = 1) SELECT t.properties.$geo| FROM t", nil},@@ -334,6 +351,7 @@ func TestCompletesScopedProjections(t *testing.T) {{"alias virtual property shadow", "SELECT uuid AS session FROM events ORDER BY session.properties.$entry|", nil},{"qualified properties bypass alias", "SELECT uuid AS properties FROM events ORDER BY events.properties.$geo_ci|", map[string]string{"$geo_city": "String"}},{"no recovered select aliases", "SELECT amount AS total FROM orders WHERE tot| >", nil},+ {"recovery preserves relation case", "SELECT Mixed.cus| FROM Events AS Mixed WHERE custom_field =", map[string]string{"custom_field": "string"}},} {t.Run(test.name, func(t *testing.T) {position := strings.IndexByte(test.query, '|')@@ -342,6 +360,9 @@ func TestCompletesScopedProjections(t *testing.T) {if err != nil {t.Fatal(err)}+ if test.name == "recovery preserves relation case" && !strings.HasPrefix(result.ParseError, "parse incomplete SQL:") {+ t.Fatalf("parse error = %q, want recovered incomplete SQL error", result.ParseError)+ }fields := map[string]string{}for _, suggestion := range result.Suggestions {if suggestion.Kind == "field" || suggestion.Kind == "property" {@@ -641,13 +662,13 @@ func TestCompletionPaginationSkipsUnsupportedIdentifiers(t *testing.T) {}}-func TestCompletesFieldsForMixedCaseTableReference(t *testing.T) {+func TestDoesNotCompleteFieldsForWrongCaseTableReference(t *testing.T) {query := "SELECT Orders. FROM Orders"result, err := Complete(testCatalog(), query, len("SELECT Orders."), PositionEncodingUTF8, "")if err != nil {t.Fatal(err)}- if !hasSuggestion(result.Suggestions, "order_id") {+ if len(result.Suggestions) != 0 {t.Fatalf("suggestions = %#v; parse error = %q", result.Suggestions, result.ParseError)}}diff --git a/services/hogql-language-service/internal/completion/context.go b/services/hogql-language-service/internal/completion/context.goindex 9ecc5a616279..67d3aae7db03 100644--- a/services/hogql-language-service/internal/completion/context.go+++ b/services/hogql-language-service/internal/completion/context.go@@ -33,6 +33,7 @@ const (type sqlToken struct {text string+ raw stringkind sqlTokenKinddepth int}@@ -274,7 +275,7 @@ func scanSQLTokens(input string) ([]sqlToken, int, bool) {if character != '\'' {kind = sqlTokenWord}- tokens = append(tokens, sqlToken{text: strings.ToUpper(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})index = endcontinue}@@ -287,7 +288,7 @@ func scanSQLTokens(input string) ([]sqlToken, int, bool) {}end += size}- tokens = append(tokens, sqlToken{text: strings.ToUpper(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})index = endcontinue}@@ -296,27 +297,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], kind: sqlTokenValue, depth: depth})+ tokens = append(tokens, sqlToken{text: input[index:end], raw: input[index:end], kind: sqlTokenValue, depth: depth})index = endcontinue}switch character {case '(':- tokens = append(tokens, sqlToken{text: "(", kind: sqlTokenLeftParen, depth: depth})+ tokens = append(tokens, sqlToken{text: "(", raw: "(", kind: sqlTokenLeftParen, depth: depth})depth++index++case ')':if depth > 0 {depth--}- tokens = append(tokens, sqlToken{text: ")", kind: sqlTokenRightParen, depth: depth})+ tokens = append(tokens, sqlToken{text: ")", raw: ")", kind: sqlTokenRightParen, depth: depth})index++case ',':- tokens = append(tokens, sqlToken{text: ",", kind: sqlTokenComma, depth: depth})+ tokens = append(tokens, sqlToken{text: ",", raw: ",", kind: sqlTokenComma, depth: depth})index++default:end := operatorEnd(input, index)- tokens = append(tokens, sqlToken{text: strings.ToUpper(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})index = end}}diff --git a/services/hogql-language-service/internal/completion/tables.go b/services/hogql-language-service/internal/completion/tables.goindex 24fff09e7f09..76e5ad86e1dd 100644--- a/services/hogql-language-service/internal/completion/tables.go+++ b/services/hogql-language-service/internal/completion/tables.go@@ -14,7 +14,10 @@ func tableResult(schema *catalog.PreparedCatalog, bindings analysis.Bindings, prreturn 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))+ if comparison := strings.Compare(strings.ToLower(left.Name), strings.ToLower(right.Name)); comparison != 0 {+ return comparison+ }+ return strings.Compare(left.Name, right.Name)})cteNames := map[string]bool{}shadowed := map[string]bool{}diff --git a/services/hogql-language-service/internal/propertyresolver/resolver.go b/services/hogql-language-service/internal/propertyresolver/resolver.goindex 2e9c947b6541..1faffeec94e4 100644--- a/services/hogql-language-service/internal/propertyresolver/resolver.go+++ b/services/hogql-language-service/internal/propertyresolver/resolver.go@@ -18,19 +18,19 @@ func Resolve(parts []string, bindings map[string]string) (string, bool) {return "", false}if propertyIndex > 0 {- owner := strings.ToLower(parts[propertyIndex-1])+ owner := parts[propertyIndex-1]if namespace, ok := namespaceForOwner(owner); ok {return namespace, true}if tableName, ok := bindings[owner]; ok {- return namespaceForOwner(strings.ToLower(tableName))+ return namespaceForOwner(tableName)}return "", false}namespaces := map[string]bool{}for _, tableName := range bindings {- if namespace, ok := namespaceForOwner(strings.ToLower(tableName)); ok {+ if namespace, ok := namespaceForOwner(tableName); ok {namespaces[namespace] = true}}diff --git a/services/hogql-language-service/internal/validation/validation.go b/services/hogql-language-service/internal/validation/validation.goindex cdd725c7398d..94e1ad8301c1 100644--- a/services/hogql-language-service/internal/validation/validation.go+++ b/services/hogql-language-service/internal/validation/validation.go@@ -54,10 +54,9 @@ func Validate(schema *catalog.PreparedCatalog, query string) Result {seenTableNames := map[string]bool{}for statement := range document.Statements() {for table := range statement.Tables() {- lowerName := strings.ToLower(table.Name)- if !seenTableNames[lowerName] {+ if !seenTableNames[table.Name] {referencedTableNames = append(referencedTableNames, table.Name)- seenTableNames[lowerName] = true+ seenTableNames[table.Name] = true}if !table.Known && len(diagnostics) < querylimits.MaxDiagnostics {diagnostics = append(diagnostics, Diagnostic{diff --git a/services/hogql-language-service/internal/validation/validation_test.go b/services/hogql-language-service/internal/validation/validation_test.goindex 55f9316a28f3..637bba64af51 100644--- a/services/hogql-language-service/internal/validation/validation_test.go+++ b/services/hogql-language-service/internal/validation/validation_test.go@@ -93,6 +93,50 @@ func TestValidateUnknownTableSuggestsVisibleMatch(t *testing.T) {}}+func TestValidateRelationNamesAreCaseSensitive(t *testing.T) {+ result := Validate(schema(), "SELECT properties FROM Events")+ if result.Valid || len(result.Diagnostics) != 1 || result.Diagnostics[0].Code != "unknown_table" || result.Diagnostics[0].Start != len("SELECT properties FROM ") {+ t.Fatalf("wrong-case table result = %#v", result)+ }++ caseVariants := catalog.Prepare(&catalog.Catalog{Tables: map[string]catalog.Table{+ "events": {Name: "events", Fields: map[string]catalog.Field{+ "properties": {Name: "properties", Type: "json"},+ }},+ "Events": {Name: "Events", Fields: map[string]catalog.Field{+ "custom_field": {Name: "custom_field", Type: "string"},+ }},+ "persons": {Name: "persons", Fields: map[string]catalog.Field{+ "properties": {Name: "properties", Type: "json"},+ }},+ }, Properties: map[string][]catalog.Property{+ "event": {{Name: "$geo_city", ValueType: "String"}},+ "person": {{Name: "$geo_country", ValueType: "String"}},+ }})++ result = Validate(caseVariants, "SELECT events.properties, Events.custom_field FROM events JOIN Events ON 1 = 1")+ if !result.Valid || len(result.Diagnostics) != 0 || strings.Join(result.TableNames, ",") != "events,Events" {+ t.Fatalf("case-variant table result = %#v", result)+ }++ for _, test := range []struct{ query, suggestion string }{+ {"SELECT e.properties.$geo_cty FROM events AS e JOIN persons AS E ON 1 = 1", "$geo_city"},+ {"SELECT E.properties.$geo_contry FROM events AS e JOIN persons AS E ON 1 = 1", "$geo_country"},+ {"WITH t AS (SELECT properties FROM events), T AS (SELECT properties FROM persons) SELECT t.properties.$geo_cty FROM t JOIN T ON 1 = 1", "$geo_city"},+ {"WITH t AS (SELECT properties FROM events), T AS (SELECT properties FROM persons) SELECT T.properties.$geo_contry FROM t JOIN T ON 1 = 1", "$geo_country"},+ } {+ checked := Validate(caseVariants, test.query)+ if checked.Valid || len(checked.Diagnostics) != 1 || checked.Diagnostics[0].Code != "unknown_property" || len(checked.Diagnostics[0].Suggestions) == 0 || checked.Diagnostics[0].Suggestions[0].Label != test.suggestion {+ t.Fatalf("query %q returned %#v", test.query, checked)+ }+ }++ result = Validate(caseVariants, "WITH t AS (SELECT properties FROM events) SELECT properties FROM T")+ if result.Valid || len(result.Diagnostics) != 1 || result.Diagnostics[0].Code != "unknown_table" || result.Diagnostics[0].Start != len("WITH t AS (SELECT properties FROM events) SELECT properties FROM ") {+ t.Fatalf("wrong-case CTE result = %#v", result)+ }+}+func TestValidateUnknownAliasedFieldSuggestsVisibleMatch(t *testing.T) {for _, test := range []struct{ query, suggestion string }{{"SELECT o.amuont FROM warehouse_orders AS o", "amount"},