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.

feat(hogql): complete dotted table paths (#103213)

Paweł Szczura12b0677ccbf
diff --git a/docs/internal/hogql-language-service.md b/docs/internal/hogql-language-service.md
index 88fadbbe36cb..8ae79686eada 100644
--- a/docs/internal/hogql-language-service.md
+++ b/docs/internal/hogql-language-service.md
@@ -79,6 +79,12 @@ CTE shadowing and table-suggestion deduplication use exact names, so a CTE named
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.
+For an unquoted multi-part prefix, completion returns matching leaf tables with full labels and suffix-only insertion.
+For example, `FROM postgres.` labels the result `postgres.demo.orders` and inserts `demo.orders`; `FROM postgres.demo.or` inserts `orders`.
+Namespace components already present in SQL must match catalog case exactly, so insertion cannot produce an unresolved spelling.
+Completion inside quoted path components and namespace-only suggestions remain follow-up work.
+The service omits dotted candidates when any remaining component would require identifier quotes.
+Monaco replaces the current word only through the cursor, so text after a mid-word cursor remains in the document.
CTE names follow the same scope, definition-order, and shadowing rules as relation lookup; scalar WITH aliases are not tables.
A visible CTE hides a catalog table with the same name, and pagination counts that name once.
CTE insertion quotes the whole name when needed, including names with dots.
diff --git a/services/hogql-language-service/README.md b/services/hogql-language-service/README.md
index 64ddde9cabb5..0cb305389cd0 100644
--- a/services/hogql-language-service/README.md
+++ b/services/hogql-language-service/README.md
@@ -33,6 +33,11 @@ curl -sS -X POST http://localhost:8091/teams/2/users/1/validate \
Completion and validation share scope analysis for table CTEs and aliased `FROM` subqueries.
Completion suggests projected fields, including aliases and wildcard outputs, with catalog types for direct field projections.
FROM and JOIN completion suggests visible CTE names before catalog tables and respects CTE shadowing.
+It reads unquoted multi-part table prefixes from the catalog: `FROM postgres.` shows the full `postgres.demo.orders` label and inserts only `demo.orders`.
+Already-typed namespace components must use the catalog's exact case, while the final partial component remains case-insensitive.
+Completion inside quoted path components remains unsupported.
+Completion omits dotted candidates when a remaining path component would require quotes.
+The editor replaces text from the start of the current word to the cursor and leaves text after the cursor unchanged.
Empty queries offer SELECT and WITH; typed prefixes filter those starting keywords.
Joined fields with the same name show their source and insert a qualified reference, including separate aliases in self-joins.
Unique fields and already-qualified completion keep their existing insertion behavior.
diff --git a/services/hogql-language-service/benchmarks_test.go b/services/hogql-language-service/benchmarks_test.go
index 0c916ddb32f8..95f30936e04b 100644
--- a/services/hogql-language-service/benchmarks_test.go
+++ b/services/hogql-language-service/benchmarks_test.go
@@ -158,6 +158,7 @@ func BenchmarkCompleteLargeCatalog(b *testing.B) {
cases := []completionCase{
{name: "table broad prefix", query: "SELECT * FROM warehouse_table_", position: len("SELECT * FROM warehouse_table_")},
{name: "alias broad prefix", query: "SELECT * FROM legacy_warehouse_table_", position: len("SELECT * FROM legacy_warehouse_table_")},
+ {name: "dotted 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")},
@@ -253,6 +254,7 @@ func TestLargeCatalogSupportedScale(t *testing.T) {
}{
{query: "SELECT * FROM warehouse_table_", total: syntheticTableCount - 3},
{query: "SELECT * FROM legacy_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},
} {
@@ -286,7 +288,7 @@ func TestLargeCatalogSupportedScale(t *testing.T) {
}
for _, query := range []string{
- "SELECT column_24 FROM legacy_warehouse_table_2048",
+ "SELECT column_24 FROM legacy.warehouse.table_2048",
"SELECT properties.$event_property_119999 FROM events",
} {
if result := validation.Validate(prepared, query); !result.Valid {
@@ -420,7 +422,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)
+ tableAliases := make(map[string]string, 2*(syntheticTableCount-3))
for tableIndex := 0; tableIndex < syntheticTableCount-3; tableIndex++ {
fields := make(map[string]catalog.Field, syntheticFieldsPerTable)
for fieldIndex := 0; fieldIndex < syntheticFieldsPerTable; fieldIndex++ {
@@ -430,6 +432,7 @@ 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
+ tableAliases[fmt.Sprintf("legacy.warehouse.table_%04d", tableIndex)] = name
}
tables["events"] = catalog.Table{Name: "events", Type: "posthog", Fields: scaleFields(
"distinct_id", "event", "person_id", "properties", "session_id", "timestamp", "uuid",
diff --git a/services/hogql-language-service/internal/catalog/catalog.go b/services/hogql-language-service/internal/catalog/catalog.go
index 1b33d3e89fbd..0f78cd390bac 100644
--- a/services/hogql-language-service/internal/catalog/catalog.go
+++ b/services/hogql-language-service/internal/catalog/catalog.go
@@ -134,14 +134,25 @@ func (c *PreparedCatalog) TableSpellings() *Index {
}
func (c *PreparedCatalog) TableSuggestions(prefix string, excluded map[string]bool) []Entry {
+ return c.tableSuggestions(prefix, excluded, nil)
+}
+
+func (c *PreparedCatalog) TableSuggestionsMatching(prefix string, excluded map[string]bool, matches func(Entry) bool) []Entry {
+ return c.tableSuggestions(prefix, excluded, matches)
+}
+
+func (c *PreparedCatalog) tableSuggestions(prefix string, excluded map[string]bool, matches func(Entry) bool) []Entry {
+ accepted := func(entry Entry) bool {
+ return !excluded[entry.Name] && (matches == nil || matches(entry))
+ }
if !c.hasAliases {
candidates := c.tables.Prefix(prefix)
- if len(excluded) == 0 {
+ if len(excluded) == 0 && matches == nil {
return candidates
}
result := make([]Entry, 0, len(candidates))
for _, candidate := range candidates {
- if !excluded[candidate.Name] {
+ if accepted(candidate) {
result = append(result, candidate)
}
}
@@ -150,7 +161,7 @@ func (c *PreparedCatalog) TableSuggestions(prefix string, excluded map[string]bo
candidates := c.tableSpellings.Prefix(prefix)
canonicalMatches := make(map[int]bool, len(candidates))
for _, candidate := range candidates {
- if excluded[candidate.Name] {
+ if !accepted(candidate) {
continue
}
index := c.tablesByName[candidate.Name]
@@ -161,7 +172,7 @@ func (c *PreparedCatalog) TableSuggestions(prefix string, excluded map[string]bo
seen := make(map[int]bool, len(candidates))
result := make([]Entry, 0, len(candidates))
for _, candidate := range candidates {
- if excluded[candidate.Name] {
+ if !accepted(candidate) {
continue
}
index := c.tablesByName[candidate.Name]
diff --git a/services/hogql-language-service/internal/completion/completion.go b/services/hogql-language-service/internal/completion/completion.go
index 6c308ccef667..2907b50420d7 100644
--- a/services/hogql-language-service/internal/completion/completion.go
+++ b/services/hogql-language-service/internal/completion/completion.go
@@ -71,6 +71,13 @@ var quotedHogQLKeywords = map[string]struct{}{
"UNBOUNDED": {}, "UNION": {}, "UNPIVOT": {}, "USING": {}, "VALUES": {}, "WEEK": {}, "WHEN": {},
"WHERE": {}, "WHILE": {}, "WINDOW": {}, "WITH": {}, "WITHIN": {}, "YEAR": {}, "YYYY": {}, "ZONE": {},
}
+var quotedHogQLKeywordsFolded = func() map[string]struct{} {
+ result := make(map[string]struct{}, len(quotedHogQLKeywords))
+ for keyword := range quotedHogQLKeywords {
+ result[strings.ToLower(keyword)] = struct{}{}
+ }
+ return result
+}()
var hogQLIdentifierEscaper = strings.NewReplacer(
"\\", "\\\\",
"`", "``",
@@ -97,11 +104,19 @@ func Complete(schema *catalog.PreparedCatalog, query string, position int, posit
return Result{}, err
}
prefix, qualifier, start := cursorWord(query[:position])
+ mode := analyzeCursorContext(query[:start])
+ tableNamespace := ""
+ if path, ok := dottedTablePathAtCursor(query[:position]); ok {
+ prefix = path.prefix
+ qualifier = ""
+ start = path.start
+ tableNamespace = path.namespace
+ mode = completionModeTable
+ }
if len(prefix) > querylimits.MaxSuggestionInputBytes {
return Result{Suggestions: []Suggestion{}}, nil
}
lowerPrefix := strings.ToLower(prefix)
- mode := analyzeCursorContext(query[:start])
if mode == completionModeNone {
return Result{Suggestions: []Suggestion{}}, nil
}
@@ -119,10 +134,17 @@ func Complete(schema *catalog.PreparedCatalog, query string, position int, posit
document, bindings, qualified, parseErr := cursorBindings(schema, repaired, start, qualifier)
var suggestions []Suggestion
- namespace, propertyPrefix, propertyOK := propertyContext(query[:position], bindings)
if document != nil && document.LimitError() != nil {
return Result{}, document.LimitError()
}
+ if mode == completionModeTable {
+ result := tableResult(schema, bindings, lowerPrefix, tableNamespace, offset, parseErr)
+ if document != nil && document.LimitError() != nil {
+ return Result{}, document.LimitError()
+ }
+ return result, nil
+ }
+ namespace, propertyPrefix, propertyOK := propertyContext(query[:position], bindings)
if propertyOK {
return indexedResult(slices.Values(schema.Properties(namespace).Prefix(propertyPrefix)), "property", offset, parseErr), nil
} else if qualifier != "" {
@@ -131,12 +153,6 @@ func Complete(schema *catalog.PreparedCatalog, query string, position int, posit
return Result{}, document.LimitError()
}
return indexedResult(entries, "field", offset, parseErr), nil
- } else if mode == completionModeTable {
- result := tableResult(schema, bindings, lowerPrefix, offset, parseErr)
- if document != nil && document.LimitError() != nil {
- return Result{}, document.LimitError()
- }
- return result, nil
} else if mode == completionModeComparison {
suggestions = appendNamed(suggestions, comparisonOperators, lowerPrefix, "operator", "")
} else if mode == completionModeBetweenSeparator {
@@ -287,11 +303,7 @@ func suggestionInsertText(kind, name string) string {
case "field", "property":
insertText = quoteHogQLFieldIdentifier(name)
case "table":
- parts := strings.Split(name, ".")
- for index := range parts {
- parts[index] = quoteHogQLFieldIdentifier(parts[index])
- }
- insertText = strings.Join(parts, ".")
+ insertText = quoteHogQLTablePath(name)
}
if insertText == name {
return ""
@@ -299,6 +311,14 @@ func suggestionInsertText(kind, name string) string {
return insertText
}
+func quoteHogQLTablePath(name string) string {
+ parts := strings.Split(name, ".")
+ for index := range parts {
+ parts[index] = quoteHogQLFieldIdentifier(parts[index])
+ }
+ return strings.Join(parts, ".")
+}
+
func supportedHogQLIdentifier(name string) bool {
return !strings.Contains(name, "%")
}
@@ -377,6 +397,43 @@ func cursorWord(input string) (prefix, qualifier string, start int) {
return prefix, qualifier, start
}
+type dottedTablePath struct {
+ prefix string
+ namespace string
+ start int
+}
+
+func dottedTablePathAtCursor(input string) (dottedTablePath, bool) {
+ start := len(input)
+ for start > 0 {
+ character, size := utf8.DecodeLastRuneInString(input[:start])
+ if character != '.' && !isIdentifier(character) {
+ break
+ }
+ start -= size
+ }
+ prefix := input[start:]
+ lastDot := strings.LastIndexByte(prefix, '.')
+ if lastDot < 1 || !directTablePathContext(input[:start]) {
+ return dottedTablePath{}, false
+ }
+ for _, component := range strings.Split(prefix[:lastDot], ".") {
+ if component == "" {
+ return dottedTablePath{}, false
+ }
+ }
+ return dottedTablePath{prefix: prefix, namespace: prefix[:lastDot+1], start: start}, true
+}
+
+func directTablePathContext(input string) bool {
+ tokens, depth, incomplete := scanSQLTokens(input)
+ if incomplete {
+ return false
+ }
+ last := lastTokenAtDepth(tokens, depth)
+ return last.kind == sqlTokenWord && (last.text == "FROM" || last.text == "JOIN")
+}
+
func isIdentifier(r rune) bool {
return unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' || r == '$'
}
diff --git a/services/hogql-language-service/internal/completion/completion_test.go b/services/hogql-language-service/internal/completion/completion_test.go
index 908b85ea8287..559268e4dfa5 100644
--- a/services/hogql-language-service/internal/completion/completion_test.go
+++ b/services/hogql-language-service/internal/completion/completion_test.go
@@ -244,6 +244,98 @@ func TestCompletesTablesAfterFrom(t *testing.T) {
}
}
+func TestCompletesDottedTablePaths(t *testing.T) {
+ prepared := catalog.Prepare(&catalog.Catalog{
+ Tables: map[string]catalog.Table{
+ "postgres.demo.orders": {Type: "data_warehouse", Fields: map[string]catalog.Field{}},
+ "postgres.demo.order items": {Type: "data_warehouse", Fields: map[string]catalog.Field{}},
+ "events.properties.archive": {Type: "data_warehouse", Fields: map[string]catalog.Field{}},
+ "persons.properties.archive": {Type: "data_warehouse", Fields: map[string]catalog.Field{}},
+ },
+ TableAliases: map[string]string{"POSTGRES.demo.orders": "postgres.demo.orders"},
+ Properties: map[string][]catalog.Property{
+ "event": {{Name: "$browser", ValueType: "String"}},
+ "person": {{Name: "email", ValueType: "String"}},
+ },
+ })
+ for _, test := range []struct {
+ name string
+ source string
+ encoding PositionEncoding
+ expected *Suggestion
+ }{
+ {name: "namespace", source: "SELECT * FROM postgres.|", expected: &Suggestion{Label: "postgres.demo.orders", Detail: "data_warehouse", InsertText: "demo.orders"}},
+ {name: "leaf", source: "SELECT * FROM postgres.demo.or|", expected: &Suggestion{Label: "postgres.demo.orders", Detail: "data_warehouse", InsertText: "orders"}},
+ {name: "join", source: "SELECT * FROM events JOIN postgres.demo.or| ON 1 = 1", expected: &Suggestion{Label: "postgres.demo.orders", Detail: "data_warehouse", InsertText: "orders"}},
+ {name: "alias exact namespace case", source: "SELECT * FROM POSTGRES.demo.or|", expected: &Suggestion{Label: "POSTGRES.demo.orders", Detail: "postgres.demo.orders", InsertText: "orders"}},
+ {name: "leaf prefix case is replaced", source: "SELECT * FROM postgres.demo.OR|", expected: &Suggestion{Label: "postgres.demo.orders", Detail: "data_warehouse", InsertText: "orders"}},
+ {name: "wrong namespace case", source: "SELECT * FROM postgres.DEMO.or|"},
+ {name: "comma source remains unsupported", source: "SELECT * FROM events, postgres.demo.or|"},
+ {name: "event property spelling remains table context", source: "SELECT * FROM events.properties.|", expected: &Suggestion{Label: "events.properties.archive", Detail: "data_warehouse", InsertText: "archive"}},
+ {name: "person property spelling remains table context", source: "SELECT * FROM persons.properties.|", expected: &Suggestion{Label: "persons.properties.archive", Detail: "data_warehouse", InsertText: "archive"}},
+ {name: "unicode utf16", source: "SELECT '😀'; SELECT * FROM postgres.demo.or|", encoding: PositionEncodingUTF16, expected: &Suggestion{Label: "postgres.demo.orders", Detail: "data_warehouse", InsertText: "orders"}},
+ {name: "midword server cursor", source: "SELECT * FROM postgres.demo.or|suffix", expected: &Suggestion{Label: "postgres.demo.orders", Detail: "data_warehouse", InsertText: "orders"}},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ bytePosition := strings.IndexByte(test.source, '|')
+ query := strings.Replace(test.source, "|", "", 1)
+ position := bytePosition
+ if test.encoding == "" {
+ test.encoding = PositionEncodingUTF8
+ }
+ if test.encoding == PositionEncodingUTF16 {
+ position = len(utf16.Encode([]rune(query[:bytePosition])))
+ }
+ result, err := Complete(prepared, query, position, test.encoding, "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if test.expected == nil {
+ if len(result.Suggestions) != 0 {
+ t.Fatalf("result = %#v", result)
+ }
+ return
+ }
+ if len(result.Suggestions) != 1 {
+ t.Fatalf("result = %#v", result)
+ }
+ actual := result.Suggestions[0]
+ if actual.Label != test.expected.Label || actual.Detail != test.expected.Detail || actual.InsertText != test.expected.InsertText {
+ t.Fatalf("suggestion = %#v, want %#v", actual, *test.expected)
+ }
+ })
+ }
+
+ quotedCanonical := catalog.Prepare(&catalog.Catalog{
+ Tables: map[string]catalog.Table{
+ "postgres.demo.order items": {Type: "data_warehouse", Fields: map[string]catalog.Field{}},
+ },
+ TableAliases: map[string]string{"postgres.demo.order_items": "postgres.demo.order items"},
+ Properties: map[string][]catalog.Property{},
+ })
+ query := "SELECT * FROM postgres.demo.order"
+ result, err := Complete(quotedCanonical, query, len(query), PositionEncodingUTF8, "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(result.Suggestions) != 1 || result.Suggestions[0].Label != "postgres.demo.order_items" || result.Suggestions[0].InsertText != "order_items" {
+ t.Fatalf("quoted canonical alias result = %#v", result)
+ }
+
+ cteCatalog := catalog.Prepare(&catalog.Catalog{Tables: map[string]catalog.Table{
+ "postgres.demo.orders": {Type: "data_warehouse", Fields: map[string]catalog.Field{}},
+ "postgres.demo.catalog_table": {Type: "data_warehouse", Fields: map[string]catalog.Field{}},
+ }})
+ cteQuery := "WITH `postgres.demo.cte` AS (SELECT 1), `postgres.demo.orders` AS (SELECT 2) SELECT * FROM postgres.demo."
+ cteResult, err := Complete(cteCatalog, cteQuery, len(cteQuery), PositionEncodingUTF8, "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(cteResult.Suggestions) != 1 || cteResult.Suggestions[0].Label != "postgres.demo.catalog_table" || cteResult.Suggestions[0].InsertText != "catalog_table" {
+ t.Fatalf("dotted CTE result = %#v", cteResult)
+ }
+}
+
func TestCompletesOneSpellingPerAliasedTableAndHonorsExactCTEShadowing(t *testing.T) {
prepared := catalog.Prepare(&catalog.Catalog{
Tables: map[string]catalog.Table{
@@ -1054,6 +1146,9 @@ func TestCompletionReturnsNoSuggestionsInsideStringOrComment(t *testing.T) {
for _, query := range []string{
"-- sel",
"/* wi",
+ "-- FROM postgres.demo.or",
+ "/* FROM postgres.demo.or",
+ "SELECT 'FROM postgres.demo.or",
"SELECT * FROM orders WHERE order_id = 'cou",
"SELECT * FROM orders -- cou",
"SELECT * FROM orders /* cou",
@@ -1118,12 +1213,12 @@ 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)
+ alias := fmt.Sprintf("legacy.demo.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_"
+ query := "SELECT * FROM legacy.demo.table_"
first, err := Complete(prepared, query, len(query), PositionEncodingUTF8, "")
if err != nil {
t.Fatal(err)
@@ -1137,9 +1232,10 @@ func TestAliasCompletionPagesWithoutRepeatingCanonicalTargets(t *testing.T) {
t.Fatalf("pages = %#v, %#v", first, second)
}
for index, suggestion := range all {
- expectedAlias := fmt.Sprintf("demo_postgres_table_%02d", index)
+ expectedAlias := fmt.Sprintf("legacy.demo.table_%02d", index)
expectedCanonical := fmt.Sprintf("postgres.demo.table_%02d", index)
- if suggestion.Label != expectedAlias || suggestion.Detail != expectedCanonical {
+ expectedInsertText := fmt.Sprintf("table_%02d", index)
+ if suggestion.Label != expectedAlias || suggestion.Detail != expectedCanonical || suggestion.InsertText != expectedInsertText {
t.Fatalf("suggestion %d = %#v", index, suggestion)
}
}
diff --git a/services/hogql-language-service/internal/completion/tables.go b/services/hogql-language-service/internal/completion/tables.go
index 5df4c9984ff8..c20b39ca6130 100644
--- a/services/hogql-language-service/internal/completion/tables.go
+++ b/services/hogql-language-service/internal/completion/tables.go
@@ -1,6 +1,7 @@
package completion
import (
+ "iter"
"slices"
"strings"
@@ -8,10 +9,12 @@ import (
"github.com/PostHog/posthog/services/hogql-language-service/internal/catalog"
)
-func tableResult(schema *catalog.PreparedCatalog, bindings analysis.Bindings, prefix string, offset int, parseErr error) Result {
+func tableResult(schema *catalog.PreparedCatalog, bindings analysis.Bindings, prefix, namespace string, offset int, parseErr error) Result {
ctes := slices.Collect(bindings.CTENames(prefix))
if len(ctes) == 0 {
- return indexedResult(slices.Values(schema.TableSuggestions(prefix, nil)), "table", offset, parseErr)
+ result := indexedResult(tableEntries(schema, prefix, namespace, nil), "table", offset, parseErr)
+ setTablePathInsertText(&result, namespace)
+ return result
}
slices.SortFunc(ctes, func(left, right catalog.Entry) int {
if comparison := strings.Compare(strings.ToLower(left.Name), strings.ToLower(right.Name)); comparison != 0 {
@@ -26,18 +29,24 @@ func tableResult(schema *catalog.PreparedCatalog, bindings analysis.Bindings, pr
shadowed[cte.Name] = true
}
entries := func(yield func(catalog.Entry) bool) {
- for _, cte := range ctes {
- if !yield(cte) {
- return
+ if namespace == "" {
+ for _, cte := range ctes {
+ if !yield(cte) {
+ return
+ }
}
}
- for _, table := range schema.TableSuggestions(prefix, shadowed) {
+ for table := range tableEntries(schema, prefix, namespace, shadowed) {
if !yield(table) {
return
}
}
}
result := indexedResult(entries, "table", offset, parseErr)
+ setTablePathInsertText(&result, namespace)
+ if namespace != "" {
+ return result
+ }
for index := range result.Suggestions {
suggestion := &result.Suggestions[index]
if cteNames[suggestion.Label] {
@@ -48,3 +57,51 @@ func tableResult(schema *catalog.PreparedCatalog, bindings analysis.Bindings, pr
}
return result
}
+
+func tableEntries(schema *catalog.PreparedCatalog, prefix, namespace string, excluded map[string]bool) iter.Seq[catalog.Entry] {
+ var entries []catalog.Entry
+ if namespace != "" {
+ entries = schema.TableSuggestionsMatching(prefix, excluded, func(entry catalog.Entry) bool {
+ return strings.HasPrefix(entry.Name, namespace) && supportedUnquotedTablePath(strings.TrimPrefix(entry.Name, namespace))
+ })
+ } else {
+ entries = schema.TableSuggestions(prefix, excluded)
+ }
+ return func(yield func(catalog.Entry) bool) {
+ for _, entry := range entries {
+ if !yield(entry) {
+ return
+ }
+ }
+ }
+}
+
+func supportedUnquotedTablePath(path string) bool {
+ for component := range strings.SplitSeq(path, ".") {
+ if !simpleHogQLIdentifier.MatchString(component) || isQuotedHogQLKeyword(component) {
+ return false
+ }
+ }
+ return true
+}
+
+func isQuotedHogQLKeyword(name string) bool {
+ folded := name
+ for index := 0; index < len(name); index++ {
+ if name[index] >= 'A' && name[index] <= 'Z' {
+ folded = strings.ToLower(name)
+ break
+ }
+ }
+ _, exists := quotedHogQLKeywordsFolded[folded]
+ return exists
+}
+
+func setTablePathInsertText(result *Result, namespace string) {
+ if namespace == "" {
+ return
+ }
+ for index := range result.Suggestions {
+ result.Suggestions[index].InsertText = quoteHogQLTablePath(strings.TrimPrefix(result.Suggestions[index].Label, namespace))
+ }
+}