Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(hogql): avoid rebuilding catalog indexes per request (#101328)

Paweł Szczurdcce76b75258
diff --git a/services/hogql-language-service/benchmarks_test.go b/services/hogql-language-service/benchmarks_test.go
index 9151d795f2e0..5b49f6085e39 100644
--- a/services/hogql-language-service/benchmarks_test.go
+++ b/services/hogql-language-service/benchmarks_test.go
@@ -146,7 +146,7 @@ type completionCase struct {
}
func BenchmarkCompleteLargeCatalog(b *testing.B) {
- schema := largeSyntheticCatalog()
+ schema := catalog.Prepare(largeSyntheticCatalog())
sessionQuery, sessionPosition := queryAndPosition(sessionActorQuery)
traceQuery, tracePosition := queryAndPosition(traceTreeQuery)
eventQuery, eventPosition := queryAndPosition(eventJourneyQuery)
@@ -168,7 +168,7 @@ func BenchmarkCompleteLargeCatalog(b *testing.B) {
}
func BenchmarkValidateLargeCatalog(b *testing.B) {
- schema := largeSyntheticCatalog()
+ schema := catalog.Prepare(largeSyntheticCatalog())
sessionQuery, _ := queryAndPosition(sessionActorQuery)
eventQuery, _ := queryAndPosition(eventJourneyQuery)
traceQuery, _ := queryAndPosition(traceTreeQuery)
@@ -197,37 +197,67 @@ func BenchmarkCatalogPublication(b *testing.B) {
b.Fatal(err)
}
authorization := serviceauth.Authorization{TeamID: 1, UserID: 1}
+ prepared := catalog.Prepare(schema)
+ b.Run("decode", func(b *testing.B) {
+ b.ReportAllocs()
+ b.SetBytes(int64(len(payload)))
+ b.ResetTimer()
+ reportCatalogMetrics(b, schema, len(payload))
+ for range b.N {
+ var decoded catalogUpdate
+ if err := json.Unmarshal(payload, &decoded); err != nil {
+ b.Fatal(err)
+ }
+ }
+ })
+
+ b.Run("prepare", func(b *testing.B) {
+ var result *catalog.PreparedCatalog
+ b.ReportAllocs()
+ b.ResetTimer()
+ reportCatalogMetrics(b, schema, len(payload))
+ b.ReportMetric(float64(prepared.EstimatedBytes()), "prepared-B")
+ for range b.N {
+ result = catalog.Prepare(schema)
+ }
+ if result == nil {
+ b.Fatal("catalog preparation returned nil")
+ }
+ })
+
b.Run("cache replacement", func(b *testing.B) {
registry := catalog.NewRegistry(2, 1<<30, time.Hour)
b.ReportAllocs()
b.ResetTimer()
reportCatalogMetrics(b, schema, len(payload))
+ b.ReportMetric(float64(prepared.EstimatedBytes()), "prepared-B")
for range b.N {
- if err := registry.Put(authorization, update.Revision, schema); err != nil {
+ if err := registry.Put(authorization, update.Revision, prepared); err != nil {
b.Fatal(err)
}
}
})
- b.Run("decode and replace", func(b *testing.B) {
+ b.Run("decode prepare and replace", func(b *testing.B) {
registry := catalog.NewRegistry(2, 1<<30, time.Hour)
b.ReportAllocs()
b.SetBytes(int64(len(payload)))
b.ResetTimer()
reportCatalogMetrics(b, schema, len(payload))
+ b.ReportMetric(float64(prepared.EstimatedBytes()), "prepared-B")
for range b.N {
var decoded catalogUpdate
if err := json.Unmarshal(payload, &decoded); err != nil {
b.Fatal(err)
}
- if err := registry.Put(authorization, decoded.Revision, &decoded.Catalog); err != nil {
+ if err := registry.Put(authorization, decoded.Revision, catalog.Prepare(&decoded.Catalog)); err != nil {
b.Fatal(err)
}
}
})
}
-func benchmarkCompletion(b *testing.B, schema *catalog.Catalog, query string, position int) {
+func benchmarkCompletion(b *testing.B, schema *catalog.PreparedCatalog, query string, position int) {
result, err := completion.Complete(schema, query, position, completion.PositionEncodingUTF8, "")
if err != nil {
b.Fatal(err)
@@ -251,7 +281,7 @@ func benchmarkCompletion(b *testing.B, schema *catalog.Catalog, query string, po
}
}
-func benchmarkValidation(b *testing.B, schema *catalog.Catalog, query string) {
+func benchmarkValidation(b *testing.B, schema *catalog.PreparedCatalog, query string) {
result := validation.Validate(schema, query)
payload, err := json.Marshal(result)
if err != nil {
diff --git a/services/hogql-language-service/cmd/server/main.go b/services/hogql-language-service/cmd/server/main.go
index fb338cc9350e..5d74209dbb7f 100644
--- a/services/hogql-language-service/cmd/server/main.go
+++ b/services/hogql-language-service/cmd/server/main.go
@@ -284,7 +284,17 @@ func (s *server) putCatalog(w http.ResponseWriter, r *http.Request, authorizatio
if !decodeJSON(w, r, 64<<20, &input) {
return
}
- if err := s.catalogs.Put(authorization, input.Revision, &input.Catalog); err != nil {
+ if err := catalog.ValidateRevision(input.Revision); err != nil {
+ setRequestResult(r, "catalog_rejected")
+ http.Error(w, err.Error(), http.StatusBadRequest)
+ return
+ }
+ if err := catalog.ValidateCatalog(&input.Catalog); err != nil {
+ setRequestResult(r, "catalog_rejected")
+ http.Error(w, err.Error(), http.StatusBadRequest)
+ return
+ }
+ if err := s.catalogs.Put(authorization, input.Revision, catalog.Prepare(&input.Catalog)); err != nil {
setRequestResult(r, "catalog_rejected")
http.Error(w, err.Error(), http.StatusBadRequest)
return
diff --git a/services/hogql-language-service/cmd/server/main_test.go b/services/hogql-language-service/cmd/server/main_test.go
index 0bb5b40613ac..342aa0dbc303 100644
--- a/services/hogql-language-service/cmd/server/main_test.go
+++ b/services/hogql-language-service/cmd/server/main_test.go
@@ -196,7 +196,7 @@ func TestPrincipalRateLimitRunsBeforeBodyDecodeAndDoesNotCrossScopes(t *testing.
}
value := &catalog.Catalog{Tables: map[string]catalog.Table{}, Properties: map[string][]catalog.Property{}}
for _, authorization := range []serviceauth.Authorization{{TeamID: 1, UserID: 10}, {TeamID: 1, UserID: 20}} {
- if err := s.catalogs.Put(authorization, "1", value); err != nil {
+ if err := s.catalogs.Put(authorization, "1", catalog.Prepare(value)); err != nil {
t.Fatal(err)
}
}
diff --git a/services/hogql-language-service/internal/catalog/catalog.go b/services/hogql-language-service/internal/catalog/catalog.go
index e68cc0ab25d2..c9bca7d0329d 100644
--- a/services/hogql-language-service/internal/catalog/catalog.go
+++ b/services/hogql-language-service/internal/catalog/catalog.go
@@ -1,5 +1,13 @@
package catalog
+import (
+ "slices"
+ "sort"
+ "strings"
+ "unicode"
+ "unicode/utf8"
+)
+
type Field struct {
Name string `json:"name"`
Type string `json:"type"`
@@ -21,3 +29,253 @@ type Catalog struct {
Tables map[string]Table `json:"tables"`
Properties map[string][]Property `json:"properties"`
}
+
+type Entry struct {
+ Name string
+ Type string
+}
+
+type Index struct {
+ entries []Entry
+}
+
+type PreparedTable struct {
+ Name string
+ Type string
+ Fields Index
+}
+
+type PreparedCatalog struct {
+ tables Index
+ tablesByName map[string]int
+ tableValues []PreparedTable
+ properties map[string]*Index
+ valid bool
+ tableCount int
+ propertyCount int
+ estimatedBytes int64
+}
+
+func Prepare(value *Catalog) *PreparedCatalog {
+ if value == nil {
+ return nil
+ }
+ prepared := &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,
+ tableCount: len(value.Tables),
+ }
+ fieldCount := 0
+ for _, table := range value.Tables {
+ fieldCount += len(table.Fields)
+ }
+ fieldEntries := make([]Entry, 0, fieldCount)
+ tableEntries := make([]Entry, 0, len(value.Tables))
+ types := map[string]string{}
+ for name, table := range value.Tables {
+ fieldStart := len(fieldEntries)
+ for fieldName, field := range table.Fields {
+ fieldEntries = append(fieldEntries, newEntry(fieldName, intern(types, field.Type)))
+ }
+ 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.tableValues = append(prepared.tableValues, preparedTable)
+ tableEntries = append(tableEntries, newEntry(name, tableType))
+ }
+ prepared.tables = newIndex(tableEntries)
+ for namespace, properties := range value.Properties {
+ entries := make([]Entry, len(properties))
+ for index, property := range properties {
+ entries[index] = newEntry(property.Name, intern(types, property.ValueType))
+ }
+ index := newIndex(entries)
+ prepared.properties[namespace] = &index
+ prepared.propertyCount += len(entries)
+ }
+ prepared.estimatedBytes = prepared.estimateSize()
+ return prepared
+}
+
+func (c *PreparedCatalog) Table(name string) (*PreparedTable, bool) {
+ index, ok := c.tablesByName[foldName(name)]
+ if !ok {
+ return nil, false
+ }
+ return &c.tableValues[index], true
+}
+
+func (c *PreparedCatalog) Tables() *Index {
+ return &c.tables
+}
+
+func (c *PreparedCatalog) Properties(namespace string) *Index {
+ return c.properties[namespace]
+}
+
+func (c *PreparedCatalog) TableCount() int {
+ return c.tableCount
+}
+
+func (c *PreparedCatalog) PropertyCount() int {
+ return c.propertyCount
+}
+
+func (c *PreparedCatalog) EstimatedBytes() int64 {
+ return c.estimatedBytes
+}
+
+func (i *Index) Exact(name string) (Entry, bool) {
+ if i == nil {
+ return Entry{}, false
+ }
+ position := sort.Search(len(i.entries), func(index int) bool {
+ return compareFold(i.entries[index].Name, name) >= 0
+ })
+ if position == len(i.entries) || compareFold(i.entries[position].Name, name) != 0 {
+ return Entry{}, false
+ }
+ return i.entries[position], true
+}
+
+func (i *Index) Prefix(prefix string) []Entry {
+ if i == nil {
+ return nil
+ }
+ foldedPrefix := foldName(prefix)
+ start := sort.Search(len(i.entries), func(index int) bool {
+ return compareFold(i.entries[index].Name, foldedPrefix) >= 0
+ })
+ end := len(i.entries)
+ if upperBound, ok := prefixUpperBound(foldedPrefix); ok {
+ end = sort.Search(len(i.entries), func(index int) bool {
+ return compareFold(i.entries[index].Name, upperBound) >= 0
+ })
+ }
+ return i.entries[start:end]
+}
+
+func (i *Index) Entries() []Entry {
+ if i == nil {
+ return nil
+ }
+ return i.entries
+}
+
+func newEntry(name, valueType string) Entry {
+ return Entry{Name: name, Type: valueType}
+}
+
+func intern(values map[string]string, value string) string {
+ if existing, ok := values[value]; ok {
+ return existing
+ }
+ values[value] = value
+ return value
+}
+
+func newIndex(entries []Entry) Index {
+ if !slices.IsSortedFunc(entries, compareEntries) {
+ slices.SortFunc(entries, compareEntries)
+ }
+ return Index{entries: entries}
+}
+
+func compareEntries(left, right Entry) int {
+ comparison := compareFold(left.Name, right.Name)
+ if comparison == 0 {
+ return strings.Compare(left.Name, right.Name)
+ }
+ return comparison
+}
+
+func (c *PreparedCatalog) estimateSize() int64 {
+ var size int64
+ for _, entry := range c.tables.entries {
+ size += entrySize(entry) + 64
+ table := &c.tableValues[c.tablesByName[foldName(entry.Name)]]
+ for _, field := range table.Fields.entries {
+ size += entrySize(field)
+ }
+ }
+ for namespace, properties := range c.properties {
+ size += int64(len(namespace) + 64)
+ for _, property := range properties.entries {
+ size += entrySize(property)
+ }
+ }
+ return size
+}
+
+func entrySize(entry Entry) int64 {
+ return int64(len(entry.Name) + len(entry.Type) + 32)
+}
+
+func compareFold(left, right string) int {
+ for len(left) > 0 && len(right) > 0 {
+ leftRune, leftSize := utf8.DecodeRuneInString(left)
+ rightRune, rightSize := utf8.DecodeRuneInString(right)
+ leftRune = foldRune(leftRune)
+ rightRune = foldRune(rightRune)
+ if leftRune < rightRune {
+ return -1
+ }
+ if leftRune > rightRune {
+ return 1
+ }
+ left = left[leftSize:]
+ right = right[rightSize:]
+ }
+ if len(left) > 0 {
+ return 1
+ }
+ if len(right) > 0 {
+ return -1
+ }
+ return 0
+}
+
+func foldName(value string) string {
+ return strings.Map(foldRune, value)
+}
+
+func foldRune(value rune) rune {
+ if value >= 'A' && value <= 'Z' {
+ return value + 'a' - 'A'
+ }
+ if value >= 'a' && value <= 'z' {
+ return value
+ }
+ canonical := value
+ for candidate := unicode.SimpleFold(value); candidate != value; candidate = unicode.SimpleFold(candidate) {
+ if candidate >= 'a' && candidate <= 'z' {
+ return candidate
+ }
+ if candidate < canonical {
+ canonical = candidate
+ }
+ }
+ return canonical
+}
+
+func prefixUpperBound(prefix string) (string, bool) {
+ characters := []rune(prefix)
+ for index := len(characters) - 1; index >= 0; index-- {
+ if characters[index] == utf8.MaxRune {
+ continue
+ }
+ characters[index]++
+ if characters[index] >= 0xD800 && characters[index] <= 0xDFFF {
+ characters[index] = 0xE000
+ }
+ return string(characters[:index+1]), true
+ }
+ return "", false
+}
diff --git a/services/hogql-language-service/internal/catalog/catalog_test.go b/services/hogql-language-service/internal/catalog/catalog_test.go
new file mode 100644
index 000000000000..c1bf714c30b6
--- /dev/null
+++ b/services/hogql-language-service/internal/catalog/catalog_test.go
@@ -0,0 +1,38 @@
+package catalog
+
+import "testing"
+
+func TestIndexExactUsesUnicodeCaseFolding(t *testing.T) {
+ index := newIndex([]Entry{newEntry("t", "String"), newEntry("ſ", "String")})
+
+ entry, ok := index.Exact("s")
+ if !ok || entry.Name != "ſ" {
+ t.Fatalf("Exact(\"s\") = %#v, %t", entry, ok)
+ }
+}
+
+func TestPreparedCatalogUsesUnicodeCaseFoldingForTableAndPrefixLookups(t *testing.T) {
+ prepared := Prepare(&Catalog{
+ Tables: map[string]Table{
+ "ς": {
+ Fields: map[string]Field{
+ "ςuffix": {Name: "ςuffix", Type: "String"},
+ },
+ },
+ },
+ Properties: map[string][]Property{},
+ })
+
+ table, ok := prepared.Table("Σ")
+ if !ok {
+ t.Fatal("Table(\"Σ\") did not find ς")
+ }
+ entry, ok := table.Fields.Exact("Σuffix")
+ if !ok || entry.Name != "ςuffix" {
+ t.Fatalf("Exact(\"Σuffix\") = %#v, %t", entry, ok)
+ }
+ prefix := table.Fields.Prefix("Σ")
+ if len(prefix) != 1 || prefix[0].Name != "ςuffix" {
+ t.Fatalf("Prefix(\"Σ\") = %#v", prefix)
+ }
+}
diff --git a/services/hogql-language-service/internal/catalog/registry.go b/services/hogql-language-service/internal/catalog/registry.go
index 3672ae8aa47e..fe3e455919df 100644
--- a/services/hogql-language-service/internal/catalog/registry.go
+++ b/services/hogql-language-service/internal/catalog/registry.go
@@ -11,6 +11,7 @@ import (
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")
ErrCatalogTooLarge = errors.New("catalog exceeds cache capacity")
)
@@ -25,7 +26,7 @@ type Registry struct {
}
type registryEntry struct {
- catalog *Catalog
+ catalog *PreparedCatalog
revision string
createdAt time.Time
lastAccess time.Time
@@ -46,17 +47,31 @@ func newRegistry(maxEntries int, maxBytes int64, ttl time.Duration, now func() t
return &Registry{entries: map[serviceauth.Authorization]registryEntry{}, maxEntries: maxEntries, maxBytes: maxBytes, ttl: ttl, now: now}
}
-func (r *Registry) Put(authorization serviceauth.Authorization, revision string, value *Catalog) error {
- if !authorization.Valid() {
- return ErrInvalidScope
- }
+func ValidateRevision(revision string) error {
if revision == "" || len(revision) > 128 {
return ErrInvalidRevision
}
+ return nil
+}
+
+func ValidateCatalog(value *Catalog) error {
if value == nil || value.Tables == nil || value.Properties == nil {
- return errors.New("catalog must contain tables and properties")
+ return ErrInvalidCatalog
}
- sizeBytes := estimatedSize(value)
+ return nil
+}
+
+func (r *Registry) Put(authorization serviceauth.Authorization, revision string, value *PreparedCatalog) error {
+ if !authorization.Valid() {
+ return ErrInvalidScope
+ }
+ if err := ValidateRevision(revision); err != nil {
+ return err
+ }
+ if value == nil || !value.valid {
+ return ErrInvalidCatalog
+ }
+ sizeBytes := value.EstimatedBytes()
if sizeBytes > r.maxBytes {
return ErrCatalogTooLarge
}
@@ -77,7 +92,7 @@ func (r *Registry) Put(authorization serviceauth.Authorization, revision string,
return nil
}
-func (r *Registry) Get(authorization serviceauth.Authorization) (*Catalog, string, bool) {
+func (r *Registry) Get(authorization serviceauth.Authorization) (*PreparedCatalog, string, bool) {
r.mu.Lock()
defer r.mu.Unlock()
now := r.now()
@@ -108,10 +123,8 @@ func (r *Registry) Stats() RegistryStats {
r.removeExpired(r.now())
stats := RegistryStats{Catalogs: len(r.entries)}
for _, entry := range r.entries {
- stats.Tables += len(entry.catalog.Tables)
- for _, properties := range entry.catalog.Properties {
- stats.Properties += len(properties)
- }
+ stats.Tables += entry.catalog.TableCount()
+ stats.Properties += entry.catalog.PropertyCount()
}
return stats
}
@@ -139,20 +152,3 @@ func (r *Registry) removeLeastRecentlyUsed() {
r.totalBytes -= r.entries[oldestAuthorization].sizeBytes
delete(r.entries, oldestAuthorization)
}
-
-func estimatedSize(value *Catalog) int64 {
- var size int64
- for name, table := range value.Tables {
- size += int64(len(name) + len(table.Name) + len(table.Type) + 64)
- for fieldName, field := range table.Fields {
- size += int64(len(fieldName) + len(field.Name) + len(field.Type) + 64)
- }
- }
- for namespace, properties := range value.Properties {
- size += int64(len(namespace) + 64)
- for _, property := range properties {
- size += int64(len(property.Name) + len(property.ValueType) + 32)
- }
- }
- return size
-}
diff --git a/services/hogql-language-service/internal/catalog/registry_test.go b/services/hogql-language-service/internal/catalog/registry_test.go
index 46e8acbe18b0..4e102b9bd97a 100644
--- a/services/hogql-language-service/internal/catalog/registry_test.go
+++ b/services/hogql-language-service/internal/catalog/registry_test.go
@@ -1,17 +1,34 @@
package catalog
import (
+ "errors"
"testing"
"time"
"github.com/PostHog/posthog/services/hogql-language-service/internal/serviceauth"
)
+func TestRegistryRejectsCaseInsensitiveDuplicateTables(t *testing.T) {
+ registry := NewRegistry(1, 1<<20, time.Hour)
+ value := Prepare(&Catalog{
+ Tables: map[string]Table{
+ "Events": {Name: "Events"},
+ "events": {Name: "events"},
+ },
+ 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)
+ }
+}
+
func TestRegistryIsolatesCatalogsAndReplacesRevisionAtomically(t *testing.T) {
now := time.Unix(100, 0)
registry := newRegistry(2, 1<<20, time.Hour, func() time.Time { return now })
- first := &Catalog{Tables: map[string]Table{"events": {Name: "events"}}, Properties: map[string][]Property{}}
- second := &Catalog{Tables: map[string]Table{"persons": {Name: "persons"}}, Properties: map[string][]Property{}}
+ first := Prepare(&Catalog{Tables: map[string]Table{"events": {Name: "events"}}, Properties: map[string][]Property{}})
+ second := Prepare(&Catalog{Tables: map[string]Table{"persons": {Name: "persons"}}, Properties: map[string][]Property{}})
if err := registry.Put(serviceauth.Authorization{TeamID: 1, UserID: 10}, "1", first); err != nil {
t.Fatal(err)
}
@@ -19,17 +36,19 @@ func TestRegistryIsolatesCatalogsAndReplacesRevisionAtomically(t *testing.T) {
t.Fatal(err)
}
loaded, revision, ok := registry.Get(serviceauth.Authorization{TeamID: 1, UserID: 10})
- if !ok || revision != "1" || loaded.Tables["events"].Name != "events" {
+ events, eventsExist := loaded.Table("events")
+ if !ok || revision != "1" || !eventsExist || events.Name != "events" {
t.Fatalf("unexpected first catalog: %#v, %q, %t", loaded, revision, ok)
}
- if _, exists := loaded.Tables["persons"]; exists {
+ if _, exists := loaded.Table("persons"); exists {
t.Fatal("one team and user scope received another scope's table")
}
if err := registry.Put(serviceauth.Authorization{TeamID: 1, UserID: 10}, "2", second); err != nil {
t.Fatal(err)
}
loaded, revision, ok = registry.Get(serviceauth.Authorization{TeamID: 1, UserID: 10})
- if !ok || revision != "2" || loaded.Tables["persons"].Name != "persons" {
+ persons, personsExist := loaded.Table("persons")
+ if !ok || revision != "2" || !personsExist || persons.Name != "persons" {
t.Fatalf("replacement was not visible: %#v, %q, %t", loaded, revision, ok)
}
}
@@ -37,7 +56,7 @@ func TestRegistryIsolatesCatalogsAndReplacesRevisionAtomically(t *testing.T) {
func TestRegistryExpiresAndEvictsLeastRecentlyUsedCatalogs(t *testing.T) {
now := time.Unix(100, 0)
registry := newRegistry(2, 1<<20, time.Minute, func() time.Time { return now })
- value := &Catalog{Tables: map[string]Table{}, Properties: map[string][]Property{}}
+ value := Prepare(&Catalog{Tables: map[string]Table{}, Properties: map[string][]Property{}})
for _, scope := range []serviceauth.Authorization{{TeamID: 1, UserID: 10}, {TeamID: 2, UserID: 20}} {
if err := registry.Put(scope, "1", value); err != nil {
t.Fatal(err)
@@ -64,7 +83,7 @@ func TestRegistryExpiresActiveCatalogFromPublicationTime(t *testing.T) {
now := time.Unix(100, 0)
registry := newRegistry(1, 1<<20, time.Minute, func() time.Time { return now })
scope := serviceauth.Authorization{TeamID: 1, UserID: 10}
- value := &Catalog{Tables: map[string]Table{}, Properties: map[string][]Property{}}
+ value := Prepare(&Catalog{Tables: map[string]Table{}, Properties: map[string][]Property{}})
if err := registry.Put(scope, "1", value); err != nil {
t.Fatal(err)
}
@@ -81,14 +100,15 @@ func TestRegistryExpiresActiveCatalogFromPublicationTime(t *testing.T) {
func TestRegistryEvictsCatalogsToStayWithinMemoryBudget(t *testing.T) {
now := time.Unix(100, 0)
value := &Catalog{Tables: map[string]Table{"events": {Name: "events", Fields: map[string]Field{"long_field_name": {Name: "long_field_name", Type: "String"}}}}, Properties: map[string][]Property{}}
- size := estimatedSize(value)
+ prepared := Prepare(value)
+ size := prepared.EstimatedBytes()
registry := newRegistry(10, size, time.Hour, func() time.Time { return now })
first := serviceauth.Authorization{TeamID: 1, UserID: 10}
second := serviceauth.Authorization{TeamID: 2, UserID: 20}
- if err := registry.Put(first, "1", value); err != nil {
+ if err := registry.Put(first, "1", prepared); err != nil {
t.Fatal(err)
}
- if err := registry.Put(second, "1", value); err != nil {
+ if err := registry.Put(second, "1", prepared); err != nil {
t.Fatal(err)
}
if _, _, ok := registry.Get(first); ok {
diff --git a/services/hogql-language-service/internal/completion/completion.go b/services/hogql-language-service/internal/completion/completion.go
index 7a9c5475a91c..bfe708806d39 100644
--- a/services/hogql-language-service/internal/completion/completion.go
+++ b/services/hogql-language-service/internal/completion/completion.go
@@ -47,7 +47,7 @@ var comparisonOperators = []string{"=", "!=", "<", "<=", ">", ">=", "LIKE", "ILI
var commonFunctions = []string{"avg", "coalesce", "count", "countDistinct", "countIf", "if", "max", "min", "now", "sum", "sumIf", "toDate", "toDateTime", "uniq", "uniqExact"}
var tableReference = regexp.MustCompile(`(?i)\b(?:FROM|JOIN)\s+([A-Za-z_][A-Za-z0-9_.$]*)(?:\s+(?:AS\s+)?([A-Za-z_][A-Za-z0-9_]*))?`)
-func Complete(schema *catalog.Catalog, query string, position int, positionEncoding PositionEncoding, cursor string) (Result, error) {
+func Complete(schema *catalog.PreparedCatalog, query string, position int, positionEncoding PositionEncoding, cursor string) (Result, error) {
if err := querylimits.Validate(query); err != nil {
return Result{}, err
}
@@ -76,34 +76,27 @@ func Complete(schema *catalog.Catalog, query string, position int, positionEncod
}
repaired := query[:start] + "__posthog_cursor__" + query[position:]
bindings, parseErr := tableBindings(repaired)
- tablesByLowerName := tableNamesByLowerName(schema)
for binding, tableName := range bindings {
- if canonicalName, ok := tablesByLowerName[strings.ToLower(tableName)]; ok {
- bindings[binding] = canonicalName
+ if table, ok := schema.Table(tableName); ok {
+ bindings[binding] = table.Name
}
}
- for binding, tableName := range fallbackBindings(repaired, tablesByLowerName) {
+ for binding, tableName := range fallbackBindings(repaired, schema) {
bindings[binding] = tableName
}
var suggestions []Suggestion
if namespace, propertyPrefix, ok := propertyContext(query[:position], bindings); ok {
- lowerPropertyPrefix := strings.ToLower(propertyPrefix)
- for _, property := range schema.Properties[namespace] {
- if hasLowerPrefix(property.Name, lowerPropertyPrefix) {
- suggestions = append(suggestions, Suggestion{Label: property.Name, Kind: "property", Detail: property.ValueType})
- }
- }
+ return indexedResult(schema.Properties(namespace).Prefix(propertyPrefix), "property", offset, parseErr), nil
} else if qualifier != "" {
if tableName, ok := bindings[strings.ToLower(qualifier)]; ok {
- suggestions = appendFields(suggestions, schema.Tables[tableName], lowerPrefix)
- }
- } else if mode == completionModeTable {
- for name, table := range schema.Tables {
- if hasLowerPrefix(name, lowerPrefix) {
- suggestions = append(suggestions, Suggestion{Label: name, Kind: "table", Detail: table.Type})
+ if table, exists := schema.Table(tableName); exists {
+ return indexedResult(table.Fields.Prefix(lowerPrefix), "field", offset, parseErr), nil
}
}
+ return indexedResult(nil, "field", offset, parseErr), nil
+ } else if mode == completionModeTable {
+ return indexedResult(schema.Tables().Prefix(lowerPrefix), "table", offset, parseErr), nil
} else if mode == completionModeComparison {
suggestions = appendNamed(suggestions, comparisonOperators, lowerPrefix, "operator", "")
} else if mode == completionModeBetweenSeparator {
@@ -120,7 +113,9 @@ func Complete(schema *catalog.Catalog, query string, position int, positionEncod
continue
}
seen[tableName] = true
- suggestions = appendFields(suggestions, schema.Tables[tableName], lowerPrefix)
+ if table, ok := schema.Table(tableName); ok {
+ suggestions = appendFields(suggestions, table, lowerPrefix)
+ }
}
if mode == completionModeExpression {
suggestions = appendFunctions(suggestions, lowerPrefix)
@@ -157,6 +152,28 @@ func Complete(schema *catalog.Catalog, query string, position int, positionEncod
return result, nil
}
+func indexedResult(entries []catalog.Entry, kind string, offset int, parseErr error) Result {
+ result := Result{Total: len(entries)}
+ if offset > len(entries) {
+ offset = len(entries)
+ }
+ end := min(offset+PageSize, len(entries))
+ result.Suggestions = make([]Suggestion, end-offset)
+ rank := strconv.Itoa(suggestionRank(kind)) + "-"
+ for index, entry := range entries[offset:end] {
+ result.Suggestions[index] = Suggestion{
+ Label: entry.Name, Kind: kind, Detail: entry.Type, SortText: rank + strings.ToLower(entry.Name),
+ }
+ }
+ if end < len(entries) {
+ result.NextCursor = encodeCursor(end)
+ }
+ if parseErr != nil {
+ result.ParseError = parseErr.Error()
+ }
+ return result
+}
+
func utf16OffsetToByteOffset(value string, offset int) int {
if offset < 0 {
return len(value)
@@ -216,34 +233,24 @@ func encodeCursor(offset int) string {
// The ClickHouse grammar accepts database.table while HogQL warehouse names may have more segments.
// Keep parser-derived bindings as the primary path and fill that syntax gap until the grammar supports it.
-func fallbackBindings(query string, tablesByLowerName map[string]string) map[string]string {
+func fallbackBindings(query string, schema *catalog.PreparedCatalog) map[string]string {
bindings := map[string]string{}
for _, match := range tableReference.FindAllStringSubmatch(query, -1) {
- tableName, ok := tablesByLowerName[strings.ToLower(match[1])]
+ table, ok := schema.Table(match[1])
if !ok {
continue
}
- bindings[strings.ToLower(tableName)] = tableName
+ bindings[strings.ToLower(table.Name)] = table.Name
if match[2] != "" && !strings.EqualFold(match[2], "FINAL") {
- bindings[strings.ToLower(match[2])] = tableName
+ bindings[strings.ToLower(match[2])] = table.Name
}
}
return bindings
}
-func tableNamesByLowerName(schema *catalog.Catalog) map[string]string {
- tables := make(map[string]string, len(schema.Tables))
- for name := range schema.Tables {
- tables[strings.ToLower(name)] = name
- }
- return tables
-}
-
-func appendFields(out []Suggestion, table catalog.Table, lowerPrefix string) []Suggestion {
- for name, field := range table.Fields {
- if hasLowerPrefix(name, lowerPrefix) {
- out = append(out, Suggestion{Label: name, Kind: "field", Detail: field.Type})
- }
+func appendFields(out []Suggestion, table *catalog.PreparedTable, lowerPrefix string) []Suggestion {
+ for _, field := range table.Fields.Prefix(lowerPrefix) {
+ out = append(out, Suggestion{Label: field.Name, Kind: "field", Detail: field.Type})
}
return out
}
diff --git a/services/hogql-language-service/internal/completion/completion_test.go b/services/hogql-language-service/internal/completion/completion_test.go
index ac9f0a91e6a3..d4c84038bc79 100644
--- a/services/hogql-language-service/internal/completion/completion_test.go
+++ b/services/hogql-language-service/internal/completion/completion_test.go
@@ -12,8 +12,8 @@ import (
"github.com/PostHog/posthog/services/hogql-language-service/internal/catalog"
)
-func testCatalog() *catalog.Catalog {
- return &catalog.Catalog{Tables: map[string]catalog.Table{
+func testCatalog() *catalog.PreparedCatalog {
+ return catalog.Prepare(&catalog.Catalog{Tables: map[string]catalog.Table{
"orders": {Name: "orders", Type: "data_warehouse", Fields: map[string]catalog.Field{
"order_id": {Name: "order_id", Type: "string"},
"amount": {Name: "amount", Type: "float"},
@@ -23,11 +23,11 @@ func testCatalog() *catalog.Catalog {
"synced_id": {Name: "synced_id", Type: "string"},
}},
}, Properties: map[string][]catalog.Property{
- "event": {{Name: "$geo_city", ValueType: "String"}, {Name: "$geo_country", ValueType: "String"}},
+ "event": {{Name: "$geo_city", ValueType: "String"}, {Name: "$geo_country", ValueType: "String"}, {Name: "$Geo_Region", ValueType: "String"}},
"person": {{Name: "$geo_city", ValueType: "String"}},
"session": {{Name: "$entry_current_url", ValueType: "String"}},
"group:0": {{Name: "industry", ValueType: "String"}},
- }}
+ }})
}
func TestCompletionRejectsQueriesOutsideResourceLimits(t *testing.T) {
@@ -67,6 +67,7 @@ func TestCompletesPropertiesForGenericNamespaces(t *testing.T) {
{query: "SELECT properties.$geo FROM persons", position: len("SELECT properties.$geo"), expect: "$geo_city"},
{query: "SELECT session.properties.$entry FROM events", position: len("SELECT session.properties.$entry"), expect: "$entry_current_url"},
{query: "SELECT group_0.properties.ind FROM events", position: len("SELECT group_0.properties.ind"), expect: "industry"},
+ {query: "SELECT properties.$geo_r FROM events", position: len("SELECT properties.$geo_r"), expect: "$Geo_Region"},
}
for _, test := range tests {
result, err := Complete(testCatalog(), test.query, test.position, PositionEncodingUTF8, "")
@@ -198,8 +199,9 @@ func TestCompletionPagesWithoutSkippingOrRepeatingTables(t *testing.T) {
name := fmt.Sprintf("table_%02d", index)
schema.Tables[name] = catalog.Table{Name: name, Type: "data_warehouse", Fields: map[string]catalog.Field{}}
}
+ prepared := catalog.Prepare(schema)
query := "SELECT * FROM table_"
- first, err := Complete(schema, query, len(query), PositionEncodingUTF8, "")
+ first, err := Complete(prepared, query, len(query), PositionEncodingUTF8, "")
if err != nil {
t.Fatal(err)
}
@@ -209,7 +211,7 @@ func TestCompletionPagesWithoutSkippingOrRepeatingTables(t *testing.T) {
if first.Total != 30 {
t.Fatalf("total = %d", first.Total)
}
- second, err := Complete(schema, query, len(query), PositionEncodingUTF8, first.NextCursor)
+ second, err := Complete(prepared, query, len(query), PositionEncodingUTF8, first.NextCursor)
if err != nil {
t.Fatal(err)
}
@@ -219,7 +221,7 @@ func TestCompletionPagesWithoutSkippingOrRepeatingTables(t *testing.T) {
if first.Suggestions[24].Label != "table_24" || second.Suggestions[0].Label != "table_25" {
t.Fatalf("page boundary is %q then %q", first.Suggestions[24].Label, second.Suggestions[0].Label)
}
- if _, err := Complete(schema, query, len(query), PositionEncodingUTF8, "not-a-cursor"); err == nil {
+ if _, err := Complete(prepared, query, len(query), PositionEncodingUTF8, "not-a-cursor"); err == nil {
t.Fatal("invalid cursor was accepted")
}
}
@@ -242,7 +244,7 @@ func findSuggestion(suggestions []Suggestion, label string) (Suggestion, bool) {
return Suggestion{}, false
}
-func largeContextualCatalog() *catalog.Catalog {
+func largeContextualCatalog() *catalog.PreparedCatalog {
schema := &catalog.Catalog{Tables: make(map[string]catalog.Table, 1024)}
for tableIndex := 0; tableIndex < 1024; tableIndex++ {
fields := make(map[string]catalog.Field, 25)
@@ -253,7 +255,7 @@ func largeContextualCatalog() *catalog.Catalog {
name := fmt.Sprintf("table_%04d", tableIndex)
schema.Tables[name] = catalog.Table{Name: name, Type: "data_warehouse", Fields: fields}
}
- return schema
+ return catalog.Prepare(schema)
}
func TestCompleteContextualCatalogStaysWithinLatencyBudget(t *testing.T) {
diff --git a/services/hogql-language-service/internal/validation/validation.go b/services/hogql-language-service/internal/validation/validation.go
index 85585b31fce3..1f80bed62f76 100644
--- a/services/hogql-language-service/internal/validation/validation.go
+++ b/services/hogql-language-service/internal/validation/validation.go
@@ -6,6 +6,7 @@ import (
"sort"
"strings"
"time"
+ "unicode/utf8"
clickhouse "github.com/orian/clickhouse-sql-parser/parser"
@@ -36,7 +37,7 @@ type Result struct {
type tableBinding struct {
name string
- table catalog.Table
+ table *catalog.PreparedTable
}
type queryScope struct {
@@ -47,7 +48,7 @@ type queryScope struct {
var tableReferencePattern = regexp.MustCompile(`(?i)\b(?:FROM|JOIN)\s+([A-Za-z_][A-Za-z0-9_.$]*)`)
-func Validate(schema *catalog.Catalog, query string) Result {
+func Validate(schema *catalog.PreparedCatalog, query string) Result {
started := time.Now()
if err := querylimits.Validate(query); err != nil {
return result([]Diagnostic{{Code: "query_limit", Message: err.Error(), Start: 0, End: len(query)}}, nil, started)
@@ -60,11 +61,6 @@ func Validate(schema *catalog.Catalog, query string) Result {
}}, nil, started)
}
- tablesByName := make(map[string]catalog.Table, len(schema.Tables))
- for name, table := range schema.Tables {
- tablesByName[strings.ToLower(name)] = table
- }
-
var diagnostics []Diagnostic
var referencedTableNames []string
seenTableNames := map[string]bool{}
@@ -86,12 +82,12 @@ func Validate(schema *catalog.Catalog, query string) Result {
referencedTableNames = append(referencedTableNames, name)
seenTableNames[lowerName] = true
}
- table, exists := tablesByName[strings.ToLower(name)]
+ table, exists := schema.Table(name)
if !exists {
if len(diagnostics) < querylimits.MaxDiagnostics {
diagnostics = append(diagnostics, Diagnostic{
Code: "unknown_table", Message: fmt.Sprintf("Unknown table %q", name), Start: start, End: end,
- Suggestions: closest(name, tableNames(schema), 5),
+ Suggestions: closest(name, schema.Tables().Entries(), 5),
})
}
return true
@@ -146,7 +142,7 @@ func Validate(schema *catalog.Catalog, query string) Result {
bindingNames[name] = binding.name
}
if namespace, ok := propertyresolver.Resolve(parts, bindingNames); ok {
- validateProperty(&diagnostics, seen, schema.Properties[namespace], typed.Fields[len(typed.Fields)-1])
+ validateProperty(&diagnostics, seen, schema.Properties(namespace), typed.Fields[len(typed.Fields)-1])
return true
}
if binding, ok := bindings[strings.ToLower(typed.Fields[0].Name)]; ok {
@@ -218,27 +214,21 @@ func visibleBindings(scope *queryScope) map[string]tableBinding {
return bindings
}
-func validateProperty(diagnostics *[]Diagnostic, seen map[string]bool, properties []catalog.Property, ident *clickhouse.Ident) {
+func validateProperty(diagnostics *[]Diagnostic, seen map[string]bool, properties *catalog.Index, ident *clickhouse.Ident) {
if len(*diagnostics) >= querylimits.MaxDiagnostics {
return
}
- for _, property := range properties {
- if strings.EqualFold(property.Name, ident.Name) {
- return
- }
+ if _, ok := properties.Exact(ident.Name); ok {
+ return
}
key := fmt.Sprintf("%d:%d", ident.Pos(), ident.End())
if seen[key] {
return
}
seen[key] = true
- names := make([]string, len(properties))
- for index, property := range properties {
- names[index] = property.Name
- }
*diagnostics = append(*diagnostics, Diagnostic{
Code: "unknown_property", Message: fmt.Sprintf("Unknown property %q", ident.Name), Start: int(ident.Pos()), End: int(ident.End()),
- Suggestions: closest(ident.Name, names, 5),
+ Suggestions: closest(ident.Name, properties.Entries(), 5),
})
}
@@ -281,7 +271,7 @@ func tableReference(expr *clickhouse.TableExpr) (name, alias string, start, end
return name, alias, int(identifier.Pos()), int(identifier.End()), true
}
-func validateField(diagnostics *[]Diagnostic, seen map[string]bool, table catalog.Table, ident *clickhouse.Ident) {
+func validateField(diagnostics *[]Diagnostic, seen map[string]bool, table *catalog.PreparedTable, ident *clickhouse.Ident) {
if len(*diagnostics) >= querylimits.MaxDiagnostics {
return
}
@@ -295,7 +285,7 @@ func validateField(diagnostics *[]Diagnostic, seen map[string]bool, table catalo
seen[key] = true
*diagnostics = append(*diagnostics, Diagnostic{
Code: "unknown_field", Message: fmt.Sprintf("Unknown field %q", ident.Name), Start: int(ident.Pos()), End: int(ident.End()),
- Suggestions: closest(ident.Name, fieldNames(table), 5),
+ Suggestions: closest(ident.Name, table.Fields.Entries(), 5),
})
}
@@ -303,16 +293,16 @@ func validateUnqualifiedField(diagnostics *[]Diagnostic, seen map[string]bool, b
if len(*diagnostics) >= querylimits.MaxDiagnostics {
return
}
- uniqueTables := map[string]catalog.Table{}
+ uniqueTables := map[string]*catalog.PreparedTable{}
for _, binding := range bindings {
uniqueTables[binding.name] = binding.table
if hasField(binding.table, ident.Name) {
return
}
}
- candidates := make([]string, 0)
+ candidates := make([]catalog.Entry, 0)
for _, table := range uniqueTables {
- candidates = append(candidates, fieldNames(table)...)
+ candidates = append(candidates, table.Fields.Entries()...)
}
key := fmt.Sprintf("%d:%d", ident.Pos(), ident.End())
if seen[key] {
@@ -325,93 +315,168 @@ func validateUnqualifiedField(diagnostics *[]Diagnostic, seen map[string]bool, b
})
}
-func hasField(table catalog.Table, name string) bool {
- for fieldName := range table.Fields {
- if strings.EqualFold(fieldName, name) {
- return true
- }
- }
- return false
-}
-
-func tableNames(schema *catalog.Catalog) []string {
- names := make([]string, 0, len(schema.Tables))
- for name := range schema.Tables {
- names = append(names, name)
- }
- return names
+func hasField(table *catalog.PreparedTable, name string) bool {
+ _, ok := table.Fields.Exact(name)
+ return ok
}
-func fieldNames(table catalog.Table) []string {
- names := make([]string, 0, len(table.Fields))
- for name := range table.Fields {
- names = append(names, name)
- }
- return names
-}
-
-func closest(input string, candidates []string, limit int) []Suggestion {
+func closest(input string, candidates []catalog.Entry, limit int) []Suggestion {
if len(input) > querylimits.MaxSuggestionInputBytes {
return nil
}
lowerInput := strings.ToLower(input)
- leftRunes := []rune(lowerInput)
- threshold := min(4, max(2, len(leftRunes)/3))
- unique := map[string]Suggestion{}
+ leftLength := utf8.RuneCountInString(lowerInput)
+ threshold := min(4, max(2, leftLength/3))
+ best := make([]Suggestion, 0, limit)
+ workspace := levenshteinWorkspace{}
for _, candidate := range candidates {
- if len(candidate) > querylimits.MaxSuggestionInputBytes {
+ if len(candidate.Name) > querylimits.MaxSuggestionInputBytes {
continue
}
- lowerCandidate := strings.ToLower(candidate)
- rightRunes := []rune(lowerCandidate)
- lengthDifference := max(len(leftRunes), len(rightRunes)) - min(len(leftRunes), len(rightRunes))
+ lowerCandidate := strings.ToLower(candidate.Name)
+ rightLength := utf8.RuneCountInString(lowerCandidate)
+ lengthDifference := max(leftLength, rightLength) - min(leftLength, rightLength)
prefix := strings.HasPrefix(lowerCandidate, lowerInput)
if lengthDifference > threshold && !prefix {
continue
}
distance := lengthDifference
if !prefix {
- distance = levenshtein(leftRunes, rightRunes)
+ distance = workspace.distance(lowerInput, lowerCandidate, threshold)
}
if distance > threshold {
continue
}
- key := lowerCandidate
- if existing, ok := unique[key]; !ok || distance < existing.Distance {
- unique[key] = Suggestion{Label: candidate, Distance: distance}
+ suggestion := Suggestion{Label: candidate.Name, Distance: distance}
+ duplicate := false
+ for _, existing := range best {
+ if strings.EqualFold(existing.Label, suggestion.Label) {
+ duplicate = true
+ break
+ }
+ }
+ if duplicate {
+ continue
+ }
+ if len(best) < limit {
+ best = append(best, suggestion)
+ sortSuggestions(best)
+ } else if suggestionLess(suggestion, best[len(best)-1]) {
+ best[len(best)-1] = suggestion
+ sortSuggestions(best)
}
}
- result := make([]Suggestion, 0, len(unique))
- for _, suggestion := range unique {
- result = append(result, suggestion)
+ return best
+}
+
+func sortSuggestions(suggestions []Suggestion) {
+ sort.Slice(suggestions, func(left, right int) bool {
+ return suggestionLess(suggestions[left], suggestions[right])
+ })
+}
+
+func suggestionLess(left, right Suggestion) bool {
+ if left.Distance != right.Distance {
+ return left.Distance < right.Distance
}
- sort.Slice(result, func(i, j int) bool {
- if result[i].Distance != result[j].Distance {
- return result[i].Distance < result[j].Distance
+ return left.Label < right.Label
+}
+
+type levenshteinWorkspace struct {
+ previous []int
+ current []int
+}
+
+func (w *levenshteinWorkspace) distance(left, right string, limit int) int {
+ if isASCII(left) && isASCII(right) {
+ for len(left) > 0 && len(right) > 0 && left[0] == right[0] {
+ left = left[1:]
+ right = right[1:]
}
- return result[i].Label < result[j].Label
- })
- return result[:min(limit, len(result))]
+ for len(left) > 0 && len(right) > 0 && left[len(left)-1] == right[len(right)-1] {
+ left = left[:len(left)-1]
+ right = right[:len(right)-1]
+ }
+ return w.distanceASCII(left, right, limit)
+ }
+ leftRunes := []rune(left)
+ rightRunes := []rune(right)
+ for len(leftRunes) > 0 && len(rightRunes) > 0 && leftRunes[0] == rightRunes[0] {
+ leftRunes = leftRunes[1:]
+ rightRunes = rightRunes[1:]
+ }
+ for len(leftRunes) > 0 && len(rightRunes) > 0 && leftRunes[len(leftRunes)-1] == rightRunes[len(rightRunes)-1] {
+ leftRunes = leftRunes[:len(leftRunes)-1]
+ rightRunes = rightRunes[:len(rightRunes)-1]
+ }
+ return w.distanceRunes(leftRunes, rightRunes, limit)
}
-func levenshtein(leftRunes, rightRunes []rune) int {
- previous := make([]int, len(rightRunes)+1)
- current := make([]int, len(rightRunes)+1)
- for index := range previous {
- previous[index] = index
+func (w *levenshteinWorkspace) distanceASCII(left, right string, limit int) int {
+ w.resize(len(right) + 1)
+ for index := range len(right) + 1 {
+ w.previous[index] = index
+ }
+ for leftIndex := range len(left) {
+ w.current[0] = leftIndex + 1
+ rowMinimum := w.current[0]
+ for rightIndex := range len(right) {
+ cost := 1
+ if left[leftIndex] == right[rightIndex] {
+ cost = 0
+ }
+ w.current[rightIndex+1] = min(w.current[rightIndex]+1, w.previous[rightIndex+1]+1, w.previous[rightIndex]+cost)
+ rowMinimum = min(rowMinimum, w.current[rightIndex+1])
+ }
+ if rowMinimum > limit {
+ return limit + 1
+ }
+ w.previous, w.current = w.current, w.previous
}
- for leftIndex, leftRune := range leftRunes {
- current[0] = leftIndex + 1
- for rightIndex, rightRune := range rightRunes {
+ return w.previous[len(right)]
+}
+
+func (w *levenshteinWorkspace) distanceRunes(left, right []rune, limit int) int {
+ w.resize(len(right) + 1)
+ for index := range len(right) + 1 {
+ w.previous[index] = index
+ }
+ for leftIndex, leftRune := range left {
+ w.current[0] = leftIndex + 1
+ rowMinimum := w.current[0]
+ for rightIndex, rightRune := range right {
cost := 1
if leftRune == rightRune {
cost = 0
}
- current[rightIndex+1] = min(current[rightIndex]+1, previous[rightIndex+1]+1, previous[rightIndex]+cost)
+ w.current[rightIndex+1] = min(w.current[rightIndex]+1, w.previous[rightIndex+1]+1, w.previous[rightIndex]+cost)
+ rowMinimum = min(rowMinimum, w.current[rightIndex+1])
+ }
+ if rowMinimum > limit {
+ return limit + 1
+ }
+ w.previous, w.current = w.current, w.previous
+ }
+ return w.previous[len(right)]
+}
+
+func (w *levenshteinWorkspace) resize(size int) {
+ if cap(w.previous) < size {
+ w.previous = make([]int, size)
+ w.current = make([]int, size)
+ return
+ }
+ w.previous = w.previous[:size]
+ w.current = w.current[:size]
+}
+
+func isASCII(value string) bool {
+ for index := range len(value) {
+ if value[index] >= utf8.RuneSelf {
+ return false
}
- previous, current = current, previous
}
- return previous[len(rightRunes)]
+ return true
}
func result(diagnostics []Diagnostic, tableNames []string, started time.Time) Result {
diff --git a/services/hogql-language-service/internal/validation/validation_test.go b/services/hogql-language-service/internal/validation/validation_test.go
index 3fd66dfdfddd..fc4287a06b95 100644
--- a/services/hogql-language-service/internal/validation/validation_test.go
+++ b/services/hogql-language-service/internal/validation/validation_test.go
@@ -7,8 +7,8 @@ import (
"github.com/PostHog/posthog/services/hogql-language-service/internal/catalog"
)
-func schema() *catalog.Catalog {
- return &catalog.Catalog{Tables: map[string]catalog.Table{
+func schema() *catalog.PreparedCatalog {
+ return catalog.Prepare(&catalog.Catalog{Tables: map[string]catalog.Table{
"warehouse_orders": {Name: "warehouse_orders", Type: "data_warehouse", Fields: map[string]catalog.Field{
"order_id": {Name: "order_id", Type: "string"},
"amount": {Name: "amount", Type: "float"},
@@ -27,11 +27,11 @@ func schema() *catalog.Catalog {
}},
"persons": {Name: "persons", Type: "posthog", Fields: map[string]catalog.Field{"properties": {Name: "properties", Type: "json"}}},
}, Properties: map[string][]catalog.Property{
- "event": {{Name: "$geo_city", ValueType: "String"}},
+ "event": {{Name: "$geo_city", ValueType: "String"}, {Name: "café", ValueType: "String"}},
"person": {{Name: "$geo_country", ValueType: "String"}},
"session": {{Name: "$entry_current_url", ValueType: "String"}},
"group:0": {{Name: "industry", ValueType: "String"}},
- }}
+ }})
}
func TestValidateDoesNotShareBindingsAcrossStatements(t *testing.T) {
@@ -110,6 +110,7 @@ func TestValidateAcceptsKnownFieldsAndFunctions(t *testing.T) {
{query: "SELECT sum(o.amount), o.order_id FROM warehouse_orders AS o WHERE o.amount > 0", tableName: "warehouse_orders"},
{query: "SELECT uuid FROM events WHERE event = '$pageview' AND timestamp > now() - interval 1 month", tableName: "events"},
{query: "SELECT extract(month FROM timestamp) FROM events", tableName: "events"},
+ {query: "SELECT properties.$GEO_CITY FROM events", tableName: "events"},
} {
result := Validate(schema(), test.query)
if !result.Valid || len(result.Diagnostics) != 0 {
@@ -137,6 +138,7 @@ func TestValidatePropertiesAcrossGenericNamespaces(t *testing.T) {
{query: "SELECT persons.properties.$geo_contry FROM persons", suggestion: "$geo_country"},
{query: "SELECT session.properties.$entry_curent_url FROM events", suggestion: "$entry_current_url"},
{query: "SELECT group_0.properties.indstry FROM events", suggestion: "industry"},
+ {query: "SELECT properties.cafe FROM events", suggestion: "café"},
}
for _, test := range tests {
result := Validate(schema(), test.query)