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): resolve select aliases in shared query analysis (#101724)

Paweł Szczur4f691fcd6042
diff --git a/docs/internal/hogql-language-service.md b/docs/internal/hogql-language-service.md
index 6ae16c1d4b3b..2cad45c8ac19 100644
--- a/docs/internal/hogql-language-service.md
+++ b/docs/internal/hogql-language-service.md
@@ -46,9 +46,18 @@ Qualified CTE completion also works before `FROM`, for example `WITH t AS (SELEC
Inner bindings take precedence, and sibling queries and statements do not contribute suggestions.
Validation checks aliased subquery output fields and continues to report only underlying catalog tables in `tableNames`.
+Select aliases follow the resolution order in `posthog/hogql/resolver.py` (`visit_select_query` and `visit_alias`).
+An explicit alias becomes visible after its defining SELECT item, so later items can reference it.
+WHERE, PREWHERE, GROUP BY, HAVING, ORDER BY, named WINDOW definitions, and LIMIT expressions can reference all SELECT aliases in their query.
+FROM and JOIN expressions cannot reference them, and aliases do not cross nested queries, CTE definitions, UNION branches, or statements.
+Alias lookup is case-sensitive, as in the Python resolver; completion prefix matching remains case-insensitive.
+An alias takes precedence over an unqualified field with the same name, while qualified field lookup still uses the relation.
+Direct alias chains retain catalog types, and validation typo suggestions include visible aliases.
+
Physical field completion borrows the catalog prefix index.
Derived projections have a shared limit of 16,384 fields before deduplication.
Field resolution also has a request-wide budget of 1,048,576 work units, counting relation visits and identifier bytes used for lookups and derived-field indexes.
+Select-alias indexing, lookup, and suggestion scans share that work budget.
Aliases of the same relation share a cached field index and one candidate entry for unqualified type resolution.
Completion returns HTTP 400 when either limit is exceeded; validation returns a `query_limit` diagnostic.
Derived qualified suggestions are sorted and deduplicated before pagination.
@@ -58,7 +67,11 @@ Derived qualified suggestions are sorted and deduplicated before pagination.
- Cursor replacement must produce parseable SQL to resolve CTE and subquery fields. Recovery for missing parentheses or incomplete predicates in multi-scope queries remains follow-up work.
- For an incomplete single `SELECT` without `WITH`, completion can recover a parseable `FROM` clause before an unfinished predicate. The response retains `parseError`. Recovery never overlays parsed bindings or scans aliases from sibling scopes.
- Property provenance through derived projections is not available. Completion suppresses property suggestions for derived owners, including CTEs that shadow built-in names such as `events`. Unqualified physical properties remain available when joined derived relations do not project `properties`; a derived `properties` field makes the namespace ambiguous. Add provenance before enabling those ambiguous suggestions.
-- Select-alias visibility within the same query remains a separate layer. A projected alias is available to consumers of a CTE or subquery, not automatically to its defining query.
+- Select-alias recovery requires parseable cursor-replaced SQL. Single-SELECT recovery retains only FROM bindings and does not guess discarded aliases. Preserve SELECT items in a structured recovery pass before enabling those suggestions.
+- Property provenance through select aliases is not available. A visible alias that shadows a property owner suppresses its property suggestions and property-name validation. Track the alias expression's owner before enabling property traversal; qualified physical properties remain available.
+- Scalar WITH aliases, aliases inside expressions, ARRAY JOIN aliases, QUALIFY, and duplicate-alias diagnostics remain follow-up work. Model their resolver order and parser support before extending the top-level SELECT alias index. For duplicate declarations, the index retains the first declaration; it does not establish that the query is valid.
+- Validation skips field checks when a query has no known FROM bindings, including SELECT without FROM. Completion can still suggest its aliases. Add explicit empty-source scopes and distinguish unknown relations before enabling strict validation there.
+- Joined relations can still produce equal field labels with no source in the suggestion detail. Add relation provenance and qualification-aware insertion text before resolving that ambiguity. References to the same relation already share one suggestion set.
- Table-name suggestions still use the catalog; adding visible CTE names to `FROM` and `JOIN` suggestions remains follow-up work.
- Unaliased `FROM` subquery outputs, completion inside quoted identifiers, expression type inference, and complete set-operation semantics remain follow-up work.
- Recursive CTEs, lateral subqueries, and full HogQL compiler parity are outside this layer. The service does not execute queries or fetch metadata during analysis.
diff --git a/services/hogql-language-service/README.md b/services/hogql-language-service/README.md
index b2db30afdd92..7189640de252 100644
--- a/services/hogql-language-service/README.md
+++ b/services/hogql-language-service/README.md
@@ -69,7 +69,9 @@ The parser currently accepts ClickHouse's `database.table` identifiers but not H
Shared analysis normalizes those table references before parsing while preserving byte offsets.
For incomplete SQL, completion can recover a single query's `FROM` clause and keeps the parser error in `parseError`.
It does not recover bindings from malformed CTEs or nested queries.
-Derived-property provenance, select-alias visibility, and other exclusions are tracked in [query analysis and remaining work](../../docs/internal/hogql-language-service.md#recovery-and-remaining-work).
+Completion and validation recognize explicit SELECT aliases in later SELECT items and clauses resolved after SELECT, including WHERE, GROUP BY, HAVING, and ORDER BY.
+Aliases stay within their defining query and do not appear in JOIN conditions.
+Derived-property provenance, additional alias forms, parser recovery, and other exclusions are tracked in [query analysis and remaining work](../../docs/internal/hogql-language-service.md#recovery-and-remaining-work).
## Multitenant catalogs
diff --git a/services/hogql-language-service/internal/analysis/aliases.go b/services/hogql-language-service/internal/analysis/aliases.go
new file mode 100644
index 000000000000..8806531c34f2
--- /dev/null
+++ b/services/hogql-language-service/internal/analysis/aliases.go
@@ -0,0 +1,93 @@
+package analysis
+
+import (
+ "iter"
+ "strings"
+
+ clickhouse "github.com/orian/clickhouse-sql-parser/parser"
+
+ "github.com/PostHog/posthog/services/hogql-language-service/internal/catalog"
+)
+
+type selectAlias struct {
+ field catalog.Entry
+ end int
+}
+
+func (s *queryScope) selectAliases() map[string]selectAlias {
+ if s.aliases != nil {
+ return s.aliases
+ }
+ s.aliases = map[string]selectAlias{}
+ for _, item := range s.query.SelectItems {
+ if !s.budget.lookup(1) {
+ break
+ }
+ if item.Alias == nil {
+ continue
+ }
+ name := item.Alias.Name
+ if !s.budget.lookup(len(name) + 1) {
+ break
+ }
+ if _, exists := s.aliases[name]; exists {
+ continue
+ }
+ // HogQL resolves each expression before registering its alias (Resolver.visit_alias).
+ field := catalog.Entry{Name: name, Type: projectedType(s, item.Expr)}
+ s.aliases[name] = selectAlias{field: field, end: int(item.End())}
+ }
+ return s.aliases
+}
+
+func (b Bindings) aliasCutoff() int {
+ if b.scope == nil {
+ return -1
+ }
+ q := b.scope.query
+ items := q.SelectItems
+ if len(items) > 0 && int(items[0].Pos()) <= b.position && b.position <= int(items[len(items)-1].End()) {
+ return b.position
+ }
+ containsPosition := func(expr clickhouse.Expr) bool {
+ return int(expr.Pos()) <= b.position && b.position <= int(expr.End())
+ }
+ // Resolver.visit_select_query resolves FROM/JOIN before SELECT, then these clauses.
+ if q.Where != nil && containsPosition(q.Where) ||
+ q.Prewhere != nil && containsPosition(q.Prewhere) ||
+ q.GroupBy != nil && containsPosition(q.GroupBy) ||
+ q.Having != nil && containsPosition(q.Having) ||
+ q.OrderBy != nil && containsPosition(q.OrderBy) ||
+ q.Window != nil && containsPosition(q.Window) ||
+ q.LimitBy != nil && containsPosition(q.LimitBy) ||
+ q.Limit != nil && containsPosition(q.Limit) {
+ return int(q.End())
+ }
+ return -1
+}
+
+func (b Bindings) SelectAlias(name string) (catalog.Entry, bool) {
+ cutoff := b.aliasCutoff()
+ if cutoff < 0 || !b.scope.budget.lookup(len(name)+1) {
+ return catalog.Entry{}, false
+ }
+ alias, ok := b.scope.selectAliases()[name]
+ return alias.field, ok && alias.end <= cutoff
+}
+
+func (b Bindings) SelectAliases(prefix string) iter.Seq[catalog.Entry] {
+ return func(yield func(catalog.Entry) bool) {
+ cutoff := b.aliasCutoff()
+ if cutoff < 0 {
+ return
+ }
+ for _, alias := range b.scope.selectAliases() {
+ if !b.scope.budget.lookup(len(alias.field.Name) + 1) {
+ return
+ }
+ if alias.end <= cutoff && strings.HasPrefix(strings.ToLower(alias.field.Name), prefix) && !yield(alias.field) {
+ return
+ }
+ }
+ }
+}
diff --git a/services/hogql-language-service/internal/analysis/document.go b/services/hogql-language-service/internal/analysis/document.go
index bb781987d225..e00dcabbcfd1 100644
--- a/services/hogql-language-service/internal/analysis/document.go
+++ b/services/hogql-language-service/internal/analysis/document.go
@@ -183,6 +183,14 @@ func (b Bindings) UniqueRelations() iter.Seq[Relation] {
}
func (b Bindings) PropertyNamespace(parts []string) (string, bool) {
+ if len(parts) >= 2 {
+ _, bound := b.Relation(parts[0])
+ if _, shadowed := b.SelectAlias(parts[0]); shadowed {
+ if len(parts) == 2 || !bound {
+ return "", false
+ }
+ }
+ }
if len(parts) > 2 {
if _, bound := b.Relation(parts[0]); !bound && resolveCTE(b.scope, parts[0], b.position) != nil {
return "", false
diff --git a/services/hogql-language-service/internal/analysis/scopes.go b/services/hogql-language-service/internal/analysis/scopes.go
index 2de1e6cab09a..42174aeda1ac 100644
--- a/services/hogql-language-service/internal/analysis/scopes.go
+++ b/services/hogql-language-service/internal/analysis/scopes.go
@@ -43,6 +43,7 @@ type queryScope struct {
budget *projectionBudget
ctes []*cteBinding
cteRoot bool
+ aliases map[string]selectAlias
}
var tableReferencePattern = regexp.MustCompile(`(?i)\b(?:FROM|JOIN)\s+([A-Za-z_][A-Za-z0-9_.$]*)`)
@@ -385,6 +386,9 @@ func projectedType(scope *queryScope, expr clickhouse.Expr) string {
bindings := visibleBindings(scope)
switch typed := expr.(type) {
case *clickhouse.Ident:
+ if field, ok := (Bindings{scope: scope, position: int(expr.Pos())}).SelectAlias(typed.Name); ok {
+ return field.Type
+ }
for _, binding := range scope.uniqueBindings() {
if !scope.budget.lookup(len(typed.Name) + 1) {
return ""
diff --git a/services/hogql-language-service/internal/completion/completion.go b/services/hogql-language-service/internal/completion/completion.go
index 4feddfb9159c..41c6d87054a2 100644
--- a/services/hogql-language-service/internal/completion/completion.go
+++ b/services/hogql-language-service/internal/completion/completion.go
@@ -129,13 +129,25 @@ func Complete(schema *catalog.PreparedCatalog, query string, position int, posit
suggestions = appendNamed(suggestions, comparisonOperators, lowerPrefix, "operator", "")
suggestions = appendNamed(suggestions, predicateContinuations, lowerPrefix, "keyword", "")
} else {
+ aliases := map[string]bool{}
+ for alias := range bindings.SelectAliases(lowerPrefix) {
+ aliases[alias.Name] = true
+ suggestions = appendFields(suggestions, slices.Values([]catalog.Entry{alias}))
+ }
seen := map[analysis.Relation]bool{}
for _, relation := range bindings.All() {
if seen[relation] {
continue
}
seen[relation] = true
- suggestions = appendFields(suggestions, relation.Prefix(lowerPrefix))
+ fields := func(yield func(catalog.Entry) bool) {
+ for field := range relation.Prefix(lowerPrefix) {
+ if !aliases[field.Name] && !yield(field) {
+ return
+ }
+ }
+ }
+ suggestions = appendFields(suggestions, fields)
}
if document != nil && document.LimitError() != nil {
return Result{}, document.LimitError()
@@ -155,7 +167,11 @@ func Complete(schema *catalog.PreparedCatalog, query string, position int, posit
if leftRank != rightRank {
return leftRank < rightRank
}
- return strings.ToLower(suggestions[i].Label) < strings.ToLower(suggestions[j].Label)
+ left, right := strings.ToLower(suggestions[i].Label), strings.ToLower(suggestions[j].Label)
+ if left == right {
+ return suggestions[i].Label < suggestions[j].Label
+ }
+ return left < right
})
for index := range suggestions {
suggestions[index].SortText = strconv.Itoa(suggestionRank(suggestions[index].Kind)) + "-" + strings.ToLower(suggestions[index].Label)
diff --git a/services/hogql-language-service/internal/completion/completion_test.go b/services/hogql-language-service/internal/completion/completion_test.go
index 77886370d097..ef73e54948e8 100644
--- a/services/hogql-language-service/internal/completion/completion_test.go
+++ b/services/hogql-language-service/internal/completion/completion_test.go
@@ -153,6 +153,31 @@ func TestCompletesScopedProjections(t *testing.T) {
{"derived body isolation", "SELECT * FROM orders AS x JOIN (SELECT x.| FROM events) AS s ON 1 = 1", nil},
{"joined derived sources", "WITH t AS (SELECT event FROM events) SELECT s.| FROM t JOIN (SELECT amount AS total FROM orders) AS s ON 1 = 1", map[string]string{"total": "float"}},
{"unicode prefix", "WITH t AS (SELECT amount AS `数額` FROM orders) SELECT t.数| FROM t", map[string]string{"数額": "float"}},
+ {"earlier select alias", "SELECT amount AS total, tot| FROM orders", map[string]string{"total": "float"}},
+ {"alias chain", "SELECT amount AS total, total AS subtotal, sub| FROM orders", map[string]string{"subtotal": "float"}},
+ {"alias in where", "SELECT amount AS total FROM orders WHERE tot| > 0", map[string]string{"total": "float"}},
+ {"alias in prewhere", "SELECT amount AS total FROM orders PREWHERE tot| > 0", map[string]string{"total": "float"}},
+ {"alias in group by", "SELECT amount AS total FROM orders GROUP BY tot|", map[string]string{"total": "float"}},
+ {"alias in having", "SELECT sum(amount) AS total FROM orders HAVING tot| > 0", map[string]string{"total": ""}},
+ {"alias in order by", "SELECT amount AS total FROM orders ORDER BY tot|", map[string]string{"total": "float"}},
+ {"alias in window", "SELECT amount AS total FROM orders WINDOW w AS (PARTITION BY tot|)", map[string]string{"total": "float"}},
+ {"alias in limit", "SELECT amount AS total FROM orders LIMIT tot|", map[string]string{"total": "float"}},
+ {"alias without from", "SELECT 1 AS total ORDER BY tot|", map[string]string{"total": ""}},
+ {"alias shadows field", "SELECT order_id AS amount FROM orders ORDER BY amo|", map[string]string{"amount": "string"}},
+ {"qualified field bypasses alias", "SELECT order_id AS amount FROM orders ORDER BY orders.amo|", map[string]string{"amount": "float"}},
+ {"projected alias chain", "SELECT s.sub| FROM (SELECT amount AS total, total AS subtotal FROM orders) AS s", map[string]string{"subtotal": "float"}},
+ {"no forward select alias", "SELECT tot|, amount AS total FROM orders", nil},
+ {"no self select alias", "SELECT tot| AS total FROM orders", nil},
+ {"no alias in join", "SELECT amount AS total FROM orders JOIN events ON tot| = 1", nil},
+ {"no outer select alias", "SELECT amount AS total FROM orders WHERE order_id IN (SELECT tot| FROM events)", nil},
+ {"no inner select alias", "SELECT tot| FROM orders WHERE order_id IN (SELECT event AS total FROM events)", nil},
+ {"no select alias across statements", "SELECT amount AS total FROM orders; SELECT tot| FROM events", nil},
+ {"no select alias across union", "SELECT amount AS total FROM orders UNION ALL SELECT tot| FROM orders", nil},
+ {"no select alias in cte", "WITH t AS (SELECT tot| FROM orders) SELECT amount AS total FROM orders", nil},
+ {"alias property shadow", "SELECT uuid AS properties FROM events ORDER BY properties.$geo_ci|", nil},
+ {"alias virtual property shadow", "SELECT uuid AS session FROM events ORDER BY session.properties.$entry|", nil},
+ {"qualified properties bypass alias", "SELECT uuid AS properties FROM events ORDER BY events.properties.$geo_ci|", map[string]string{"$geo_city": "String"}},
+ {"no recovered select aliases", "SELECT amount AS total FROM orders WHERE tot| >", nil},
} {
t.Run(test.name, func(t *testing.T) {
position := strings.IndexByte(test.query, '|')
@@ -164,6 +189,9 @@ func TestCompletesScopedProjections(t *testing.T) {
fields := map[string]string{}
for _, suggestion := range result.Suggestions {
if suggestion.Kind == "field" || suggestion.Kind == "property" {
+ if _, duplicate := fields[suggestion.Label]; duplicate {
+ t.Fatalf("duplicate suggestion: %#v", suggestion)
+ }
fields[suggestion.Label] = suggestion.Detail
}
}
@@ -236,7 +264,26 @@ func BenchmarkCompleteDerivedLookups(b *testing.B) {
}
}
-func TestDerivedProjectionPaginationAndLimits(t *testing.T) {
+func TestSelectAliasLookupWorkBudget(t *testing.T) {
+ tables := map[string]catalog.Table{}
+ var sources []string
+ for index := range 128 {
+ name := fmt.Sprintf("source_%d", index)
+ tables[name] = catalog.Table{Name: name, Fields: map[string]catalog.Field{"amount": {Name: "amount", Type: "float"}}}
+ sources = append(sources, name)
+ }
+ schema := catalog.Prepare(&catalog.Catalog{Tables: tables})
+ query := "SELECT " + strings.Repeat("x", 8192) + " AS total FROM " + strings.Join(sources, " CROSS JOIN ") + " ORDER BY tot"
+ if err := querylimits.Validate(query); err != nil {
+ t.Fatal(err)
+ }
+ result, err := Complete(schema, query, len(query), PositionEncodingUTF8, "")
+ if !errors.Is(err, querylimits.ErrFieldLookupTooLarge) || len(result.Suggestions) != 0 {
+ t.Fatalf("result = %#v, err = %v", result, err)
+ }
+}
+
+func TestProjectionPaginationAndLimits(t *testing.T) {
var items []string
for index := 0; index < PageSize+2; index++ {
items = append(items, fmt.Sprintf("amount AS field_%02d", index))
@@ -245,6 +292,7 @@ func TestDerivedProjectionPaginationAndLimits(t *testing.T) {
for _, source := range []string{
"WITH t AS (SELECT " + strings.Join(items, ", ") + " FROM orders) SELECT t.| FROM t",
"SELECT t.| FROM (SELECT " + strings.Join(items, ", ") + " FROM orders) AS t",
+ "SELECT " + strings.Join(items[:PageSize+2], ", ") + " FROM orders ORDER BY field_|",
} {
position := strings.IndexByte(source, '|')
query := strings.Replace(source, "|", "", 1)
@@ -319,6 +367,11 @@ func TestCompletionQuotesIdentifierInsertionText(t *testing.T) {
if err != nil {
t.Fatal(err)
}
+ aliasQuery := "SELECT o.\"order-total\" AS \"billing total\" FROM orders AS o ORDER BY bill"
+ aliasResult, err := Complete(schema, aliasQuery, len(aliasQuery), PositionEncodingUTF8, "")
+ if err != nil {
+ t.Fatal(err)
+ }
for _, test := range []struct {
result Result
@@ -331,6 +384,7 @@ func TestCompletionQuotesIdentifierInsertionText(t *testing.T) {
{result: fieldResult, label: "FROM", insertText: "`FROM`"},
{result: fieldResult, label: "order-total", insertText: "`order-total`"},
{result: fieldResult, label: "tick`value", insertText: "`tick``value`"},
+ {result: aliasResult, label: "billing total", insertText: "`billing total`"},
} {
suggestion, ok := findSuggestion(test.result.Suggestions, test.label)
if !ok || suggestion.InsertText != test.insertText {
diff --git a/services/hogql-language-service/internal/validation/validation.go b/services/hogql-language-service/internal/validation/validation.go
index 738353d706c4..088d4be7c79a 100644
--- a/services/hogql-language-service/internal/validation/validation.go
+++ b/services/hogql-language-service/internal/validation/validation.go
@@ -221,6 +221,9 @@ func validateUnqualifiedField(diagnostics *[]Diagnostic, seen map[string]bool, b
if len(*diagnostics) >= querylimits.MaxDiagnostics || document.LimitError() != nil {
return
}
+ if _, ok := bindings.SelectAlias(ident.Name); ok {
+ return
+ }
uniqueTables := map[string]analysis.Relation{}
for binding := range bindings.UniqueRelations() {
uniqueTables[binding.Name()] = binding
@@ -231,7 +234,7 @@ func validateUnqualifiedField(diagnostics *[]Diagnostic, seen map[string]bool, b
return
}
}
- candidates := make([]catalog.Entry, 0)
+ candidates := slices.Collect(bindings.SelectAliases(""))
for _, binding := range uniqueTables {
candidates = slices.AppendSeq(candidates, binding.Fields())
if document.LimitError() != nil {
diff --git a/services/hogql-language-service/internal/validation/validation_test.go b/services/hogql-language-service/internal/validation/validation_test.go
index acaf06b62830..729c9866d299 100644
--- a/services/hogql-language-service/internal/validation/validation_test.go
+++ b/services/hogql-language-service/internal/validation/validation_test.go
@@ -94,13 +94,18 @@ func TestValidateUnknownTableSuggestsVisibleMatch(t *testing.T) {
}
func TestValidateUnknownAliasedFieldSuggestsVisibleMatch(t *testing.T) {
- result := Validate(schema(), "SELECT o.amuont FROM warehouse_orders AS o")
- if result.Valid || len(result.Diagnostics) != 1 {
- t.Fatalf("result = %#v", result)
- }
- diagnostic := result.Diagnostics[0]
- if diagnostic.Code != "unknown_field" || len(diagnostic.Suggestions) == 0 || diagnostic.Suggestions[0].Label != "amount" || diagnostic.Suggestions[0].Distance != 2 {
- t.Fatalf("diagnostic = %#v", diagnostic)
+ for _, test := range []struct{ query, suggestion string }{
+ {"SELECT o.amuont FROM warehouse_orders AS o", "amount"},
+ {"SELECT amount AS total FROM warehouse_orders ORDER BY totla", "total"},
+ } {
+ result := Validate(schema(), test.query)
+ if result.Valid || len(result.Diagnostics) != 1 {
+ t.Fatalf("query %q: result = %#v", test.query, result)
+ }
+ diagnostic := result.Diagnostics[0]
+ if diagnostic.Code != "unknown_field" || len(diagnostic.Suggestions) == 0 || diagnostic.Suggestions[0].Label != test.suggestion || diagnostic.Suggestions[0].Distance != 2 {
+ t.Fatalf("query %q: diagnostic = %#v", test.query, diagnostic)
+ }
}
}
@@ -116,6 +121,10 @@ func TestValidateAcceptsKnownFieldsAndFunctions(t *testing.T) {
{query: "SELECT s.kind FROM (SELECT event AS kind FROM events) AS s", tableName: "events"},
{query: "WITH t AS (SELECT event AS `Σ` FROM events) SELECT t.`ς` FROM t", tableName: "events"},
{query: "WITH t AS (SELECT event AS kind FROM events) SELECT s.kind FROM (SELECT * FROM t) AS s", tableName: "events"},
+ {query: "SELECT amount AS total, total AS subtotal FROM warehouse_orders PREWHERE subtotal > 0 WHERE total > 0 GROUP BY total, subtotal HAVING total > 1 ORDER BY subtotal", tableName: "warehouse_orders"},
+ {query: "SELECT event AS kind FROM events WHERE uuid IN (SELECT uuid AS kind FROM events WHERE kind != '') ORDER BY kind", tableName: "events"},
+ {query: "SELECT s.subtotal FROM (SELECT amount AS total, total AS subtotal FROM warehouse_orders) AS s", tableName: "warehouse_orders"},
+ {query: "SELECT amount AS amount FROM warehouse_orders ORDER BY amount", tableName: "warehouse_orders"},
} {
result := Validate(schema(), test.query)
if !result.Valid || len(result.Diagnostics) != 0 {
@@ -211,11 +220,21 @@ func TestValidateRejectsUnknownCommonTableExpressionField(t *testing.T) {
}
}
-func TestValidateRejectsUnknownQualifiedFields(t *testing.T) {
+func TestValidateRejectsUnknownFields(t *testing.T) {
for _, query := range []string{
"SELECT missing.event FROM events",
"SELECT missing.properties.value FROM events",
"SELECT missing.* FROM events",
+ "SELECT total, amount AS total FROM warehouse_orders",
+ "SELECT total AS total FROM warehouse_orders",
+ "SELECT amount AS total FROM warehouse_orders JOIN events ON total = 1",
+ "SELECT amount AS total FROM warehouse_orders WHERE order_id IN (SELECT total FROM events)",
+ "SELECT total FROM warehouse_orders WHERE order_id IN (SELECT event AS total FROM events)",
+ "SELECT amount AS total FROM warehouse_orders; SELECT total FROM events",
+ "SELECT amount AS total FROM warehouse_orders UNION ALL SELECT total FROM warehouse_orders",
+ "WITH t AS (SELECT total FROM warehouse_orders) SELECT amount AS total FROM warehouse_orders",
+ "SELECT event AS kind FROM events ORDER BY events.kind",
+ "SELECT amount AS Total FROM warehouse_orders ORDER BY total",
} {
result := Validate(schema(), query)
if result.Valid || len(result.Diagnostics) != 1 || result.Diagnostics[0].Code != "unknown_field" {