:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(hogql): add table and field notices to validation (#104999)
Paweł Szczur5ea283f572a0
diff --git a/docs/internal/hogql-language-service.md b/docs/internal/hogql-language-service.mdindex 33a9df5d1e7e..9054bb05c864 100644--- a/docs/internal/hogql-language-service.md+++ b/docs/internal/hogql-language-service.md@@ -417,10 +417,56 @@ Service failures preserve the original request, including its source context, foGo metadata returns diagnostics and logical table names, not the full Python compiler metadata.`indexUsage: true` does not force Python fallback or enable index analysis in Go.-Go responses leave `index_usage`, `isUsingIndices`, and `ch_table_names` unset, and return an empty `notices` list.+Go-backed Django responses leave `index_usage`, `isUsingIndices`, and `ch_table_names` unset, and return an empty `notices` list until the adapter forwards service notices.Python-only heuristic warnings, type notices, and actionable index warnings are not added to a successful Go response.Index analysis and compiler metadata parity remain separate follow-up work; this routing change does not add a second Python validation pass.+### Table and field notices++The Go validation response includes a separate `notices` array with `message`, `start`, and `end` fields.+These notices identify resolved table references and report known types for fields written in the query.+They use the published, permission-filtered catalog and the same scope resolution as validation.+They do not execute a query, expand the Python compiler's internal expressions, or change whether a query is valid.+Property definitions published as `Numeric` produce `Float` notices, matching Python's HogQL property conversion.++```sql+SELECT timestamp FROM events+```++This query produces a table notice for `events` and a `DateTime` field notice for `timestamp` when that type is published in the catalog.+Warehouse alias notices identify the canonical catalog table, and CTE source notices identify the common table expression without adding it to `table_names`.+Table notices mark named `FROM` and `JOIN` sources; alias declarations, qualifiers in field paths, and derived-subquery aliases do not receive separate table notices.++```sql+SELECT e.person.id FROM events AS e+```++The field notice uses the lazy relation's target schema when the catalog includes the `person` traversal.+An older flat catalog cannot provide that traversal's type information.++```sql+SELECT * FROM events+```++This query produces a table notice, but no field notices for the columns represented by `*`.+Generated field expressions have no matching token in the editor and must not produce hints at unrelated source positions.++Notices remain separate from error and warning diagnostics, with at most 128 notices per response.+Their source ranges follow the requested position encoding, including UTF-16 for the editor.+Unknown or ambiguous fields do not receive a type hint.+SELECT alias hints follow declaration order:++```sql+SELECT event AS v, v, timestamp AS v FROM events ORDER BY v+```++The middle `v` retains the `String` hint from `event`; the later duplicate declaration makes `ORDER BY v` ambiguous, so it receives no hint.+Notice collection reuses the parsed query after validation and stops when its output or lookup budget is exhausted; it does not turn a valid query into an error.+Expression type inference, physical ClickHouse table metadata, and property materialization details remain follow-up work.+Unrecognized catalog type strings are omitted rather than converted into a guessed type.++### Routing metrics+For authenticated requests that have the service configured and the feature flag enabled, the Prometheus counter `hogql_editor_assist_responses_total` counts the backend that produced the final successful editor response.Its bounded attributes are the operation, backend, and routing reason.The operation is `autocomplete` or `metadata`, the backend is `language_service` or `python`, and the reason is `served`, `ineligible`, `service_error`, or `invalid_response`.diff --git a/services/hogql-language-service/internal/analysis/aliases.go b/services/hogql-language-service/internal/analysis/aliases.goindex 1e3476bb54fb..4b4385191ca9 100644--- a/services/hogql-language-service/internal/analysis/aliases.go+++ b/services/hogql-language-service/internal/analysis/aliases.go@@ -78,6 +78,11 @@ func (b Bindings) SelectAlias(name string) (catalog.Entry, bool) {return alias.field, ok}+func (b Bindings) ResolvedSelectAlias(name string) (catalog.Entry, bool) {+ alias, ok := b.selectAlias(name)+ return alias.field, ok && (alias.ambiguousAt == 0 || alias.ambiguousAt > b.aliasCutoff())+}+func (b Bindings) selectAlias(name string) (selectAlias, bool) {cutoff := b.aliasCutoff()if cutoff < 0 || !b.scope.budget.lookup(len(name)+1) {diff --git a/services/hogql-language-service/internal/analysis/document.go b/services/hogql-language-service/internal/analysis/document.goindex 892e1e67e7a9..1b31dafe1591 100644--- a/services/hogql-language-service/internal/analysis/document.go+++ b/services/hogql-language-service/internal/analysis/document.go@@ -26,11 +26,14 @@ type Statement struct {budget *projectionBudgetscopes []*queryScopetables []TableReference+ resolvedTables []TableReferenceanalyzed bool}type TableReference struct {Name string+ Canonical string+ CTE boolStart, End intKnown bool}@@ -114,11 +117,13 @@ func (s *Statement) analyze() {}if cte := resolveCTE(scope, name, start); cte != nil {addBinding(scope, name, alias, Relation{name: cte.name, cte: cte}, start, end)+ s.resolvedTables = append(s.resolvedTables, TableReference{Name: name, Canonical: cte.name, CTE: true, Start: start, End: end, Known: true})return true}table, exists := s.schema.Table(name)s.tables = append(s.tables, TableReference{Name: name, Start: start, End: end, Known: exists})if exists {+ s.resolvedTables = append(s.resolvedTables, TableReference{Name: name, Canonical: table.Name, Start: start, End: end, Known: true})if alias == "" && implicitAlias != name {// HogQL registers multi-part table paths under a double-underscore alias.alias = implicitAlias@@ -139,6 +144,10 @@ func (s *Statement) Tables() iter.Seq[TableReference] {return slices.Values(s.tables)}+func (s *Statement) ResolvedTables() iter.Seq[TableReference] {+ return slices.Values(s.resolvedTables)+}+func (s *Statement) DuplicateSources() iter.Seq[Source] {return func(yield func(Source) bool) {for _, scope := range s.scopes {@@ -217,6 +226,33 @@ func (b Bindings) Relation(name string) (Relation, bool) {return relation, ok}+func (b Bindings) UnambiguousRelation(name string) (Relation, bool) {+ relation, ok := b.Relation(name)+ return relation, ok && b.scope != nil && !b.scope.hasDuplicateSource(name)+}++func (b Bindings) ResolvedField(name string) (catalog.Entry, bool) {+ if b.scope == nil {+ return catalog.Entry{}, false+ }+ var found catalog.Entry+ matches := 0+ for source := range b.sources() {+ if b.scope.hasDuplicateSource(source.name) {+ return catalog.Entry{}, false+ }+ if _, ok := source.relation.Field(name); ok {+ matches+++ field, resolved := source.relation.ResolvedField(name)+ if !resolved {+ return catalog.Entry{}, false+ }+ found = field+ }+ }+ return found, matches == 1 && !b.scope.budget.lookupExceeded+}+func (b Bindings) All() iter.Seq2[string, Relation] {return func(yield func(string, Relation) bool) {for name, relation := range b.relations {@@ -415,6 +451,15 @@ func (r Relation) Field(name string) (catalog.Entry, bool) {return bindingField(r, name)}+func (r Relation) ResolvedField(name string) (catalog.Entry, bool) {+ field, ok := bindingField(r, name)+ if !ok || r.cte == nil {+ return field, ok+ }+ projected, exists := r.cte.fieldIndex[foldedFieldName(name)]+ return field, exists && !projected.ambiguous+}+// Fields yields values without copying catalog indexes or exposing their backing slices.func (r Relation) Fields() iter.Seq[catalog.Entry] {return slices.Values(bindingFields(r))diff --git a/services/hogql-language-service/internal/httpapi/handler_test.go b/services/hogql-language-service/internal/httpapi/handler_test.goindex 813a56bfbfcc..41f3f7a7cdf6 100644--- a/services/hogql-language-service/internal/httpapi/handler_test.go+++ b/services/hogql-language-service/internal/httpapi/handler_test.go@@ -205,6 +205,8 @@ func TestValidateEncodesDiagnosticPositions(t *testing.T) {query := "SELECT '😀', missing FROM events"byteStart := strings.Index(query, "missing")utf16Start := len(utf16.Encode([]rune(query[:byteStart])))+ tableByteStart := strings.Index(query, "events")+ tableUTF16Start := len(utf16.Encode([]rune(query[:tableByteStart])))for _, test := range []struct {encoding string@@ -240,6 +242,16 @@ func TestValidateEncodesDiagnosticPositions(t *testing.T) {if diagnostic.Start != test.start || diagnostic.End != test.start+len("missing") {t.Fatalf("%s diagnostic span = [%d,%d), want [%d,%d)", test.responseEncoding, diagnostic.Start, diagnostic.End, test.start, test.start+len("missing"))}+ if len(result.Notices) != 1 || result.Notices[0].Message != "Table 'events'" {+ t.Fatalf("notices = %#v", result.Notices)+ }+ tableStart := tableByteStart+ if test.responseEncoding == "utf-16" {+ tableStart = tableUTF16Start+ }+ if result.Notices[0].Start != tableStart || result.Notices[0].End != tableStart+len("events") {+ t.Fatalf("%s notice span = [%d,%d), want [%d,%d)", test.responseEncoding, result.Notices[0].Start, result.Notices[0].End, tableStart, tableStart+len("events"))+ }}}diff --git a/services/hogql-language-service/internal/querylimits/limits.go b/services/hogql-language-service/internal/querylimits/limits.goindex 781eaef32dc4..6730336ae5ab 100644--- a/services/hogql-language-service/internal/querylimits/limits.go+++ b/services/hogql-language-service/internal/querylimits/limits.go@@ -6,6 +6,7 @@ const MaxQueryBytes = 64 << 10const MaxNestingDepth = 128const MaxSuggestionInputBytes = 128const MaxDiagnostics = 25+const MaxNotices = 128const MaxCTEProjectedFields = 16 << 10const MaxFieldLookupWork = 1 << 20const MaxRelationTraversalHops = 16diff --git a/services/hogql-language-service/internal/validation/notices.go b/services/hogql-language-service/internal/validation/notices.gonew file mode 100644index 000000000000..bcb9ccbd770e--- /dev/null+++ b/services/hogql-language-service/internal/validation/notices.go@@ -0,0 +1,196 @@+package validation++import (+ "fmt"+ "sort"+ "strings"++ clickhouse "github.com/orian/clickhouse-sql-parser/parser"++ "github.com/PostHog/posthog/services/hogql-language-service/internal/analysis"+ "github.com/PostHog/posthog/services/hogql-language-service/internal/catalog"+ "github.com/PostHog/posthog/services/hogql-language-service/internal/querylimits"+)++type Notice struct {+ Message string `json:"message"`+ Start int `json:"start"`+ End int `json:"end"`+}++type noticeCollector struct {+ query string+ notices []Notice+ seen map[[2]int]bool+}++func newNoticeCollector(query string) *noticeCollector {+ return ¬iceCollector{query: query, seen: make(map[[2]int]bool)}+}++func (c *noticeCollector) add(message string, start, end int) {+ if start < 0 || end > len(c.query) || start >= end {+ return+ }+ if start > 0 && end < len(c.query) && (c.query[start-1] == '`' && c.query[end] == '`' || c.query[start-1] == '"' && c.query[end] == '"') {+ start--+ end+++ }+ if len(c.notices) >= querylimits.MaxNotices || c.seen[[2]int{start, end}] {+ return+ }+ c.seen[[2]int{start, end}] = true+ c.notices = append(c.notices, Notice{Message: message, Start: start, End: end})+}++func displayType(raw string) string {+ switch strings.ToLower(raw) {+ case "string":+ return "String"+ case "integer", "int":+ return "Integer"+ case "float", "numeric":+ return "Float"+ case "boolean", "bool":+ return "Boolean"+ case "datetime":+ return "DateTime"+ case "date":+ return "Date"+ case "uuid":+ return "UUID"+ case "json":+ return "JSON"+ case "array":+ return "Array"+ case "tuple":+ return "Tuple"+ case "decimal":+ return "Decimal"+ default:+ return ""+ }+}++func (c *noticeCollector) addField(ident *clickhouse.Ident, rawType string) {+ if fieldType := displayType(rawType); fieldType != "" {+ c.add(fmt.Sprintf("Field '%s' is of type '%s'", ident.Name, fieldType), int(ident.Pos()), int(ident.End()))+ }+}++func (c *noticeCollector) addProperty(ident *clickhouse.Ident, namespace string, properties *catalog.Index) {+ field, ok := properties.Exact(ident.Name)+ if !ok {+ return+ }+ fieldType := displayType(field.Type)+ if fieldType == "" {+ return+ }+ owner := namespace+ if strings.HasPrefix(owner, "group:") {+ owner = "group"+ }+ c.add(fmt.Sprintf("%s property '%s' is of type '%s'", strings.ToUpper(owner[:1])+owner[1:], ident.Name, fieldType), int(ident.Pos()), int(ident.End()))+}++func (c *noticeCollector) sorted() []Notice {+ sort.Slice(c.notices, func(i, j int) bool {+ if c.notices[i].Start != c.notices[j].Start {+ return c.notices[i].Start < c.notices[j].Start+ }+ return c.notices[i].End < c.notices[j].End+ })+ return c.notices+}++func collectNotices(schema *catalog.PreparedCatalog, document *analysis.Document, query string) []Notice {+ if document.LimitError() != nil {+ return nil+ }+ collector := newNoticeCollector(query)+ for statement := range document.Statements() {+ for table := range statement.ResolvedTables() {+ message := fmt.Sprintf("Table '%s'", table.Name)+ if table.CTE {+ message = fmt.Sprintf("Table '%s' is a common table expression", table.Name)+ } else if table.Canonical != table.Name {+ message = fmt.Sprintf("Table '%s' refers to '%s'", table.Name, table.Canonical)+ }+ collector.add(message, table.Start, table.End)+ }+ ignoredIdents := ignoredIdentifierNodes(statement)+ statement.Walk(func(node clickhouse.Expr) bool {+ if len(collector.notices) >= querylimits.MaxNotices || document.LimitError() != nil {+ return false+ }+ switch typed := node.(type) {+ case *clickhouse.NestedIdentifier:+ if typed.DotIdent == nil {+ return true+ }+ ignoredIdents[typed.Ident] = true+ ignoredIdents[typed.DotIdent] = true+ bindings := statement.BindingsAt(int(node.Pos()), int(node.End()))+ if resolved, ok := bindings.UnambiguousRelation(typed.Ident.Name); ok {+ if field, ok := resolved.ResolvedField(typed.DotIdent.Name); ok {+ collector.addField(typed.DotIdent, field.Type)+ }+ }+ case *clickhouse.Path:+ if len(typed.Fields) < 2 {+ return true+ }+ for _, field := range typed.Fields {+ ignoredIdents[field] = true+ }+ bindings := statement.BindingsAt(int(node.Pos()), int(node.End()))+ parts := make([]string, len(typed.Fields))+ for index, field := range typed.Fields {+ parts[index] = field.Name+ }+ target := bindings.Traversal(parts[:len(parts)-1])+ if target.Explicit {+ if target.Valid && target.PropertyNamespace != "" {+ propertyAt := len(typed.Fields) - 1+ if target.HasProperty {+ propertyAt = target.PropertyAt+ }+ collector.addProperty(typed.Fields[propertyAt], target.PropertyNamespace, schema.Properties(target.PropertyNamespace))+ } else if target.Valid && target.Fields != nil {+ if field, ok := target.Fields.Exact(typed.Fields[len(typed.Fields)-1].Name); ok {+ collector.addField(typed.Fields[len(typed.Fields)-1], field.Type)+ }+ }+ return true+ }+ if namespace, ok := bindings.PropertyNamespace(parts); ok {+ collector.addProperty(typed.Fields[len(typed.Fields)-1], namespace, schema.Properties(namespace))+ return true+ }+ if resolved, ok := bindings.UnambiguousRelation(typed.Fields[0].Name); ok {+ if field, ok := resolved.ResolvedField(typed.Fields[1].Name); ok {+ collector.addField(typed.Fields[1], field.Type)+ }+ }+ case *clickhouse.Ident:+ if ignoredIdents[typed] || typed.Name == "*" || analysis.IsBooleanLiteral(typed) {+ return true+ }+ bindings := statement.BindingsAt(int(node.Pos()), int(node.End()))+ if field, ok := bindings.ResolvedSelectAlias(typed.Name); ok {+ collector.addField(typed, field.Type)+ } else if _, exists := bindings.SelectAlias(typed.Name); !exists {+ if field, ok := bindings.ResolvedField(typed.Name); ok {+ collector.addField(typed, field.Type)+ }+ }+ }+ return true+ })+ if len(collector.notices) >= querylimits.MaxNotices || document.LimitError() != nil {+ break+ }+ }+ return collector.sorted()+}diff --git a/services/hogql-language-service/internal/validation/validation.go b/services/hogql-language-service/internal/validation/validation.goindex 83540568b983..53473ef9e646 100644--- a/services/hogql-language-service/internal/validation/validation.go+++ b/services/hogql-language-service/internal/validation/validation.go@@ -34,6 +34,7 @@ type Diagnostic struct {type Result struct {Valid bool `json:"valid"`Diagnostics []Diagnostic `json:"diagnostics"`+ Notices []Notice `json:"notices"`TableNames []string `json:"tableNames"`DurationMicros int64 `json:"durationMicros"`}@@ -46,7 +47,7 @@ func Validate(schema *catalog.PreparedCatalog, query string) Result {if errors.Is(err, querylimits.ErrQueryTooLarge) || errors.Is(err, querylimits.ErrQueryTooDeep) {code = "query_limit"}- return result([]Diagnostic{{Code: code, Message: err.Error(), Start: 0, End: len(query)}}, nil, started)+ return result([]Diagnostic{{Code: code, Message: err.Error(), Start: 0, End: len(query)}}, nil, nil, started)}var diagnostics []Diagnostic@@ -76,31 +77,7 @@ func Validate(schema *catalog.PreparedCatalog, query string) Result {End: source.End(),})}- ignoredIdents := map[*clickhouse.Ident]bool{}- statement.Walk(func(node clickhouse.Expr) bool {- switch typed := node.(type) {- case *clickhouse.TableIdentifier:- ignoredIdents[typed.Database] = true- ignoredIdents[typed.Table] = true- case *clickhouse.CTEStmt:- if ident, ok := typed.Expr.(*clickhouse.Ident); ok {- ignoredIdents[ident] = true- }- case *clickhouse.FunctionExpr:- ignoredIdents[typed.Name] = true- case *clickhouse.IntervalExpr:- ignoredIdents[typed.Unit] = true- case *clickhouse.IntervalFrom:- ignoredIdents[typed.Interval] = true- case *clickhouse.SelectItem:- ignoredIdents[typed.Alias] = true- case *clickhouse.AliasExpr:- if alias, ok := typed.Alias.(*clickhouse.Ident); ok {- ignoredIdents[alias] = true- }- }- return true- })+ ignoredIdents := ignoredIdentifierNodes(statement)seen := map[string]bool{}statement.Walk(func(node clickhouse.Expr) bool {switch typed := node.(type) {@@ -184,7 +161,7 @@ func Validate(schema *catalog.PreparedCatalog, query string) Result {Code: "query_limit", Message: err.Error(), Start: 0, End: len(query),})}- return result(diagnostics, referencedTableNames, started)+ return result(diagnostics, collectNotices(schema, document, query), referencedTableNames, started)}func ValidateWithEncoding(schema *catalog.PreparedCatalog, query string, encoding textposition.Encoding) (Result, error) {@@ -204,9 +181,50 @@ func ValidateWithEncoding(schema *catalog.PreparedCatalog, query string, encodinresult.Diagnostics[index].Start = startresult.Diagnostics[index].End = end}+ for index := range result.Notices {+ start, err := textposition.FromByteOffset(query, result.Notices[index].Start, encoding)+ if err != nil {+ return Result{}, err+ }+ end, err := textposition.FromByteOffset(query, result.Notices[index].End, encoding)+ if err != nil {+ return Result{}, err+ }+ result.Notices[index].Start = start+ result.Notices[index].End = end+ }return result, nil}+func ignoredIdentifierNodes(statement *analysis.Statement) map[*clickhouse.Ident]bool {+ ignoredIdents := map[*clickhouse.Ident]bool{}+ statement.Walk(func(node clickhouse.Expr) bool {+ switch typed := node.(type) {+ case *clickhouse.TableIdentifier:+ ignoredIdents[typed.Database] = true+ ignoredIdents[typed.Table] = true+ case *clickhouse.CTEStmt:+ if ident, ok := typed.Expr.(*clickhouse.Ident); ok {+ ignoredIdents[ident] = true+ }+ case *clickhouse.FunctionExpr:+ ignoredIdents[typed.Name] = true+ case *clickhouse.IntervalExpr:+ ignoredIdents[typed.Unit] = true+ case *clickhouse.IntervalFrom:+ ignoredIdents[typed.Interval] = true+ case *clickhouse.SelectItem:+ ignoredIdents[typed.Alias] = true+ case *clickhouse.AliasExpr:+ if alias, ok := typed.Alias.(*clickhouse.Ident); ok {+ ignoredIdents[alias] = true+ }+ }+ return true+ })+ return ignoredIdents+}+func validateProperty(diagnostics *[]Diagnostic, seen map[string]bool, properties *catalog.Index, ident *clickhouse.Ident) {if len(*diagnostics) >= querylimits.MaxDiagnostics {return@@ -483,15 +501,18 @@ func isASCII(value string) bool {return true}-func result(diagnostics []Diagnostic, tableNames []string, started time.Time) Result {+func result(diagnostics []Diagnostic, notices []Notice, tableNames []string, started time.Time) Result {if diagnostics == nil {diagnostics = []Diagnostic{}}if tableNames == nil {tableNames = []string{}}+ if notices == nil {+ notices = []Notice{}+ }return Result{- Valid: len(diagnostics) == 0, Diagnostics: diagnostics, TableNames: tableNames,+ Valid: len(diagnostics) == 0, Diagnostics: diagnostics, Notices: notices, TableNames: tableNames,DurationMicros: time.Since(started).Microseconds(),}}diff --git a/services/hogql-language-service/internal/validation/validation_test.go b/services/hogql-language-service/internal/validation/validation_test.goindex 363f71665e62..9b5eed7113d1 100644--- a/services/hogql-language-service/internal/validation/validation_test.go+++ b/services/hogql-language-service/internal/validation/validation_test.go@@ -29,7 +29,7 @@ func schema() *catalog.PreparedCatalog {}},"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"}, {Name: "café", ValueType: "String"}},+ "event": {{Name: "$geo_city", ValueType: "String"}, {Name: "café", ValueType: "String"}, {Name: "amount", ValueType: "Numeric"}},"person": {{Name: "$geo_country", ValueType: "String"}},"session": {{Name: "$entry_current_url", ValueType: "String"}},"group:0": {{Name: "industry", ValueType: "String"}},@@ -89,6 +89,175 @@ func TestValidateTraversalRelations(t *testing.T) {}}+func TestValidateNotices(t *testing.T) {+ tests := []struct {+ name string+ query string+ schema *catalog.PreparedCatalog+ notices []struct{ source, message string }+ }{+ {+ name: "qualified fields and table",+ query: "SELECT e.event, e.timestamp FROM events AS e",+ notices: []struct{ source, message string }{+ {"event", "Field 'event' is of type 'String'"},+ {"timestamp", "Field 'timestamp' is of type 'DateTime'"},+ {"events", "Table 'events'"},+ },+ },+ {+ name: "cte projection",+ query: "WITH x AS (SELECT event AS kind FROM events) SELECT x.kind FROM x",+ notices: []struct{ source, message string }{+ {"event", "Field 'event' is of type 'String'"},+ {"events", "Table 'events'"},+ {"kind", "Field 'kind' is of type 'String'"},+ {"x", "Table 'x' is a common table expression"},+ },+ },+ {+ name: "select alias before duplicate",+ query: "SELECT event AS v, v, timestamp AS v FROM events",+ notices: []struct{ source, message string }{+ {"event", "Field 'event' is of type 'String'"},+ {"v", "Field 'v' is of type 'String'"},+ {"timestamp", "Field 'timestamp' is of type 'DateTime'"},+ {"events", "Table 'events'"},+ },+ },+ {+ name: "property",+ query: "SELECT e.properties.$geo_city FROM events AS e",+ notices: []struct{ source, message string }{+ {"$geo_city", "Event property '$geo_city' is of type 'String'"},+ {"events", "Table 'events'"},+ },+ },+ {+ name: "numeric property",+ query: "SELECT e.properties.amount FROM events AS e",+ notices: []struct{ source, message string }{+ {"amount", "Event property 'amount' is of type 'Float'"},+ {"events", "Table 'events'"},+ },+ },+ {+ name: "traversed property",+ query: "SELECT e.person.properties.plan FROM events AS e",+ schema: traversalSchema(),+ notices: []struct{ source, message string }{+ {"plan", "Person property 'plan' is of type 'String'"},+ {"events", "Table 'events'"},+ },+ },+ {+ name: "quoted field",+ query: "SELECT `event` FROM events",+ notices: []struct{ source, message string }{+ {"`event`", "Field 'event' is of type 'String'"},+ {"events", "Table 'events'"},+ },+ },+ {+ name: "double-quoted field",+ query: "SELECT \"event\" FROM events",+ notices: []struct{ source, message string }{+ {"\"event\"", "Field 'event' is of type 'String'"},+ {"events", "Table 'events'"},+ },+ },+ {+ name: "relation traversal",+ query: "SELECT e.person.email FROM events AS e",+ schema: traversalSchema(),+ notices: []struct{ source, message string }{+ {"email", "Field 'email' is of type 'String'"},+ {"events", "Table 'events'"},+ },+ },+ {+ name: "unicode offsets",+ query: "SELECT '🐱', event FROM events",+ notices: []struct{ source, message string }{+ {"event", "Field 'event' is of type 'String'"},+ {"events", "Table 'events'"},+ },+ },+ {+ name: "wildcard",+ query: "SELECT * FROM events",+ notices: []struct{ source, message string }{+ {"events", "Table 'events'"},+ },+ },+ {+ name: "unknown field",+ query: "SELECT missing FROM events",+ notices: []struct{ source, message string }{+ {"events", "Table 'events'"},+ },+ },+ {+ name: "unresolved qualifier",+ query: "SELECT missing.event FROM events",+ notices: []struct{ source, message string }{+ {"events", "Table 'events'"},+ },+ },+ }+ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ testSchema := test.schema+ if testSchema == nil {+ testSchema = schema()+ }+ result := Validate(testSchema, test.query)+ if len(result.Notices) != len(test.notices) {+ t.Fatalf("notices = %#v", result.Notices)+ }+ for index, expected := range test.notices {+ actual := result.Notices[index]+ if test.query[actual.Start:actual.End] != expected.source || actual.Message != expected.message {+ t.Fatalf("notice %d = %#v, want %q: %q", index, actual, expected.source, expected.message)+ }+ }+ })+ }+}++func TestValidateNoticesUseCanonicalTableAndSkipAmbiguousFields(t *testing.T) {+ aliased := catalog.Prepare(&catalog.Catalog{+ Tables: map[string]catalog.Table{"warehouse_orders": {+ Name: "warehouse_orders", Fields: map[string]catalog.Field{"order_id": {Type: "integer"}},+ }},+ TableAliases: map[string]string{"orders": "warehouse_orders"},+ Properties: map[string][]catalog.Property{},+ })+ query := "SELECT orders.order_id FROM orders"+ result := Validate(aliased, query)+ if !result.Valid || len(result.Notices) != 2 || result.Notices[0].Message != "Field 'order_id' is of type 'Integer'" || result.Notices[1].Message != "Table 'orders' refers to 'warehouse_orders'" {+ t.Fatalf("alias notices = %#v", result)+ }+ for _, query := range []string{+ "SELECT amount FROM warehouse_orders AS o JOIN warehouse_orders AS p ON o.order_id = p.order_id",+ "WITH x AS (SELECT event AS v, timestamp AS v FROM events) SELECT x.v FROM x",+ "SELECT event AS v, timestamp AS v FROM events ORDER BY v",+ } {+ checked := Validate(schema(), query)+ fieldAt := strings.LastIndex(query, "v")+ if strings.Contains(query, "amount") {+ fieldAt = strings.Index(query, "amount")+ } else if strings.Contains(query, "x.v") {+ fieldAt = strings.Index(query, "x.v") + len("x.")+ }+ for _, notice := range checked.Notices {+ if notice.Start == fieldAt {+ t.Fatalf("ambiguous field has notice in %q: %#v", query, notice)+ }+ }+ }+}+func TestTraversalRelationHopLimit(t *testing.T) {parts := make([]string, querylimits.MaxRelationTraversalHops+1)for index := range parts {@@ -147,6 +316,19 @@ func TestValidateCapsDiagnostics(t *testing.T) {}}+func TestValidateCapsNoticesWithoutSuppressingDiagnostics(t *testing.T) {+ fields := strings.Repeat("event, ", querylimits.MaxNotices) + "event"+ valid := Validate(schema(), "SELECT "+fields+" FROM events")+ if !valid.Valid || len(valid.Notices) != querylimits.MaxNotices {+ t.Fatalf("valid result = %#v", valid)+ }++ invalid := Validate(schema(), "SELECT "+fields+", missing FROM events")+ if invalid.Valid || len(invalid.Diagnostics) != 1 || invalid.Diagnostics[0].Code != "unknown_field" || len(invalid.Notices) > querylimits.MaxNotices {+ t.Fatalf("invalid result = %#v", invalid)+ }+}+func TestValidateUnknownTableSuggestsVisibleMatch(t *testing.T) {result := Validate(schema(), "SELECT order_id FROM warehose_orders")if result.Valid || len(result.Diagnostics) != 1 {