: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): support catalog table aliases (#103172)
Paweł Szczurf5103566f592
diff --git a/docs/internal/hogql-language-service.md b/docs/internal/hogql-language-service.mdindex 406f7da875fb..88fadbbe36cb 100644--- a/docs/internal/hogql-language-service.md+++ b/docs/internal/hogql-language-service.md@@ -70,7 +70,13 @@ Catalogs can contain both `events` and `Events`; each name retains its own fieldWith 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.+The optional `tableAliases` catalog map registers exact alternate spellings without duplicating field indexes.+For example, `"demo_postgres_orders": "postgres.demo.orders"` lets both names resolve to the fields on the canonical `tables` entry.+Validation retains the spelling from SQL in `tableNames`, and self-joins through two spellings keep separate source bindings.+Completion shows one spelling per canonical target. It prefers a matching canonical name and otherwise shows one matching alias.+CTEs shadow only their exact spelling, so a CTE named `demo_postgres_orders` does not hide `postgres.demo.orders`.CTE shadowing and table-suggestion deduplication use exact names, so a CTE named `Events` does not hide the catalog table `events`.+Multi-part names retain their source identity when their parser-safe forms coincide, such as `a.b.c_d` and `a.b_c.d`.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.@@ -165,6 +171,7 @@ Closed block comments and line comments at end of input remain valid.### Recovery and remaining work+- Multi-part normalization supports unquoted table paths after `FROM` and `JOIN`. Separately quoted path components and multi-part paths in comma-separated sources remain unsupported. Replacing the regular-expression normalization with token-aware handling is follow-up 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.- 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.@@ -212,10 +219,35 @@ team remains the primary isolation boundary in that model.Catalog publication replaces the catalog and revision atomically. Readers observe either the previous completerevision or the next complete revision.+The publication contract accepts this alias form:++```json+{+ "tables": {+ "postgres.demo.orders": { "type": "data_warehouse", "fields": {} }+ },+ "tableAliases": {+ "demo_postgres_orders": "postgres.demo.orders"+ },+ "properties": {}+}+```++`tableAliases` is optional, so older publishers remain compatible.+Each alias target must be a direct key in `tables`; aliases cannot target another alias.+An alias that equals a canonical key is valid only when it targets itself, which makes the entry a no-op.+The service rejects empty names, dangling targets, chains, cycles, and aliases that contradict canonical keys before cache admission.+Alias strings and lookup entries count toward the catalog memory limit.+The in-memory registry has two bounds:-- an idle TTL removes unused entries; and-- least-recently-used eviction caps the number of entries.+- a publication TTL expires entries after their catalog was published; and+- least-recently-used eviction caps both the number of entries and their estimated resident bytes.++The generated scale fixture verifies the HTTP publication path, completion, pagination, and validation with 4,096 canonical tables, 25 fields per table, and 120,000 event properties in one property namespace.+The table fields are columns, not part of the property count.+This profile fits the `64 MiB` request limit and the default `8 GiB` shared cache budget, but it is not an unlimited count guarantee.+Longer names and richer metadata increase both serialized and resident sizes.Warm autocomplete and validation perform no synchronous metadata requests. Catalog refresh remains outside thekeystroke path.@@ -242,6 +274,8 @@ fails startup unless dedicated signing keys are configured.Local and debug environments may use the service directly. Production integration remains behind a server-sidefeature flag and should progress through shadow comparison before serving editor results.+The Go consumer accepts alias metadata before Django publishes it.+Deploy this consumer first, then enable alias publication separately; catalogs without aliases continue to work throughout the rollout.The initial rollout keeps ClickHouse execution in Django:diff --git a/services/hogql-language-service/README.md b/services/hogql-language-service/README.mdindex f16a3fbd34b4..64ddde9cabb5 100644--- a/services/hogql-language-service/README.md+++ b/services/hogql-language-service/README.md@@ -49,6 +49,7 @@ For example, `WITH t AS (SELECT properties AS props FROM events) SELECT t.props.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.+Multi-part names also retain distinct identities when their parser-safe forms coincide, such as `a.b.c_d` and `a.b_c.d`.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.@@ -98,13 +99,21 @@ curl -sS -X PUT http://localhost:8091/teams/2/users/17/catalog \"revision": "schema-42:permissions-9","catalog": {"tables": {- "events": {"name": "events", "type": "posthog", "fields": {}}+ "events": {"name": "events", "type": "posthog", "fields": {}},+ "postgres.demo.orders": {"name": "postgres.demo.orders", "type": "data_warehouse", "fields": {}}},+ "tableAliases": {"demo_postgres_orders": "postgres.demo.orders"},"properties": {"event": [{"name": "$geo_city", "property_type": "String"}]}}}'```+`tableAliases` is optional. Each key is an accepted alternate table spelling, and each value must name a canonical key in `tables`.+An alias and its canonical table share prepared fields, but validation retains the spelling used in SQL in `tableNames`.+An identity entry such as `"events": "events"` is a no-op.+Publication rejects empty names, aliases that replace another canonical key, and targets that create a dangling reference, chain, or cycle.+Catalogs without `tableAliases` keep the previous behavior.+Every protected route requires positive `teamId` and `userId` path parameters. The response includes`catalogRevision`, allowing Django and the editor to detect a stale response. An unknown, expired, or evicted pairreturns `404`; the service never falls back to another team or user.@@ -116,6 +125,10 @@ When `MAX_CATALOGS` (default `1024`) or `CATALOG_CACHE_MAX_BYTES` (default `8 Gicatalog is evicted. A catalog request is limited to `64 MiB`. Publishing a new revision replaces the old immutablecatalog atomically.+The generated scale fixture verifies publication, completion, pagination, and validation with 4,096 canonical tables, 25 fields per table, and 120,000 event properties for one user catalog.+Table fields and event properties are separate catalog entries.+This is a tested profile, not a count limit: admission still depends on the serialized request size and the prepared catalog's share of the cache byte budget.+Authentication is required unless `HOGQL_LANGUAGE_SERVICE_ALLOW_INSECURE=1` explicitly disables it on a loopbacklistener for local development. Insecure mode logs a startup warning and is rejected on non-loopback listeners.`HOGQL_LANGUAGE_SERVICE_SIGNING_KEYS` contains one or more comma-separated HMAC keys. Django sends a short-liveddiff --git a/services/hogql-language-service/benchmarks_test.go b/services/hogql-language-service/benchmarks_test.goindex 5b49f6085e39..0c916ddb32f8 100644--- a/services/hogql-language-service/benchmarks_test.go+++ b/services/hogql-language-service/benchmarks_test.go@@ -1,25 +1,30 @@package hogqllanguageservice_testimport (+ "bytes""encoding/json""fmt"+ "io"+ "log/slog"+ "net/http"+ "net/http/httptest""strings""testing""time""github.com/PostHog/posthog/services/hogql-language-service/internal/catalog""github.com/PostHog/posthog/services/hogql-language-service/internal/completion"+ "github.com/PostHog/posthog/services/hogql-language-service/internal/httpapi"+ "github.com/PostHog/posthog/services/hogql-language-service/internal/ratelimit""github.com/PostHog/posthog/services/hogql-language-service/internal/serviceauth""github.com/PostHog/posthog/services/hogql-language-service/internal/validation")const (- syntheticTableCount = 4096- syntheticFieldsPerTable = 25- syntheticPropertyCount = 100000- syntheticNamespaceCount = 4- syntheticPropertiesPerNS = syntheticPropertyCount / syntheticNamespaceCount- cursorMarker = "§"+ syntheticTableCount = 4096+ syntheticFieldsPerTable = 25+ syntheticPropertyCount = 120000+ cursorMarker = "§")const sessionActorQuery = `@@ -152,7 +157,8 @@ func BenchmarkCompleteLargeCatalog(b *testing.B) {eventQuery, eventPosition := queryAndPosition(eventJourneyQuery)cases := []completionCase{{name: "table broad prefix", query: "SELECT * FROM warehouse_table_", position: len("SELECT * FROM warehouse_table_")},- {name: "field broad prefix", query: "SELECT w.column_ FROM warehouse_table_2048 AS w", position: len("SELECT w.column_")},+ {name: "alias broad prefix", query: "SELECT * FROM legacy_warehouse_table_", position: len("SELECT * FROM legacy_warehouse_table_")},+ {name: "field broad prefix", query: "SELECT w. FROM warehouse_table_2048 AS w", position: len("SELECT w.")},{name: "event property broad prefix", query: "SELECT properties.$event_property_ FROM events", position: len("SELECT properties.$event_property_")},{name: "event property selective prefix", query: "SELECT properties.$event_property_249 FROM events", position: len("SELECT properties.$event_property_249")},{name: "large session query", query: sessionQuery, position: sessionPosition},@@ -181,7 +187,7 @@ func BenchmarkValidateLargeCatalog(b *testing.B) {{name: "large event query", query: eventQuery},{name: "large trace query", query: traceQuery},{name: "unknown table", query: "SELECT column_00 FROM warehouse_tabel_2048"},- {name: "unknown event property", query: "SELECT properties.$event_property_25000 FROM events"},+ {name: "unknown event property", query: "SELECT properties.$event_property_120000 FROM events"},} {b.Run(benchmark.name, func(b *testing.B) {benchmarkValidation(b, schema, benchmark.query)@@ -189,6 +195,106 @@ func BenchmarkValidateLargeCatalog(b *testing.B) {}}+func TestLargeCatalogSupportedScale(t *testing.T) {+ schema := largeSyntheticCatalog()+ if len(schema.Tables) != syntheticTableCount {+ t.Fatalf("tables = %d, want %d", len(schema.Tables), syntheticTableCount)+ }+ for name, table := range schema.Tables {+ if len(table.Fields) != syntheticFieldsPerTable {+ t.Fatalf("table %q fields = %d, want %d", name, len(table.Fields), syntheticFieldsPerTable)+ }+ }+ if len(schema.Properties) != 1 || len(schema.Properties["event"]) != syntheticPropertyCount {+ t.Fatalf("property namespaces = %d, event properties = %d", len(schema.Properties), len(schema.Properties["event"]))+ }++ update := catalogUpdate{Revision: "supported-scale", Catalog: *schema}+ payload, err := json.Marshal(update)+ if err != nil {+ t.Fatal(err)+ }+ registry := catalog.NewRegistry(1024, 8<<30, time.Hour)+ limiterConfig := ratelimit.Config{Capacity: 10, RefillPerSec: 10, MaxEntries: 10, IdleTTL: time.Hour}+ preAuthLimiter, err := ratelimit.New(limiterConfig)+ if err != nil {+ t.Fatal(err)+ }+ principalLimiter, err := ratelimit.New(limiterConfig)+ if err != nil {+ t.Fatal(err)+ }+ handler := httpapi.NewHandler(httpapi.Config{+ Catalogs: registry,+ Auth: serviceauth.New(nil, true),+ PreAuthLimiter: preAuthLimiter,+ PrincipalLimiter: principalLimiter,+ Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),+ })+ request := httptest.NewRequest(http.MethodPut, "/teams/1/users/1/catalog", bytes.NewReader(payload))+ request.Header.Set("Content-Type", "application/json")+ response := httptest.NewRecorder()+ handler.ServeHTTP(response, request)+ if response.Code != http.StatusOK {+ t.Fatalf("catalog publication returned %d: %s", response.Code, response.Body.String())+ }+ prepared, revision, ok := registry.Get(serviceauth.Authorization{TeamID: 1, UserID: 1})+ if !ok {+ t.Fatal("published catalog was not found")+ }+ if revision != update.Revision || prepared.TableCount() != syntheticTableCount || prepared.PropertyCount() != syntheticPropertyCount {+ t.Fatalf("published catalog = revision %q, found %t, tables %d, properties %d", revision, ok, prepared.TableCount(), prepared.PropertyCount())+ }++ for _, test := range []struct {+ query string+ position int+ total int+ }{+ {query: "SELECT * FROM warehouse_table_", total: syntheticTableCount - 3},+ {query: "SELECT * FROM legacy_warehouse_table_", total: syntheticTableCount - 3},+ {query: "SELECT w. FROM warehouse_table_2048 AS w", position: len("SELECT w."), total: syntheticFieldsPerTable},+ {query: "SELECT properties.$event_property_ FROM events", position: len("SELECT properties.$event_property_"), total: syntheticPropertyCount},+ } {+ position := test.position+ if position == 0 {+ position = len(test.query)+ }+ result, err := completion.Complete(prepared, test.query, position, completion.PositionEncodingUTF8, "")+ if err != nil {+ t.Fatalf("complete %q: %v", test.query, err)+ }+ if result.Total != test.total || len(result.Suggestions) != completion.PageSize {+ t.Fatalf("complete %q returned total %d, page %d, cursor %q", test.query, result.Total, len(result.Suggestions), result.NextCursor)+ }+ if test.total == completion.PageSize {+ if result.NextCursor != "" {+ t.Fatalf("complete %q returned unexpected cursor %q", test.query, result.NextCursor)+ }+ continue+ }+ if result.NextCursor == "" {+ t.Fatalf("complete %q did not return a second-page cursor", test.query)+ }+ second, err := completion.Complete(prepared, test.query, position, completion.PositionEncodingUTF8, result.NextCursor)+ if err != nil {+ t.Fatalf("complete second page %q: %v", test.query, err)+ }+ if second.Total != test.total || len(second.Suggestions) == 0 || second.Suggestions[0].Label == result.Suggestions[0].Label {+ t.Fatalf("complete second page %q returned %#v", test.query, second)+ }+ }++ for _, query := range []string{+ "SELECT column_24 FROM legacy_warehouse_table_2048",+ "SELECT properties.$event_property_119999 FROM events",+ } {+ if result := validation.Validate(prepared, query); !result.Valid {+ t.Fatalf("validate %q returned %#v", query, result)+ }+ }+}+func BenchmarkCatalogPublication(b *testing.B) {schema := largeSyntheticCatalog()update := catalogUpdate{Revision: "synthetic-revision", Catalog: *schema}@@ -314,6 +420,7 @@ func queryAndPosition(marked string) (string, int) {func largeSyntheticCatalog() *catalog.Catalog {tables := make(map[string]catalog.Table, syntheticTableCount)+ tableAliases := make(map[string]string, syntheticTableCount-3)for tableIndex := 0; tableIndex < syntheticTableCount-3; tableIndex++ {fields := make(map[string]catalog.Field, syntheticFieldsPerTable)for fieldIndex := 0; fieldIndex < syntheticFieldsPerTable; fieldIndex++ {@@ -322,37 +429,35 @@ func largeSyntheticCatalog() *catalog.Catalog {}name := fmt.Sprintf("warehouse_table_%04d", tableIndex)tables[name] = catalog.Table{ID: fmt.Sprintf("table-%04d", tableIndex), Name: name, Type: "data_warehouse", Fields: fields}+ tableAliases[fmt.Sprintf("legacy_warehouse_table_%04d", tableIndex)] = name}- tables["events"] = catalog.Table{Name: "events", Type: "posthog", Fields: fields(+ tables["events"] = catalog.Table{Name: "events", Type: "posthog", Fields: scaleFields("distinct_id", "event", "person_id", "properties", "session_id", "timestamp", "uuid",)}- tables["sessions"] = catalog.Table{Name: "sessions", Type: "posthog", Fields: fields(+ tables["sessions"] = catalog.Table{Name: "sessions", Type: "posthog", Fields: scaleFields("$autocapture_count", "$channel_type", "$end_timestamp", "$entry_pathname", "$entry_referring_domain","$entry_utm_campaign", "$entry_utm_content", "$entry_utm_medium", "$entry_utm_source", "$entry_utm_term","$exit_pathname", "$last_external_click_url", "$num_uniq_urls", "$pageview_count", "$session_duration","$start_timestamp", "session_id",)}- tables["posthog.trace_spans"] = catalog.Table{Name: "posthog.trace_spans", Type: "posthog", Fields: fields(+ tables["posthog.trace_spans"] = catalog.Table{Name: "posthog.trace_spans", Type: "posthog", Fields: scaleFields("duration_nano", "name", "parent_span_id", "service_name", "span_id", "status_code", "timestamp", "trace_id",)}- properties := make(map[string][]catalog.Property, syntheticNamespaceCount)- for _, namespace := range []struct {- name string- prefix string- }{- {name: "event", prefix: "$event_property_"},- {name: "person", prefix: "$person_property_"},- {name: "group:0", prefix: "$group_property_"},- {name: "session", prefix: "$session_property_"},- } {- values := make([]catalog.Property, syntheticPropertiesPerNS)- for propertyIndex := range values {- values[propertyIndex] = catalog.Property{Name: fmt.Sprintf("%s%05d", namespace.prefix, propertyIndex), ValueType: "String"}- }- properties[namespace.name] = values+ properties := make([]catalog.Property, syntheticPropertyCount)+ for propertyIndex := range properties {+ properties[propertyIndex] = catalog.Property{Name: fmt.Sprintf("$event_property_%05d", propertyIndex), ValueType: "String"}}- return &catalog.Catalog{Tables: tables, Properties: properties}+ return &catalog.Catalog{Tables: tables, TableAliases: tableAliases, Properties: map[string][]catalog.Property{"event": properties}}+}++func scaleFields(names ...string) map[string]catalog.Field {+ result := fields(names...)+ for fieldIndex := len(result); fieldIndex < syntheticFieldsPerTable; fieldIndex++ {+ name := fmt.Sprintf("scale_column_%02d", fieldIndex)+ result[name] = catalog.Field{Name: name, Type: "String"}+ }+ return result}func fields(names ...string) map[string]catalog.Field {diff --git a/services/hogql-language-service/cmd/demo/catalog.go b/services/hogql-language-service/cmd/demo/catalog.goindex c225b34bc4f6..8e2d6efe4606 100644--- a/services/hogql-language-service/cmd/demo/catalog.go+++ b/services/hogql-language-service/cmd/demo/catalog.go@@ -71,5 +71,9 @@ 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-v2", Catalog: catalog.Catalog{Tables: tables, Properties: properties}}+ return catalogPublication{Revision: "synthetic-demo-v3", Catalog: catalog.Catalog{+ Tables: tables,+ TableAliases: map[string]string{"demo_postgres_orders": "postgres.demo.orders"},+ Properties: properties,+ }}}diff --git a/services/hogql-language-service/internal/analysis/document.go b/services/hogql-language-service/internal/analysis/document.goindex fd9fcd4894f9..06866efbb0bd 100644--- a/services/hogql-language-service/internal/analysis/document.go+++ b/services/hogql-language-service/internal/analysis/document.go@@ -22,7 +22,7 @@ type Document struct {type Statement struct {expr clickhouse.Exprschema *catalog.PreparedCatalog- originalTableNames map[string]string+ originalTableNames map[int]stringbudget *projectionBudgetscopes []*queryScopetables []TableReference@@ -105,14 +105,14 @@ func (s *Statement) analyze() {if scope == nil {return true}+ if original, exists := s.originalTableNames[start]; exists {+ name = original+ implicitAlias = strings.ReplaceAll(original, ".", "__")+ }if cte := resolveCTE(scope, name, start); cte != nil {addBinding(scope, name, alias, Relation{name: cte.name, cte: cte}, start, end)return true}- if original, exists := s.originalTableNames[name]; exists {- name = original- implicitAlias = strings.ReplaceAll(original, ".", "__")- }table, exists := s.schema.Table(name)s.tables = append(s.tables, TableReference{Name: name, Start: start, End: end, Known: exists})if exists {@@ -286,7 +286,7 @@ func (b Bindings) PropertyNamespace(parts []string) (string, bool) {}continue}- names[name] = relation.name+ names[name] = relation.table.Name}return propertyresolver.Resolve(parts, names)}diff --git a/services/hogql-language-service/internal/analysis/scopes.go b/services/hogql-language-service/internal/analysis/scopes.goindex cc39dea14739..0465e308460e 100644--- a/services/hogql-language-service/internal/analysis/scopes.go+++ b/services/hogql-language-service/internal/analysis/scopes.go@@ -299,9 +299,9 @@ func (s *queryScope) unqualifiedPropertyNamespace(name string) (string, bool, boreturn resolved.name, resolved.ok, resolved.matched}-func normalizeHogQLTableReferences(query string) (string, map[string]string) {+func normalizeHogQLTableReferences(query string) (string, map[int]string) {normalized := []byte(query)- originalNames := map[string]string{}+ originalNames := map[int]string{}for _, indexes := range tableReferencePattern.FindAllStringSubmatchIndex(query, -1) {start, end := indexes[2], indexes[3]name := query[start:end]@@ -314,7 +314,7 @@ func normalizeHogQLTableReferences(query string) (string, map[string]string) {normalized[index] = '_'}}- originalNames[string(normalized[start:end])] = name+ originalNames[start] = 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{binding.name: binding.name})+ return propertyresolver.Resolve([]string{binding.table.Name, name, "property"}, nil)}if binding.cte == nil {return "", falsediff --git a/services/hogql-language-service/internal/catalog/catalog.go b/services/hogql-language-service/internal/catalog/catalog.goindex 45890638f717..1b33d3e89fbd 100644--- a/services/hogql-language-service/internal/catalog/catalog.go+++ b/services/hogql-language-service/internal/catalog/catalog.go@@ -26,8 +26,9 @@ type Property struct {}type Catalog struct {- Tables map[string]Table `json:"tables"`- Properties map[string][]Property `json:"properties"`+ Tables map[string]Table `json:"tables"`+ TableAliases map[string]string `json:"tableAliases,omitempty"`+ Properties map[string][]Property `json:"properties"`}type Entry struct {@@ -47,12 +48,14 @@ type PreparedTable struct {type PreparedCatalog struct {tables Index+ tableSpellings IndextablesByName map[string]inttableValues []PreparedTableproperties map[string]*Indexvalid booltableCount intpropertyCount int+ hasAliases boolestimatedBytes int64}@@ -64,7 +67,7 @@ func Prepare(value *Catalog) *PreparedCatalog {tablesByName: make(map[string]int, len(value.Tables)),tableValues: make([]PreparedTable, 0, len(value.Tables)),properties: make(map[string]*Index, len(value.Properties)),- valid: value.Tables != nil && value.Properties != nil,+ valid: ValidateCatalog(value) == nil,tableCount: len(value.Tables),}fieldCount := 0@@ -86,6 +89,21 @@ func Prepare(value *Catalog) *PreparedCatalog {tableEntries = append(tableEntries, newEntry(name, tableType))}prepared.tables = newIndex(tableEntries)+ prepared.tableSpellings = prepared.tables+ if prepared.valid {+ spellingEntries := slices.Clone(tableEntries)+ for alias, target := range value.TableAliases {+ if alias == target {+ continue+ }+ prepared.hasAliases = true+ prepared.tablesByName[alias] = prepared.tablesByName[target]+ spellingEntries = append(spellingEntries, newEntry(alias, target))+ }+ if prepared.hasAliases {+ prepared.tableSpellings = newIndex(spellingEntries)+ }+ }for namespace, properties := range value.Properties {entries := make([]Entry, len(properties))for index, property := range properties {@@ -111,6 +129,60 @@ func (c *PreparedCatalog) Tables() *Index {return &c.tables}+func (c *PreparedCatalog) TableSpellings() *Index {+ return &c.tableSpellings+}++func (c *PreparedCatalog) TableSuggestions(prefix string, excluded map[string]bool) []Entry {+ if !c.hasAliases {+ candidates := c.tables.Prefix(prefix)+ if len(excluded) == 0 {+ return candidates+ }+ result := make([]Entry, 0, len(candidates))+ for _, candidate := range candidates {+ if !excluded[candidate.Name] {+ result = append(result, candidate)+ }+ }+ return result+ }+ candidates := c.tableSpellings.Prefix(prefix)+ canonicalMatches := make(map[int]bool, len(candidates))+ for _, candidate := range candidates {+ if excluded[candidate.Name] {+ continue+ }+ index := c.tablesByName[candidate.Name]+ if c.tableValues[index].Name == candidate.Name {+ canonicalMatches[index] = true+ }+ }+ seen := make(map[int]bool, len(candidates))+ result := make([]Entry, 0, len(candidates))+ for _, candidate := range candidates {+ if excluded[candidate.Name] {+ continue+ }+ index := c.tablesByName[candidate.Name]+ canonical := c.tableValues[index].Name == candidate.Name+ if seen[index] || (!canonical && canonicalMatches[index]) {+ continue+ }+ seen[index] = true+ result = append(result, candidate)+ }+ return result+}++func (c *PreparedCatalog) CanonicalTableName(name string) (string, bool) {+ table, ok := c.Table(name)+ if !ok {+ return "", false+ }+ return table.Name, true+}+func (c *PreparedCatalog) Properties(namespace string) *Index {return c.properties[namespace]}@@ -200,6 +272,15 @@ func (c *PreparedCatalog) estimateSize() int64 {size += entrySize(field)}}+ if c.hasAliases {+ for _, entry := range c.tableSpellings.entries {+ if c.tableValues[c.tablesByName[entry.Name]].Name == entry.Name {+ size += 32+ continue+ }+ size += entrySize(entry) + 32+ }+ }for namespace, properties := range c.properties {size += int64(len(namespace) + 64)for _, property := range properties.entries {diff --git a/services/hogql-language-service/internal/catalog/catalog_test.go b/services/hogql-language-service/internal/catalog/catalog_test.goindex 6b44c9df465e..05927b07f6ff 100644--- a/services/hogql-language-service/internal/catalog/catalog_test.go+++ b/services/hogql-language-service/internal/catalog/catalog_test.go@@ -59,3 +59,61 @@ func TestPreparedCatalogRetainsCaseVariantTables(t *testing.T) {t.Fatalf("Prefix(\"EV\") = %#v", prefix)}}++func TestPreparedCatalogResolvesAliasesToCanonicalTables(t *testing.T) {+ prepared := Prepare(&Catalog{+ Tables: map[string]Table{+ "postgres.demo.orders": {Type: "data_warehouse", Fields: map[string]Field{"id": {Type: "integer"}}},+ },+ TableAliases: map[string]string{"demo_postgres_orders": "postgres.demo.orders"},+ Properties: map[string][]Property{},+ })++ canonical, canonicalOK := prepared.Table("postgres.demo.orders")+ alias, aliasOK := prepared.Table("demo_postgres_orders")+ if !canonicalOK || !aliasOK || canonical != alias {+ t.Fatalf("alias and canonical lookup did not share a prepared table: canonical=%p alias=%p", canonical, alias)+ }+ if _, ok := prepared.Table("Demo_postgres_orders"); ok {+ t.Fatal("alias lookup ignored exact case")+ }+ if field, ok := alias.Fields.Exact("id"); !ok || field.Type != "integer" {+ t.Fatalf("alias fields = %#v, %t", field, ok)+ }+}++func TestValidateCatalogRejectsInvalidAliases(t *testing.T) {+ base := func(aliases map[string]string) *Catalog {+ return &Catalog{+ Tables: map[string]Table{+ "orders": {Fields: map[string]Field{}},+ "events": {Fields: map[string]Field{}},+ },+ TableAliases: aliases,+ Properties: map[string][]Property{},+ }+ }++ for name, aliases := range map[string]map[string]string{+ "empty alias": {"": "orders"},+ "empty target": {"legacy_orders": ""},+ "dangling target": {"legacy_orders": "missing"},+ "chain": {"legacy_orders": "older_orders", "older_orders": "orders"},+ "cycle": {"legacy_orders": "older_orders", "older_orders": "legacy_orders"},+ "canonical collision": {"orders": "events"},+ } {+ t.Run(name, func(t *testing.T) {+ value := base(aliases)+ if err := ValidateCatalog(value); err == nil {+ t.Fatal("invalid alias map was accepted")+ }+ if prepared := Prepare(value); prepared == nil || prepared.valid {+ t.Fatalf("prepared invalid catalog = %#v", prepared)+ }+ })+ }++ if err := ValidateCatalog(base(map[string]string{"orders": "orders"})); err != nil {+ t.Fatalf("canonical identity alias was rejected: %v", err)+ }+}diff --git a/services/hogql-language-service/internal/catalog/registry.go b/services/hogql-language-service/internal/catalog/registry.goindex fe3e455919df..16a3e4a8a0a2 100644--- a/services/hogql-language-service/internal/catalog/registry.go+++ b/services/hogql-language-service/internal/catalog/registry.go@@ -12,6 +12,7 @@ var (ErrInvalidScope = errors.New("team ID and user ID must be positive")ErrInvalidRevision = errors.New("invalid catalog revision")ErrInvalidCatalog = errors.New("catalog must contain tables and properties")+ ErrInvalidAliases = errors.New("table aliases must map non-empty alternate names directly to canonical table keys")ErrCatalogTooLarge = errors.New("catalog exceeds cache capacity"))@@ -58,6 +59,17 @@ func ValidateCatalog(value *Catalog) error {if value == nil || value.Tables == nil || value.Properties == nil {return ErrInvalidCatalog}+ for alias, target := range value.TableAliases {+ if alias == "" || target == "" {+ return ErrInvalidAliases+ }+ if _, targetExists := value.Tables[target]; !targetExists {+ return ErrInvalidAliases+ }+ if _, aliasIsCanonical := value.Tables[alias]; aliasIsCanonical && alias != target {+ return ErrInvalidAliases+ }+ }return nil}diff --git a/services/hogql-language-service/internal/catalog/registry_test.go b/services/hogql-language-service/internal/catalog/registry_test.goindex 3418da213f24..071f25b08dd3 100644--- a/services/hogql-language-service/internal/catalog/registry_test.go+++ b/services/hogql-language-service/internal/catalog/registry_test.go@@ -1,6 +1,7 @@package catalogimport (+ "strings""testing""time"@@ -116,3 +117,28 @@ func TestRegistryEvictsCatalogsToStayWithinMemoryBudget(t *testing.T) {t.Fatal("new catalog was not retained")}}++func TestRegistryCountsAliasesAgainstMemoryBudget(t *testing.T) {+ canonicalName := "orders." + strings.Repeat("canonical", 32)+ aliasName := "demo_" + strings.Repeat("alias", 32)+ base := &Catalog{Tables: map[string]Table{canonicalName: {Fields: map[string]Field{"id": {Type: "integer"}}}}, Properties: map[string][]Property{}}+ withAlias := &Catalog{+ Tables: base.Tables,+ TableAliases: map[string]string{aliasName: strings.Clone(canonicalName)},+ Properties: base.Properties,+ }+ baseSize := Prepare(base).EstimatedBytes()+ aliased := Prepare(withAlias)+ expectedAliasBytes := int64(len(aliasName) + len(canonicalName) + 96)+ if actual := aliased.EstimatedBytes() - baseSize; actual != expectedAliasBytes {+ t.Fatalf("alias bytes = %d, want %d", actual, expectedAliasBytes)+ }+ rightSized := NewRegistry(1, baseSize+expectedAliasBytes, time.Hour)+ if err := rightSized.Put(serviceauth.Authorization{TeamID: 1, UserID: 10}, "1", aliased); err != nil {+ t.Fatalf("Put() error = %v for exact derived budget", err)+ }+ registry := NewRegistry(1, baseSize, time.Hour)+ if err := registry.Put(serviceauth.Authorization{TeamID: 1, UserID: 10}, "1", aliased); err != ErrCatalogTooLarge {+ t.Fatalf("Put() error = %v, want %v", err, ErrCatalogTooLarge)+ }+}diff --git a/services/hogql-language-service/internal/completion/completion_test.go b/services/hogql-language-service/internal/completion/completion_test.goindex e76d92cc78e0..908b85ea8287 100644--- a/services/hogql-language-service/internal/completion/completion_test.go+++ b/services/hogql-language-service/internal/completion/completion_test.go@@ -94,6 +94,58 @@ func TestCompletesPropertiesForGenericNamespaces(t *testing.T) {}}+func TestTableAliasesUseCanonicalPropertyOrigins(t *testing.T) {+ properties := map[string][]catalog.Property{+ "event": {{Name: "$browser", ValueType: "String"}},+ "person": {{Name: "email", ValueType: "String"}},+ }+ for _, test := range []struct {+ name string+ tables map[string]catalog.Table+ aliases map[string]string+ query string+ expected string+ excluded string+ }{+ {+ name: "ordinary alias",+ tables: map[string]catalog.Table{"events": {Fields: map[string]catalog.Field{"properties": {Type: "json"}}}},+ aliases: map[string]string{"legacy_events": "events"},+ query: "SELECT legacy_events.properties.$br FROM legacy_events",+ expected: "$browser",+ },+ {+ name: "misleading person alias",+ tables: map[string]catalog.Table{"events": {Fields: map[string]catalog.Field{"properties": {Type: "json"}}}},+ aliases: map[string]string{"persons": "events"},+ query: "SELECT persons.properties.$br FROM persons",+ expected: "$browser",+ excluded: "email",+ },+ {+ name: "event-like warehouse alias",+ tables: map[string]catalog.Table{"warehouse_records": {Fields: map[string]catalog.Field{"properties": {Type: "json"}}}},+ aliases: map[string]string{"events": "warehouse_records"},+ query: "SELECT events.properties.$br FROM events",+ excluded: "$browser",+ },+ } {+ t.Run(test.name, func(t *testing.T) {+ prepared := catalog.Prepare(&catalog.Catalog{Tables: test.tables, TableAliases: test.aliases, Properties: properties})+ result, err := Complete(prepared, test.query, strings.Index(test.query, " FROM "), PositionEncodingUTF8, "")+ if err != nil {+ t.Fatal(err)+ }+ if test.expected != "" && !hasSuggestion(result.Suggestions, test.expected) {+ t.Fatalf("query %q returned %#v", test.query, result)+ }+ if test.excluded != "" && hasSuggestion(result.Suggestions, test.excluded) {+ t.Fatalf("query %q returned excluded property %#v", test.query, result)+ }+ })+ }+}+func TestCompletesFieldsForHogQLQualifiedTable(t *testing.T) {query := "SELECT s. FROM postgres.synced.orders AS s"result, err := Complete(testCatalog(), query, len("SELECT s."), PositionEncodingUTF8, "")@@ -105,6 +157,49 @@ func TestCompletesFieldsForHogQLQualifiedTable(t *testing.T) {}}+func TestCompletesFieldsForCollidingNormalizedTableReferences(t *testing.T) {+ fieldTable := func(name, field string) catalog.Table {+ return catalog.Table{Name: name, Type: "data_warehouse", Fields: map[string]catalog.Field{field: {Name: field, Type: "string"}}}+ }+ for _, test := range []struct {+ name string+ catalog *catalog.Catalog+ }{+ {+ name: "canonical tables",+ catalog: &catalog.Catalog{Tables: map[string]catalog.Table{+ "a.b.c_d": fieldTable("a.b.c_d", "left_field"),+ "a.b_c.d": fieldTable("a.b_c.d", "right_field"),+ }},+ },+ {+ name: "alias and canonical table",+ catalog: &catalog.Catalog{+ Tables: map[string]catalog.Table{+ "left_target": fieldTable("left_target", "left_field"),+ "a.b_c.d": fieldTable("a.b_c.d", "right_field"),+ },+ TableAliases: map[string]string{"a.b.c_d": "left_target"},+ },+ },+ } {+ t.Run(test.name, func(t *testing.T) {+ test.catalog.Properties = map[string][]catalog.Property{}+ prepared := catalog.Prepare(test.catalog)+ query := "SELECT l. FROM a.b.c_d AS l JOIN a.b_c.d AS r ON 1 = 1"+ left, err := Complete(prepared, query, len("SELECT l."), PositionEncodingUTF8, "")+ if err != nil || len(left.Suggestions) != 1 || left.Suggestions[0].Label != "left_field" {+ t.Fatalf("left completion = %#v, error = %v", left, err)+ }+ query = "SELECT r. FROM a.b.c_d AS l JOIN a.b_c.d AS r ON 1 = 1"+ right, err := Complete(prepared, query, len("SELECT r."), PositionEncodingUTF8, "")+ if err != nil || len(right.Suggestions) != 1 || right.Suggestions[0].Label != "right_field" {+ t.Fatalf("right completion = %#v, error = %v", right, err)+ }+ })+ }+}+func TestCompletesTablesAfterFrom(t *testing.T) {for _, test := range []struct {name, query string@@ -149,6 +244,38 @@ func TestCompletesTablesAfterFrom(t *testing.T) {}}+func TestCompletesOneSpellingPerAliasedTableAndHonorsExactCTEShadowing(t *testing.T) {+ prepared := catalog.Prepare(&catalog.Catalog{+ Tables: map[string]catalog.Table{+ "postgres.demo.orders": {Type: "data_warehouse", Fields: map[string]catalog.Field{"id": {Type: "integer"}}},+ "events": {Type: "posthog", Fields: map[string]catalog.Field{"uuid": {Type: "uuid"}}},+ },+ TableAliases: map[string]string{"demo_postgres_orders": "postgres.demo.orders"},+ Properties: map[string][]catalog.Property{},+ })+ for _, test := range []struct {+ query string+ expected []string+ }{+ {query: "SELECT * FROM ", expected: []string{"events", "postgres.demo.orders"}},+ {query: "SELECT * FROM demo_", expected: []string{"demo_postgres_orders"}},+ {query: "WITH demo_postgres_orders AS (SELECT uuid FROM events) SELECT * FROM ", expected: []string{"demo_postgres_orders", "events", "postgres.demo.orders"}},+ {query: "WITH `postgres.demo.orders` AS (SELECT uuid FROM events) SELECT * FROM ", expected: []string{"postgres.demo.orders", "demo_postgres_orders", "events"}},+ } {+ result, err := Complete(prepared, test.query, len(test.query), PositionEncodingUTF8, "")+ if err != nil {+ t.Fatal(err)+ }+ labels := make([]string, len(result.Suggestions))+ for index, suggestion := range result.Suggestions {+ labels[index] = suggestion.Label+ }+ if strings.Join(labels, ",") != strings.Join(test.expected, ",") {+ t.Fatalf("query %q returned %#v", test.query, result)+ }+ }+}+func TestCompletesFieldsForAlias(t *testing.T) {type testCase struct {name, query string@@ -987,6 +1114,37 @@ func TestCompletionPagesWithoutSkippingOrRepeatingTables(t *testing.T) {}}+func TestAliasCompletionPagesWithoutRepeatingCanonicalTargets(t *testing.T) {+ value := &catalog.Catalog{Tables: map[string]catalog.Table{}, TableAliases: map[string]string{}, Properties: map[string][]catalog.Property{}}+ for index := range 30 {+ canonical := fmt.Sprintf("postgres.demo.table_%02d", index)+ alias := fmt.Sprintf("demo_postgres_table_%02d", index)+ value.Tables[canonical] = catalog.Table{Type: "data_warehouse", Fields: map[string]catalog.Field{}}+ value.TableAliases[alias] = canonical+ }+ prepared := catalog.Prepare(value)+ query := "SELECT * FROM demo_postgres_table_"+ first, err := Complete(prepared, query, len(query), PositionEncodingUTF8, "")+ if err != nil {+ t.Fatal(err)+ }+ second, err := Complete(prepared, query, len(query), PositionEncodingUTF8, first.NextCursor)+ if err != nil {+ t.Fatal(err)+ }+ all := append(first.Suggestions, second.Suggestions...)+ if first.Total != 30 || second.Total != 30 || len(all) != 30 || second.NextCursor != "" {+ t.Fatalf("pages = %#v, %#v", first, second)+ }+ for index, suggestion := range all {+ expectedAlias := fmt.Sprintf("demo_postgres_table_%02d", index)+ expectedCanonical := fmt.Sprintf("postgres.demo.table_%02d", index)+ if suggestion.Label != expectedAlias || suggestion.Detail != expectedCanonical {+ t.Fatalf("suggestion %d = %#v", index, suggestion)+ }+ }+}+func hasSuggestion(suggestions []Suggestion, label string) bool {for _, suggestion := range suggestions {if suggestion.Label == label {diff --git a/services/hogql-language-service/internal/completion/tables.go b/services/hogql-language-service/internal/completion/tables.goindex 76e5ad86e1dd..5df4c9984ff8 100644--- a/services/hogql-language-service/internal/completion/tables.go+++ b/services/hogql-language-service/internal/completion/tables.go@@ -11,7 +11,7 @@ import (func tableResult(schema *catalog.PreparedCatalog, bindings analysis.Bindings, prefix string, offset int, parseErr error) Result {ctes := slices.Collect(bindings.CTENames(prefix))if len(ctes) == 0 {- return indexedResult(slices.Values(schema.Tables().Prefix(prefix)), "table", offset, parseErr)+ return indexedResult(slices.Values(schema.TableSuggestions(prefix, nil)), "table", offset, parseErr)}slices.SortFunc(ctes, func(left, right catalog.Entry) int {if comparison := strings.Compare(strings.ToLower(left.Name), strings.ToLower(right.Name)); comparison != 0 {@@ -23,9 +23,7 @@ func tableResult(schema *catalog.PreparedCatalog, bindings analysis.Bindings, prshadowed := map[string]bool{}for _, cte := range ctes {cteNames[cte.Name] = true- if table, ok := schema.Table(cte.Name); ok {- shadowed[table.Name] = true- }+ shadowed[cte.Name] = true}entries := func(yield func(catalog.Entry) bool) {for _, cte := range ctes {@@ -33,8 +31,8 @@ func tableResult(schema *catalog.PreparedCatalog, bindings analysis.Bindings, prreturn}}- for _, table := range schema.Tables().Prefix(prefix) {- if !shadowed[table.Name] && !yield(table) {+ for _, table := range schema.TableSuggestions(prefix, shadowed) {+ if !yield(table) {return}}diff --git a/services/hogql-language-service/internal/httpapi/handler_test.go b/services/hogql-language-service/internal/httpapi/handler_test.goindex 3ccb64e115a7..7873fca25ce3 100644--- a/services/hogql-language-service/internal/httpapi/handler_test.go+++ b/services/hogql-language-service/internal/httpapi/handler_test.go@@ -95,6 +95,61 @@ func TestAutocompleteRequiresKnownTeamAndUser(t *testing.T) {}}+func TestCatalogAliasesStayWithinPublishedTeamAndUser(t *testing.T) {+ s := newTestServer(t)+ handler := s.handler()+ body := `{"revision":"aliases","catalog":{"tables":{"postgres.demo.orders":{"type":"data_warehouse","fields":{"id":{"type":"integer"}}}},"tableAliases":{"demo_postgres_orders":"postgres.demo.orders"},"properties":{}}}`+ request := httptest.NewRequest(http.MethodPut, scopePath(1, 10)+"/catalog", strings.NewReader(body))+ response := httptest.NewRecorder()+ handler.ServeHTTP(response, request)+ if response.Code != http.StatusOK {+ t.Fatalf("catalog upload returned %d: %s", response.Code, response.Body.String())+ }+ putCatalogForTest(t, handler, 1, 20, "without-aliases", "postgres.demo.orders")++ for _, test := range []struct {+ userID int64+ valid bool+ }{+ {userID: 10, valid: true},+ {userID: 20, valid: false},+ } {+ request = httptest.NewRequest(http.MethodPost, scopePath(1, test.userID)+"/validate", strings.NewReader(`{"query":"SELECT id FROM demo_postgres_orders"}`))+ response = httptest.NewRecorder()+ handler.ServeHTTP(response, request)+ if response.Code != http.StatusOK {+ t.Fatalf("validate returned %d: %s", response.Code, response.Body.String())+ }+ var result validationResponse+ if err := json.NewDecoder(response.Body).Decode(&result); err != nil {+ t.Fatal(err)+ }+ if result.Valid != test.valid {+ t.Fatalf("user %d result = %#v", test.userID, result)+ }+ }+}++func TestCatalogRejectsInvalidAliasMaps(t *testing.T) {+ handler := newTestServer(t).handler()+ for name, aliases := range map[string]string{+ "dangling": `{"legacy_orders":"missing"}`,+ "chain": `{"legacy_orders":"older_orders","older_orders":"orders"}`,+ "cycle": `{"legacy_orders":"older_orders","older_orders":"legacy_orders"}`,+ "collision": `{"orders":"events"}`,+ } {+ t.Run(name, func(t *testing.T) {+ body := `{"revision":"invalid","catalog":{"tables":{"orders":{"fields":{}},"events":{"fields":{}}},"tableAliases":` + aliases + `,"properties":{}}}`+ request := httptest.NewRequest(http.MethodPut, scopePath(1, 10)+"/catalog", strings.NewReader(body))+ response := httptest.NewRecorder()+ handler.ServeHTTP(response, request)+ if response.Code != http.StatusBadRequest || !strings.Contains(response.Body.String(), catalog.ErrInvalidAliases.Error()) {+ t.Fatalf("response = %d: %s", response.Code, response.Body.String())+ }+ })+ }+}+func TestValidateEncodesDiagnosticPositions(t *testing.T) {s := newTestServer(t)handler := s.handler()diff --git a/services/hogql-language-service/internal/validation/validation.go b/services/hogql-language-service/internal/validation/validation.goindex bd6a4c9935a9..cf1097aca078 100644--- a/services/hogql-language-service/internal/validation/validation.go+++ b/services/hogql-language-service/internal/validation/validation.go@@ -61,7 +61,7 @@ func Validate(schema *catalog.PreparedCatalog, query string) Result {if !table.Known && len(diagnostics) < querylimits.MaxDiagnostics {diagnostics = append(diagnostics, Diagnostic{Code: "unknown_table", Message: fmt.Sprintf("Unknown table %q", table.Name), Start: table.Start, End: table.End,- Suggestions: closest(table.Name, slices.Values(schema.Tables().Entries()), 5),+ Suggestions: closestTables(table.Name, schema, 5),})}}@@ -263,6 +263,17 @@ func validateUnqualifiedField(diagnostics *[]Diagnostic, seen map[string]bool, b}func closest(input string, candidates iter.Seq[catalog.Entry], limit int) []Suggestion {+ return closestBy(input, candidates, limit, func(entry catalog.Entry) string { return strings.ToLower(entry.Name) })+}++func closestTables(input string, schema *catalog.PreparedCatalog, limit int) []Suggestion {+ return closestBy(input, slices.Values(schema.TableSpellings().Entries()), limit, func(entry catalog.Entry) string {+ canonical, _ := schema.CanonicalTableName(entry.Name)+ return canonical+ })+}++func closestBy(input string, candidates iter.Seq[catalog.Entry], limit int, identity func(catalog.Entry) string) []Suggestion {if len(input) > querylimits.MaxSuggestionInputBytes {return nil}@@ -290,14 +301,20 @@ func closest(input string, candidates iter.Seq[catalog.Entry], limit int) []Suggcontinue}suggestion := Suggestion{Label: candidate.Name, Distance: distance}- duplicate := false- for _, existing := range best {- if strings.EqualFold(existing.Label, suggestion.Label) {- duplicate = true+ duplicate := -1+ candidateIdentity := identity(candidate)+ for index, existing := range best {+ existingIdentity := identity(catalog.Entry{Name: existing.Label})+ if existingIdentity == candidateIdentity {+ duplicate = indexbreak}}- if duplicate {+ if duplicate >= 0 {+ if suggestionLess(suggestion, best[duplicate]) {+ best[duplicate] = suggestion+ sortSuggestions(best)+ }continue}if len(best) < limit {diff --git a/services/hogql-language-service/internal/validation/validation_test.go b/services/hogql-language-service/internal/validation/validation_test.goindex 6f410ace434b..f1a2f3775a63 100644--- a/services/hogql-language-service/internal/validation/validation_test.go+++ b/services/hogql-language-service/internal/validation/validation_test.go@@ -190,6 +190,125 @@ func TestValidateAcceptsHogQLQualifiedTable(t *testing.T) {}}+func TestValidatePreservesCollidingNormalizedTableReferences(t *testing.T) {+ fieldTable := func(name, field string) catalog.Table {+ return catalog.Table{Name: name, Type: "data_warehouse", Fields: map[string]catalog.Field{field: {Name: field, Type: "string"}}}+ }+ for _, test := range []struct {+ name string+ catalog *catalog.Catalog+ query string+ tableNames string+ }{+ {+ name: "distinct canonical tables across statements and Unicode bytes",+ catalog: &catalog.Catalog{Tables: map[string]catalog.Table{+ "a.b.c_d": fieldTable("a.b.c_d", "left_field"),+ "a.b_c.d": fieldTable("a.b_c.d", "right_field"),+ }},+ query: "SELECT 'café'; SELECT l.left_field, r.right_field FROM a.b.c_d AS l JOIN a.b_c.d AS r ON 1 = 1",+ tableNames: "a.b.c_d,a.b_c.d",+ },+ {+ name: "alias and canonical table",+ catalog: &catalog.Catalog{+ Tables: map[string]catalog.Table{+ "left_target": fieldTable("left_target", "left_field"),+ "a.b_c.d": fieldTable("a.b_c.d", "right_field"),+ },+ TableAliases: map[string]string{"a.b.c_d": "left_target"},+ },+ query: "SELECT l.left_field, r.right_field FROM a.b.c_d AS l JOIN a.b_c.d AS r ON 1 = 1",+ tableNames: "a.b.c_d,a.b_c.d",+ },+ {+ name: "same target aliases keep implicit qualifiers",+ catalog: &catalog.Catalog{+ Tables: map[string]catalog.Table{"target": fieldTable("target", "shared_field")},+ TableAliases: map[string]string{+ "a.b.c_d": "target",+ "a.b_c.d": "target",+ },+ },+ query: "SELECT a__b__c_d.shared_field, a__b_c__d.shared_field FROM a.b.c_d JOIN a.b_c.d ON 1 = 1",+ tableNames: "a.b.c_d,a.b_c.d",+ },+ {+ name: "normalized and unchanged names",+ catalog: &catalog.Catalog{Tables: map[string]catalog.Table{+ "a.b.c_d": fieldTable("a.b.c_d", "left_field"),+ "a.b_c_d": fieldTable("a.b_c_d", "right_field"),+ }},+ query: "SELECT l.left_field, r.right_field FROM a.b.c_d AS l JOIN a.b_c_d AS r ON 1 = 1",+ tableNames: "a.b.c_d,a.b_c_d",+ },+ {+ name: "quoted normalized spelling CTE does not shadow",+ catalog: &catalog.Catalog{Tables: map[string]catalog.Table{+ "a.b.c_d": fieldTable("a.b.c_d", "left_field"),+ }},+ query: "WITH `a.b_c_d` AS (SELECT 1 AS cte_field) SELECT a__b__c_d.left_field FROM a.b.c_d",+ tableNames: "a.b.c_d",+ },+ } {+ t.Run(test.name, func(t *testing.T) {+ test.catalog.Properties = map[string][]catalog.Property{}+ result := Validate(catalog.Prepare(test.catalog), test.query)+ if !result.Valid || strings.Join(result.TableNames, ",") != test.tableNames {+ t.Fatalf("result = %#v", result)+ }+ })+ }+}++func TestValidateCatalogTableAliasesPreserveQuerySpellingAndOccurrences(t *testing.T) {+ value := &catalog.Catalog{+ Tables: map[string]catalog.Table{+ "postgres.demo.orders": {Type: "data_warehouse", Fields: map[string]catalog.Field{"id": {Type: "integer"}}},+ "events": {Type: "posthog", Fields: map[string]catalog.Field{"uuid": {Type: "uuid"}}},+ },+ TableAliases: map[string]string{"demo_postgres_orders": "postgres.demo.orders"},+ Properties: map[string][]catalog.Property{},+ }+ prepared := catalog.Prepare(value)++ for _, query := range []string{+ "SELECT id FROM demo_postgres_orders",+ "SELECT a.id, b.id FROM demo_postgres_orders AS a JOIN postgres.demo.orders AS b ON a.id = b.id",+ } {+ result := Validate(prepared, query)+ if !result.Valid {+ t.Fatalf("query %q returned %#v", query, result)+ }+ }+ result := Validate(prepared, "SELECT a.id, b.id FROM demo_postgres_orders AS a JOIN postgres.demo.orders AS b ON a.id = b.id")+ if strings.Join(result.TableNames, ",") != "demo_postgres_orders,postgres.demo.orders" {+ t.Fatalf("table names = %#v", result.TableNames)+ }++ cte := Validate(prepared, "WITH demo_postgres_orders AS (SELECT uuid FROM events) SELECT c.uuid, o.id FROM demo_postgres_orders AS c JOIN postgres.demo.orders AS o ON 1 = 1")+ if !cte.Valid || strings.Join(cte.TableNames, ",") != "events,postgres.demo.orders" {+ t.Fatalf("CTE shadow result = %#v", cte)+ }+}++func TestUnknownTableSuggestionsDeduplicateAliasTargets(t *testing.T) {+ prepared := catalog.Prepare(&catalog.Catalog{+ Tables: map[string]catalog.Table{+ "postgres.demo.orders": {Fields: map[string]catalog.Field{}},+ },+ TableAliases: map[string]string{+ "demo_postgres_orders": "postgres.demo.orders",+ "legacy_postgres_orders": "postgres.demo.orders",+ },+ Properties: map[string][]catalog.Property{},+ })+ result := Validate(prepared, "SELECT * FROM demo_postgres_order")+ if result.Valid || len(result.Diagnostics) != 1 || len(result.Diagnostics[0].Suggestions) != 1 || result.Diagnostics[0].Suggestions[0].Label != "demo_postgres_orders" {+ t.Fatalf("result = %#v", result)+ }+}+func TestValidateDuplicateTableNames(t *testing.T) {for _, test := range []struct {name, query, qualifier string