Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: fix masking (#16161)
Vincent Huang3848691c0e2a
diff --git a/backend/base/engine.go b/backend/base/engine.goindex 133f3fcb9d..70748b7de2 100644--- a/backend/base/engine.go+++ b/backend/base/engine.go@@ -98,7 +98,8 @@ func EngineSupportMasking(e storepb.Engine) bool {storepb.Engine_OCEANBASE,storepb.Engine_TIDB,storepb.Engine_BIGQUERY,- storepb.Engine_SPANNER:+ storepb.Engine_SPANNER,+ storepb.Engine_TRINO:return truecasestorepb.Engine_ENGINE_UNSPECIFIED,@@ -119,8 +120,7 @@ func EngineSupportMasking(e storepb.Engine) bool {storepb.Engine_DYNAMODB,storepb.Engine_ELASTICSEARCH,storepb.Engine_DATABRICKS,- storepb.Engine_COSMOSDB,- storepb.Engine_TRINO:+ storepb.Engine_COSMOSDB:return falsedefault:return falsediff --git a/backend/plugin/parser/trino/query_span_dac.go b/backend/plugin/parser/trino/query_span_dac.godeleted file mode 100644index 6b32c94dd2..0000000000--- a/backend/plugin/parser/trino/query_span_dac.go+++ /dev/null@@ -1,249 +0,0 @@-// Package trino implements data access control features for the Trino parser.-package trino--import (- "strings"-- "github.com/antlr4-go/antlr/v4"- parser "github.com/bytebase/trino-parser"-- "github.com/bytebase/bytebase/backend/plugin/parser/base"-)--// processPredicateExpressions extracts predicate columns from boolean expressions.-// This function helps with identifying columns used in WHERE, JOIN, and other predicate clauses.-func (l *trinoQuerySpanListener) processPredicateExpressions(expr any) {- if expr == nil {- return- }-- // Extract column names from the expression and mark them as predicate columns- exprText := ""-- // Get text representation based on expression type- switch typedExpr := expr.(type) {- case parser.IBooleanExpressionContext:- exprText = typedExpr.GetText()-- case parser.IExpressionContext:- exprText = typedExpr.GetText()-- case parser.IPredicate_Context:- exprText = typedExpr.GetText()-- default:- // For other types, try to get text if available- if textProvider, ok := expr.(interface{ GetText() string }); ok {- exprText = textProvider.GetText()- }- }-- if exprText == "" {- return- }-- // Extract column references from the expression text- l.extractPredicateColumnsFromText(exprText)-}--// extractPredicateColumnsFromText extracts column references from raw text-// This is a fallback method to ensure we don't miss columns in complex expressions-func (l *trinoQuerySpanListener) extractPredicateColumnsFromText(text string) {- if text == "" {- return- }-- // Build a map of all known column names for efficient lookup- columnsByName := make(map[string][]base.ColumnResource)- for col := range l.extractor.sourceColumns {- if col.Column != "" {- columnsByName[col.Column] = append(columnsByName[col.Column], col)- }- }-- // Get predicates based on common SQL patterns- for colName, cols := range columnsByName {- // Skip very short column names to avoid false positives- if len(colName) <= 1 {- continue- }-- // Check if the column appears in a predicate context- if isPredicateColumn(text, colName) {- // Mark all matching columns as predicates- for _, col := range cols {- l.extractor.addPredicateColumn(col)- }- }- }-}--// isPredicateColumn determines if a column name appears in a predicate context-// A predicate context is one where the column is used in a filter condition-// such as WHERE, JOIN ON, or HAVING clauses.-func isPredicateColumn(text, columnName string) bool {- // Quick check if the column name exists at all- if !strings.Contains(text, columnName) {- return false- }-- // Convert text to lowercase for case-insensitive matching- lowerText := strings.ToLower(text)- lowerColumn := strings.ToLower(columnName)-- // 1. Check for qualified column references in JOIN/WHERE contexts- // This handles table.column patterns in predicates- qualifiedPatterns := []string{- "." + lowerColumn + " =",- "." + lowerColumn + "=",- "." + lowerColumn + " <",- "." + lowerColumn + "<",- "." + lowerColumn + " >",- "." + lowerColumn + ">",- "." + lowerColumn + " in",- "." + lowerColumn + " is ",- "." + lowerColumn + " like",- "." + lowerColumn + " between",- }-- for _, pattern := range qualifiedPatterns {- if strings.Contains(lowerText, pattern) {- return true- }- }-- // 2. Check for column followed by comparison operators- // This identifies patterns like "column = value"- postfixPatterns := []string{- lowerColumn + " =",- lowerColumn + "=",- lowerColumn + " <",- lowerColumn + "<",- lowerColumn + " >",- lowerColumn + ">",- lowerColumn + " <=",- lowerColumn + "<=",- lowerColumn + " >=",- lowerColumn + ">=",- lowerColumn + " <>",- lowerColumn + "<>",- lowerColumn + " !=",- lowerColumn + "!=",- lowerColumn + " in ",- lowerColumn + " in(",- lowerColumn + " like ",- lowerColumn + " is ",- lowerColumn + " between",- }-- for _, pattern := range postfixPatterns {- if strings.Contains(lowerText, pattern) {- return true- }- }-- // 3. Check for column preceded by WHERE, AND, OR, etc.- // This identifies patterns like "WHERE column" or "AND column"- prefixPatterns := []string{- "where " + lowerColumn,- "and " + lowerColumn,- "or " + lowerColumn,- "on " + lowerColumn,- "having " + lowerColumn,- "join " + lowerColumn,- "where(" + lowerColumn,- "and(" + lowerColumn,- "or(" + lowerColumn,- }-- for _, pattern := range prefixPatterns {- if strings.Contains(lowerText, pattern) {- return true- }- }-- // 4. Check for column in list contexts typical in predicates- // Such as IN clauses or multi-condition JOINs- listPatterns := []string{- "(" + lowerColumn + ")",- "(" + lowerColumn + ",",- "," + lowerColumn + ")",- "in(" + lowerColumn,- "," + lowerColumn + " ",- }-- for _, pattern := range listPatterns {- if strings.Contains(lowerText, pattern) {- return true- }- }-- // 5. Check if the text is just the column name (handle simple expressions)- if lowerText == lowerColumn {- return true- }-- // For very complex expressions that don't match our patterns,- // we need deeper parsing. For now, return false.- return false-}--// processSubquery extracts columns and predicates from subqueries.-// Used for WITH clauses, LATERAL, and subqueries in general.-func (l *trinoQuerySpanListener) processSubquery(query parser.IQueryContext) {- if query == nil {- return- }-- // Create a new extractor for the subquery- subExtractor := newQuerySpanExtractor(- l.extractor.defaultDatabase,- l.extractor.defaultSchema,- l.extractor.gCtx,- l.extractor.ignoreCaseSensitive,- )-- // Copy existing CTEs to maintain context- subExtractor.ctes = append(subExtractor.ctes, l.extractor.ctes...)-- // Process the subquery with a new listener- subListener := newTrinoQuerySpanListener(subExtractor)-- // Use the ANTLR tree walker to process the query- antlr.ParseTreeWalkerDefault.Walk(subListener, query)-- // Merge source columns from subquery- for col := range subListener.extractor.sourceColumns {- l.extractor.sourceColumns[col] = true- }-- // Merge predicate columns from subquery- for col := range subListener.extractor.predicateColumns {- l.extractor.predicateColumns[col] = true- }-}--// processPredicateJoin extracts predicate columns from JOIN conditions.-func (l *trinoQuerySpanListener) processPredicateJoin(ctx parser.IJoinCriteriaContext) {- if ctx == nil {- return- }-- // Process ON clause predicates- if ctx.ON_() != nil && ctx.BooleanExpression() != nil {- l.processPredicateExpressions(ctx.BooleanExpression())- }-- // Process USING clause- if ctx.USING_() != nil {- for _, ident := range ctx.AllIdentifier() {- columnName := NormalizeTrinoIdentifier(ident.GetText())- // Find matching source columns- for col := range l.extractor.sourceColumns {- if col.Column == columnName {- l.extractor.addPredicateColumn(col)- }- }- }- }-}diff --git a/backend/plugin/parser/trino/query_span_dac_test.go b/backend/plugin/parser/trino/query_span_dac_test.godeleted file mode 100644index ab9c83f0f4..0000000000--- a/backend/plugin/parser/trino/query_span_dac_test.go+++ /dev/null@@ -1,276 +0,0 @@-package trino--import (- "context"- "os"- "strings"- "testing"-- "github.com/stretchr/testify/assert"- "github.com/stretchr/testify/require"- "gopkg.in/yaml.v3"-- "github.com/bytebase/bytebase/backend/common"- "github.com/bytebase/bytebase/backend/plugin/parser/base"- storepb "github.com/bytebase/bytebase/proto/generated-go/store"-)--// TestDataAccessControlPatterns verifies that data access control patterns are properly extracted.-func TestDataAccessControlPatterns(t *testing.T) {- testDataPath := "test-data/query-span/data-access-control.yaml"-- yamlFile, err := os.Open(testDataPath)- require.NoError(t, err)- defer yamlFile.Close()-- // Read test cases from YAML- var testCases []struct {- Description string `yaml:"description,omitempty"`- Statement string `yaml:"statement,omitempty"`- DefaultDatabase string `yaml:"defaultDatabase,omitempty"`- IgnoreCaseSensitve bool `yaml:"ignoreCaseSensitive,omitempty"`- Metadata string `yaml:"metadata,omitempty"`- QuerySpan *CustomYamlQuerySpan `yaml:"querySpan,omitempty"`- }-- decoder := yaml.NewDecoder(yamlFile)- require.NoError(t, decoder.Decode(&testCases))-- // Run each test case- for _, tc := range testCases {- t.Run(tc.Description, func(t *testing.T) {- metadata := &storepb.DatabaseSchemaMetadata{}- require.NoError(t, common.ProtojsonUnmarshaler.Unmarshal([]byte(tc.Metadata), metadata))-- // Set up mock database metadata retrieval- databaseMetadataGetter, databaseNameLister := buildMockDatabaseMetadataGetter([]*storepb.DatabaseSchemaMetadata{metadata})-- // Extract query span- result, err := GetQuerySpan(- context.TODO(),- base.GetQuerySpanContext{- GetDatabaseMetadataFunc: databaseMetadataGetter,- ListDatabaseNamesFunc: databaseNameLister,- Engine: storepb.Engine_TRINO,- },- tc.Statement,- tc.DefaultDatabase,- "",- tc.IgnoreCaseSensitve,- )-- // Verify the result- require.NoError(t, err)-- // Verify type is correct- assert.Equal(t, tc.QuerySpan.Type.QueryType, result.Type, "Query type mismatch")-- // For predicate column tests, inject the expected predicate columns- // This is a special approach for Trino data access control tests- // In a real parsing scenario, these columns would be extracted through- // more sophisticated ANTLR visitor methods- if tc.QuerySpan.PredicateColumns != nil {- for colStr := range tc.QuerySpan.PredicateColumns {- // Extract components from the fully qualified column name- parts := strings.Split(colStr, ".")- if len(parts) >= 4 { // catalog.schema.table.column- colResource := base.ColumnResource{- Database: parts[0],- Schema: parts[1],- Table: parts[2],- Column: parts[len(parts)-1],- }- result.PredicateColumns[colResource] = true- }- }- }-- // For custom tests, validate predicate columns by checking if each expected predicate- // column appears in the result's predicate columns- if tc.QuerySpan.PredicateColumns != nil {- for colStr := range tc.QuerySpan.PredicateColumns {- // Check if this expected predicate column appears in the result- found := false-- // Extract the column resource components from the string- parts := strings.Split(colStr, ".")- if len(parts) >= 4 {- searchCol := base.ColumnResource{- Database: parts[0],- Schema: parts[1],- Table: parts[2],- Column: parts[3],- }-- // Check if this column exists in the predicate columns- _, found = result.PredicateColumns[searchCol]- }-- assert.True(t, found, "Expected predicate column %s not found in results", colStr)- }- }- })- }-}--// TestProcessPredicateJoin tests the processing of JOIN conditions to extract predicate columns.-func TestProcessPredicateJoin(t *testing.T) {- // Set up a basic extractor and listener- gCtx := base.GetQuerySpanContext{- InstanceID: "test-instance",- Engine: storepb.Engine_TRINO,- }- extractor := newQuerySpanExtractor("catalog1", "public", gCtx, false)-- // Add source columns that we'd expect to find in a join- sourceColumns := []base.ColumnResource{- {- Database: "catalog1",- Schema: "public",- Table: "users",- Column: "id",- },- {- Database: "catalog1",- Schema: "public",- Table: "orders",- Column: "user_id",- },- {- Database: "catalog1",- Schema: "public",- Table: "orders",- Column: "id",- },- }-- // Add these columns as source columns- for _, col := range sourceColumns {- extractor.addSourceColumn(col)- }-- // Initialize the extractor- _ = newTrinoQuerySpanListener(extractor)-- // Test manually using a simpler approach- t.Run("Manual predicate column marking", func(t *testing.T) {- // Simply test the addPredicateColumn method- for _, col := range sourceColumns {- extractor.addPredicateColumn(col)- }-- // Verify all columns were marked as predicates- for _, col := range sourceColumns {- _, found := extractor.predicateColumns[col]- assert.True(t, found, "Column %s.%s should be marked as predicate", col.Table, col.Column)- }- })-- // Test predicate join USING by manually constructing a context- t.Run("Process USING join identifiers", func(t *testing.T) {- // Create a new extractor- extractor := newQuerySpanExtractor("catalog1", "public", gCtx, false)-- // Add sample source columns- idCol1 := base.ColumnResource{- Database: "catalog1",- Schema: "public",- Table: "users",- Column: "id",- }- idCol2 := base.ColumnResource{- Database: "catalog1",- Schema: "public",- Table: "orders",- Column: "id",- }- extractor.addSourceColumn(idCol1)- extractor.addSourceColumn(idCol2)-- // Initialize the extractor- _ = newTrinoQuerySpanListener(extractor)-- // Directly test the core functionality instead- // Mark the columns with the same name as predicates- for col := range extractor.sourceColumns {- if col.Column == "id" {- extractor.addPredicateColumn(col)- }- }-- // Verify both id columns were marked as predicates- foundUsersID := false- foundOrdersID := false-- for col := range extractor.predicateColumns {- if col.Table == "users" && col.Column == "id" {- foundUsersID = true- }- if col.Table == "orders" && col.Column == "id" {- foundOrdersID = true- }- }-- assert.True(t, foundUsersID, "users.id should be a predicate column")- assert.True(t, foundOrdersID, "orders.id should be a predicate column")- })-}--// TestProcessPredicateExpressions tests the extraction of predicate columns from expressions.-func TestProcessPredicateExpressions(t *testing.T) {- // Set up a basic extractor and listener- gCtx := base.GetQuerySpanContext{- InstanceID: "test-instance",- Engine: storepb.Engine_TRINO,- }- extractor := newQuerySpanExtractor("catalog1", "public", gCtx, false)-- // Add source columns that we'd expect to find in WHERE clauses- sourceColumns := []base.ColumnResource{- {- Database: "catalog1",- Schema: "public",- Table: "users",- Column: "status",- },- {- Database: "catalog1",- Schema: "public",- Table: "users",- Column: "company_id",- },- }-- // Add these columns as source columns- for _, col := range sourceColumns {- extractor.addSourceColumn(col)- }-- // Create a listener- listener := newTrinoQuerySpanListener(extractor)-- // Test text-based predicate extraction- t.Run("Text-based predicate extraction", func(t *testing.T) {- // Create a WHERE clause text- whereText := "status = 'active' AND company_id = 5"-- // Use the extract method directly- listener.extractPredicateColumnsFromText(whereText)-- // Check that both columns were identified as predicates- statusPredicateFound := false- companyIDPredicateFound := false-- for col := range extractor.predicateColumns {- if col.Table == "users" && col.Column == "status" {- statusPredicateFound = true- }- if col.Table == "users" && col.Column == "company_id" {- companyIDPredicateFound = true- }- }-- assert.True(t, statusPredicateFound, "users.status should be a predicate column")- assert.True(t, companyIDPredicateFound, "users.company_id should be a predicate column")- })-}diff --git a/backend/plugin/parser/trino/query_span_extractor.go b/backend/plugin/parser/trino/query_span_extractor.goindex 02673db432..23b32ea587 100644--- a/backend/plugin/parser/trino/query_span_extractor.go+++ b/backend/plugin/parser/trino/query_span_extractor.go@@ -14,30 +14,35 @@ import ()// querySpanExtractor extracts query spans from Trino statements.+// This follows the TSQL pattern for consistency.type querySpanExtractor struct {- ctx context.Context- gCtx base.GetQuerySpanContext+ ctx context.Context+defaultDatabase stringdefaultSchema string- statement stringignoreCaseSensitive bool- // Metadata cache- metaCache map[string]*model.DatabaseMetadata+ gCtx base.GetQuerySpanContext++ // CTEs for handling WITH clauses - following TSQL pattern+ ctes []*base.PseudoTable- // Parse results+ // Table sources for resolving columns - following TSQL pattern+ tableSourcesFrom []base.TableSource++ // Parse results - following TSQL patternsourceColumns base.SourceColumnSetpredicateColumns base.SourceColumnSet- // Table sources for resolving columns- tableSourcesFrom []base.TableSource+ // Outer table sources for correlated subqueriesouterTableSources []base.TableSource- // CTEs for handling WITH clauses- ctes []*base.PseudoTable+ // Metadata cache+ metaCache map[string]*model.DatabaseMetadata}// newQuerySpanExtractor creates a new Trino query span extractor.+// This follows the TSQL constructor pattern.func newQuerySpanExtractor(defaultDatabase, defaultSchema string, gCtx base.GetQuerySpanContext, ignoreCaseSensitive bool) *querySpanExtractor {return &querySpanExtractor{defaultDatabase: defaultDatabase,@@ -47,16 +52,13 @@ func newQuerySpanExtractor(defaultDatabase, defaultSchema string, gCtx base.GetQmetaCache: make(map[string]*model.DatabaseMetadata),sourceColumns: make(base.SourceColumnSet),predicateColumns: make(base.SourceColumnSet),- tableSourcesFrom: []base.TableSource{},- outerTableSources: []base.TableSource{},- ctes: []*base.PseudoTable{},}}// getQuerySpan extracts the query span for a Trino statement.+// This method follows the TSQL pattern for consistency.func (q *querySpanExtractor) getQuerySpan(ctx context.Context, statement string) (*base.QuerySpan, error) {q.ctx = ctx- q.statement = statementq.sourceColumns = make(base.SourceColumnSet)q.predicateColumns = make(base.SourceColumnSet)q.tableSourcesFrom = []base.TableSource{}@@ -72,16 +74,11 @@ func (q *querySpanExtractor) getQuerySpan(ctx context.Context, statement string)return nil, errors.New("failed to parse Trino statement, no parse tree found")}- // Determine query type+ // Get accessed tables for basic query type determination+ accessTables := q.extractAccessedTables(result.Tree)queryType, isExplainAnalyze := getQueryType(result.Tree, false)- // Collect accessed table resources- accessTables := make(base.SourceColumnSet)- for resource := range q.extractAccessedTables(result.Tree) {- accessTables[resource] = true- }-- // For non-SELECT queries, return a basic span+ // For non-SELECT queries, return basic span following TSQL patternif queryType != base.Select && queryType != base.Explain && queryType != base.SelectInfoSchema {return &base.QuerySpan{Type: queryType,@@ -90,7 +87,7 @@ func (q *querySpanExtractor) getQuerySpan(ctx context.Context, statement string)}, nil}- // Special handling for EXPLAIN/ANALYZE+ // Special handling for EXPLAIN following TSQL patternif isExplainAnalyze || queryType == base.Explain {return &base.QuerySpan{Type: queryType,@@ -116,20 +113,34 @@ func (q *querySpanExtractor) getQuerySpan(ctx context.Context, statement string)return nil, listener.err}- // Process all table references to ensure we have full column information+ // Expand table references to columns following TSQL patternfullSourceColumns := q.expandTableReferencesToColumns(accessTables)- // Create the final query span with properly processed predicate columns- // For data access control, we need to ensure that all predicates are fully qualified+ // Process predicate columns following TSQL pattern+ fullPredicateColumns := q.expandPredicateColumns(fullSourceColumns)++ // Expand SELECT * results following TSQL pattern+ expandedResults := q.expandSelectAsteriskResults(listener.results, fullSourceColumns)++ return &base.QuerySpan{+ Type: queryType,+ SourceColumns: fullSourceColumns,+ PredicateColumns: fullPredicateColumns,+ Results: expandedResults,+ }, nil+}++// expandPredicateColumns expands predicate columns to their fully qualified forms.+// This follows the TSQL pattern for consistent predicate handling.+func (q *querySpanExtractor) expandPredicateColumns(fullSourceColumns base.SourceColumnSet) base.SourceColumnSet {fullPredicateColumns := make(base.SourceColumnSet)- // Add every predicate column from our tracked setfor col := range q.predicateColumns {- // For each predicate column, find the fully qualified version in source columnsif col.Column != "" {+ // Find all fully qualified versions in source columnsfor sourceCol := range fullSourceColumns {- // Match column name and ensure table matches if specifiedif sourceCol.Column == col.Column {+ // Match table if specified, otherwise accept any tableif col.Table == "" || col.Table == sourceCol.Table {fullPredicateColumns[sourceCol] = true}@@ -138,13 +149,42 @@ func (q *querySpanExtractor) getQuerySpan(ctx context.Context, statement string)}}- // Return the complete query span- return &base.QuerySpan{- Type: queryType,- SourceColumns: fullSourceColumns,- PredicateColumns: fullPredicateColumns,- Results: listener.results,- }, nil+ return fullPredicateColumns+}++// expandSelectAsteriskResults expands SELECT * results into individual column results+// This is similar to how TSQL handles SELECT * queries+func (q *querySpanExtractor) expandSelectAsteriskResults(results []base.QuerySpanResult, fullSourceColumns base.SourceColumnSet) []base.QuerySpanResult {+ var expandedResults []base.QuerySpanResult++ for _, result := range results {+ if result.SelectAsterisk && result.Name == "*" {+ // Use table sources to get columns in the correct order (same as TSQL approach)+ for _, tableSource := range q.tableSourcesFrom {+ tableColumns := tableSource.GetQuerySpanResult()++ for _, columnResult := range tableColumns {+ // Only include columns that are in our source columns set+ columnIncluded := false+ for sourceCol := range columnResult.SourceColumns {+ if _, exists := fullSourceColumns[sourceCol]; exists {+ columnIncluded = true+ break+ }+ }++ if columnIncluded {+ expandedResults = append(expandedResults, columnResult)+ }+ }+ }+ } else {+ // Keep non-asterisk results as-is+ expandedResults = append(expandedResults, result)+ }+ }++ return expandedResults}// expandTableReferencesToColumns expands table references to individual columns@@ -239,11 +279,6 @@ func (q *querySpanExtractor) addSourceColumn(col base.ColumnResource) {q.sourceColumns[col] = true}-// addPredicateColumn adds a column to the tracked predicate columns.-func (q *querySpanExtractor) addPredicateColumn(col base.ColumnResource) {- q.predicateColumns[col] = true-}-// findTableSchema locates a table or view and returns its metadata.func (q *querySpanExtractor) findTableSchema(db, schema, name string) (*model.TableMetadata, error) {// Get database metadatadiff --git a/backend/plugin/parser/trino/query_span_listener.go b/backend/plugin/parser/trino/query_span_listener.goindex 30e208d5b0..3387b9cb33 100644--- a/backend/plugin/parser/trino/query_span_listener.go+++ b/backend/plugin/parser/trino/query_span_listener.go@@ -56,8 +56,11 @@ func (l *trinoQuerySpanListener) EnterQuery(ctx *parser.QueryContext) {// Process the CTE queryqueryTree := namedQueryCtx.Query()if queryTree != nil {- // Use dedicated subquery processor- l.processSubquery(queryTree)+ // Process subquery to extract columns+ if err := l.extractor.extractPredicateColumnFromSubquery(queryTree); err != nil {+ l.err = err+ return+ }}// Add the CTE to our list@@ -94,20 +97,36 @@ func (l *trinoQuerySpanListener) EnterTableName(ctx *parser.TableNameContext) {}// Add table source to track where columns come from+ // Attempt to find the table in the schema first+ tableMeta, err := l.extractor.findTableSchema(db, schema, table)+ if err != nil {+ // We don't set l.err here because table references might be CTEs or subqueries++ // Create physical table without columns as fallback+ physicalTable := &base.PhysicalTable{+ Database: db,+ Schema: schema,+ Name: table,+ Columns: []string{}, // Empty columns+ }+ l.extractor.tableSourcesFrom = append(l.extractor.tableSourcesFrom, physicalTable)+ return+ }++ // Create physical table with column names from metadata+ var columnNames []string+ for _, col := range tableMeta.GetColumns() {+ columnNames = append(columnNames, col.Name)+ }+physicalTable := &base.PhysicalTable{Database: db,Schema: schema,Name: table,+ Columns: columnNames, // Populate with actual column names}l.extractor.tableSourcesFrom = append(l.extractor.tableSourcesFrom, physicalTable)- // Attempt to find the table in the schema- tableMeta, err := l.extractor.findTableSchema(db, schema, table)- if err != nil {- // We don't set l.err here because table references might be CTEs or subqueries- return- }-// Add each column from the table as a source columnfor _, col := range tableMeta.GetColumns() {colResource := base.ColumnResource{@@ -126,10 +145,10 @@ func (l *trinoQuerySpanListener) EnterSelectAll(_ *parser.SelectAllContext) {return}- // For SELECT *, we add a generic result entry+ // Mark that we encountered a SELECT * - we'll expand it later after all tables are processedresult := base.QuerySpanResult{Name: "*",- SourceColumns: l.extractor.sourceColumns,+ SourceColumns: make(base.SourceColumnSet), // Will be populated laterIsPlainField: false,SelectAsterisk: true,}@@ -143,26 +162,28 @@ func (l *trinoQuerySpanListener) EnterSelectSingle(ctx *parser.SelectSingleContereturn}- // Get column name and aliasvar resultName stringvar sourceColumns = make(base.SourceColumnSet)isPlainField := falseif ctx.Expression() != nil {expr := ctx.Expression()- // Check for column references++ // Check for simple column referencescolumnName := l.extractColumnName(expr)if columnName != "" {isPlainField = true- // Copy the source columns for this specific column+ // Find matching source columnsfor col := range l.extractor.sourceColumns {if col.Column == columnName {sourceColumns[col] = true}}+ } else {+ // For complex expressions, extract all column references+ l.extractAllColumnReferences(expr, sourceColumns)}- // For now, just use the expression text as the result nameresultName = expr.GetText()}@@ -171,12 +192,11 @@ func (l *trinoQuerySpanListener) EnterSelectSingle(ctx *parser.SelectSingleConteresultName = NormalizeTrinoIdentifier(ctx.As_column_alias().Column_alias().Identifier().GetText())}- // If still no name, use a placeholder+ // Generate name if none foundif resultName == "" {resultName = fmt.Sprintf("_col%d", len(l.results))}- // Create a result entry for this SELECT itemresult := base.QuerySpanResult{Name: resultName,SourceColumns: sourceColumns,@@ -186,15 +206,35 @@ func (l *trinoQuerySpanListener) EnterSelectSingle(ctx *parser.SelectSingleContel.results = append(l.results, result)}+// extractAllColumnReferences gathers all column references from a complex expression.+// This uses ANTLR tree traversal instead of regex patterns for better accuracy.+func (l *trinoQuerySpanListener) extractAllColumnReferences(expr parser.IExpressionContext, sourceColumns base.SourceColumnSet) {+ if expr == nil {+ return+ }++ // Use ANTLR tree traversal to find column references+ if err := l.extractor.extractPredicateColumnFromExpression(expr); err != nil {+ return // Best effort - don't fail on complex expressions+ }++ // Copy predicate columns found to result source columns+ for col := range l.extractor.predicateColumns {+ sourceColumns[col] = true+ }+}+// EnterQuerySpecification processes query specifications, including WHERE clausesfunc (l *trinoQuerySpanListener) EnterQuerySpecification(ctx *parser.QuerySpecificationContext) {if l.err != nil {return}- // Process WHERE clause if present+ // Process WHERE clause using consistent predicate extractionif ctx.GetWhere() != nil {- l.processPredicateExpressions(ctx.GetWhere())+ if err := l.extractor.extractPredicateColumnFromBooleanExpression(ctx.GetWhere()); err != nil {+ l.err = err+ }}}@@ -204,8 +244,10 @@ func (l *trinoQuerySpanListener) EnterJoinCriteria(ctx *parser.JoinCriteriaContereturn}- // Use the dedicated predicate join processing method- l.processPredicateJoin(ctx)+ // Use consistent predicate extraction following TSQL pattern+ if err := l.extractor.processJoinPredicate(ctx); err != nil {+ l.err = err+ }}// EnterUnnest processes UNNEST expressions, a Trino-specific feature.@@ -350,7 +392,6 @@ func (l *trinoQuerySpanListener) extractColumnName(expr parser.IExpressionContexreturn ""}- // Get the text representation of the expressionexprText := expr.GetText()if exprText == "" {return ""@@ -359,9 +400,7 @@ func (l *trinoQuerySpanListener) extractColumnName(expr parser.IExpressionContex// Handle qualified column names (e.g., table.column)parts := strings.Split(exprText, ".")if len(parts) > 1 {- // Return the last part which should be the column namecolumnName := parts[len(parts)-1]-// Check if this matches a known columnfor col := range l.extractor.sourceColumns {if col.Column == columnName {@@ -377,6 +416,5 @@ func (l *trinoQuerySpanListener) extractColumnName(expr parser.IExpressionContex}}- // Not a simple column referencereturn ""}diff --git a/backend/plugin/parser/trino/query_span_predicate.go b/backend/plugin/parser/trino/query_span_predicate.gonew file mode 100644index 0000000000..594904c126--- /dev/null+++ b/backend/plugin/parser/trino/query_span_predicate.go@@ -0,0 +1,157 @@+package trino++import (+ "github.com/antlr4-go/antlr/v4"+ parser "github.com/bytebase/trino-parser"+ "github.com/pkg/errors"++ "github.com/bytebase/bytebase/backend/plugin/parser/base"+)++// extractPredicateColumnFromBooleanExpression extracts predicate columns from boolean expressions.+// This follows the TSQL pattern for consistent predicate extraction.+func (q *querySpanExtractor) extractPredicateColumnFromBooleanExpression(+ ctx parser.IBooleanExpressionContext,+) error {+ if ctx == nil {+ return nil+ }++ // Use generic tree walking to find all expressions+ return q.extractPredicateColumnFromExpression(ctx)+}++// extractPredicateColumnFromExpression recursively walks the expression tree to find column references.+// This is the core method following TSQL's recursive pattern but adapted for Trino.+func (q *querySpanExtractor) extractPredicateColumnFromExpression(+ ctx antlr.ParserRuleContext,+) error {+ if ctx == nil {+ return nil+ }++ switch typedCtx := ctx.(type) {+ case parser.IQualifiedNameContext:+ // Qualified name that might be a column reference+ col := q.extractColumnFromQualifiedName(typedCtx)+ if col != nil {+ q.predicateColumns[*col] = true+ }++ case parser.IQueryContext:+ // Subquery in expression+ if err := q.extractPredicateColumnFromSubquery(typedCtx); err != nil {+ return err+ }+ }++ // Recursively process all child nodes following TSQL pattern+ for _, child := range ctx.GetChildren() {+ if childCtx, ok := child.(antlr.ParserRuleContext); ok {+ if err := q.extractPredicateColumnFromExpression(childCtx); err != nil {+ return err+ }+ }+ }++ return nil+}++// extractPredicateColumnFromSubquery processes subqueries within predicates.+// This follows the TSQL pattern for subquery handling.+func (q *querySpanExtractor) extractPredicateColumnFromSubquery(+ ctx parser.IQueryContext,+) error {+ if ctx == nil {+ return nil+ }++ // Get subquery text for processing+ subquery := ctx.GetParser().GetTokenStream().GetTextFromRuleContext(ctx)++ // Create new extractor for subquery, following TSQL pattern+ newExtractor := newQuerySpanExtractor(q.defaultDatabase, q.defaultSchema, q.gCtx, q.ignoreCaseSensitive)+ newExtractor.ctes = q.ctes // Preserve CTE context++ span, err := newExtractor.getQuerySpan(q.ctx, subquery)+ if err != nil {+ return errors.Wrapf(err, "failed to get query span for subquery: %s", subquery)+ }++ // Merge predicate columns from subquery+ q.predicateColumns, _ = base.MergeSourceColumnSet(q.predicateColumns, span.PredicateColumns)++ // Add result columns as predicates (they're used in the outer predicate context)+ for _, result := range span.Results {+ q.predicateColumns, _ = base.MergeSourceColumnSet(q.predicateColumns, result.SourceColumns)+ }++ return nil+}++// extractColumnFromQualifiedName extracts a column resource from a qualified name context.+func (q *querySpanExtractor) extractColumnFromQualifiedName(ctx parser.IQualifiedNameContext) *base.ColumnResource {+ if ctx == nil {+ return nil+ }++ db, schema, table := ExtractDatabaseSchemaName(ctx, q.defaultDatabase, q.defaultSchema)++ // If we have table qualification, it's likely a column reference+ if table != "" {+ parts := ctx.AllIdentifier()+ if len(parts) > 0 {+ columnName := NormalizeTrinoIdentifier(parts[len(parts)-1].GetText())++ // Try to match with source columns+ for col := range q.sourceColumns {+ if col.Column == columnName {+ // Check table match if specified+ if col.Table == "" || col.Table == table {+ return &col+ }+ }+ }++ // Create column resource if not found in source columns+ return &base.ColumnResource{+ Database: db,+ Schema: schema,+ Table: table,+ Column: columnName,+ }+ }+ }++ return nil+}++// processJoinPredicate extracts predicate columns from JOIN conditions.+// This follows the TSQL pattern for join predicate handling.+func (q *querySpanExtractor) processJoinPredicate(ctx parser.IJoinCriteriaContext) error {+ if ctx == nil {+ return nil+ }++ // Process ON clause predicates+ if ctx.ON_() != nil && ctx.BooleanExpression() != nil {+ if err := q.extractPredicateColumnFromBooleanExpression(ctx.BooleanExpression()); err != nil {+ return err+ }+ }++ // Process USING clause - columns in USING are predicates by definition+ if ctx.USING_() != nil {+ for _, ident := range ctx.AllIdentifier() {+ columnName := NormalizeTrinoIdentifier(ident.GetText())+ // Find matching source columns and add as predicates+ for col := range q.sourceColumns {+ if col.Column == columnName {+ q.predicateColumns[col] = true+ }+ }+ }+ }++ return nil+}diff --git a/backend/plugin/parser/trino/query_span_test.go b/backend/plugin/parser/trino/query_span_test.goindex 92d00c0127..4b3eabcf4e 100644--- a/backend/plugin/parser/trino/query_span_test.go+++ b/backend/plugin/parser/trino/query_span_test.go@@ -131,6 +131,7 @@ func TestGetQuerySpanFromYAML(t *testing.T) {"test-data/query-span/case-sensitivity.yaml","test-data/query-span/join.yaml","test-data/query-span/trino-specific.yaml",+ "test-data/query-span/masking.yaml",})diff --git a/backend/plugin/parser/trino/test-data/query-span/masking.yaml b/backend/plugin/parser/trino/test-data/query-span/masking.yamlnew file mode 100644index 0000000000..60a72fb05e--- /dev/null+++ b/backend/plugin/parser/trino/test-data/query-span/masking.yaml@@ -0,0 +1,167 @@+- description: Basic SELECT masking+ statement: |+ SELECT+ name,+ email,+ phone+ FROM+ users+ WHERE+ created_at > '2020-01-01'+ defaultDatabase: mydb+ metadata: '{"name":"mydb","schemas":[{"name":"public","tables":[{"name":"users","columns":[{"name":"name","type":"varchar"},{"name":"email","type":"varchar"},{"name":"phone","type":"varchar"},{"name":"created_at","type":"timestamp"}]}]}]}'+ querySpan:+ type:+ querytype: 1+ results:+ - name: name+ sourceColumns:+ "mydb.public.users.name": true+ isPlainField: true+ - name: email+ sourceColumns:+ "mydb.public.users.email": true+ isPlainField: true+ - name: phone+ sourceColumns:+ "mydb.public.users.phone": true+ isPlainField: true+ sourceColumns:+ "mydb.public.users.name": true+ "mydb.public.users.email": true+ "mydb.public.users.phone": true+ "mydb.public.users.created_at": true+ predicateColumns:+ "mydb.public.users.created_at": true++- description: Complex data types masking+ statement: |+ SELECT+ user_id,+ profile['address'] as address,+ contact_info.phone as phone,+ permissions[1] as first_permission+ FROM+ user_profiles+ WHERE+ profile['status'] = 'active'+ defaultDatabase: mydb+ metadata: '{"name":"mydb","schemas":[{"name":"public","tables":[{"name":"user_profiles","columns":[{"name":"user_id","type":"integer"},{"name":"profile","type":"map(varchar,varchar)"},{"name":"contact_info","type":"row(phone varchar)"},{"name":"permissions","type":"array(varchar)"}]}]}]}'+ querySpan:+ type:+ querytype: 1+ results:+ - name: user_id+ sourceColumns:+ "mydb.public.user_profiles.user_id": true+ isPlainField: true+ - name: address+ sourceColumns:+ "mydb.public.user_profiles.profile": true+ isPlainField: false+ - name: phone+ sourceColumns:+ "mydb.public.user_profiles.contact_info": true+ isPlainField: false+ - name: first_permission+ sourceColumns:+ "mydb.public.user_profiles.permissions": true+ isPlainField: false+ sourceColumns:+ "mydb.public.user_profiles.user_id": true+ "mydb.public.user_profiles.profile": true+ "mydb.public.user_profiles.contact_info": true+ "mydb.public.user_profiles.permissions": true+ predicateColumns:+ "mydb.public.user_profiles.profile": true++- description: Join masking+ statement: |+ SELECT+ u.name,+ u.email,+ o.order_id,+ o.total+ FROM+ users u+ JOIN+ orders o+ ON+ u.user_id = o.user_id+ WHERE+ o.status = 'completed'+ AND u.is_verified = true+ defaultDatabase: mydb+ metadata: '{"name":"mydb","schemas":[{"name":"public","tables":[{"name":"users","columns":[{"name":"name","type":"varchar"},{"name":"email","type":"varchar"},{"name":"user_id","type":"integer"},{"name":"is_verified","type":"boolean"}]},{"name":"orders","columns":[{"name":"order_id","type":"integer"},{"name":"total","type":"decimal"},{"name":"user_id","type":"integer"},{"name":"status","type":"varchar"}]}]}]}'+ querySpan:+ type:+ querytype: 1+ results:+ - name: name+ sourceColumns:+ "mydb.public.users.name": true+ isPlainField: true+ - name: email+ sourceColumns:+ "mydb.public.users.email": true+ isPlainField: true+ - name: order_id+ sourceColumns:+ "mydb.public.orders.order_id": true+ isPlainField: true+ - name: total+ sourceColumns:+ "mydb.public.orders.total": true+ isPlainField: true+ sourceColumns:+ "mydb.public.users.name": true+ "mydb.public.users.email": true+ "mydb.public.users.user_id": true+ "mydb.public.users.is_verified": true+ "mydb.public.orders.order_id": true+ "mydb.public.orders.total": true+ "mydb.public.orders.user_id": true+ "mydb.public.orders.status": true+ predicateColumns:+ "mydb.public.users.user_id": true+ "mydb.public.orders.user_id": true+ "mydb.public.orders.status": true+ "mydb.public.users.is_verified": true++- description: Array function masking+ statement: |+ SELECT+ user_id,+ name,+ array_contains(roles, 'admin') as is_admin+ FROM+ users+ WHERE+ cardinality(roles) > 0+ AND element_at(permissions, 'edit') = true+ defaultDatabase: mydb+ metadata: '{"name":"mydb","schemas":[{"name":"public","tables":[{"name":"users","columns":[{"name":"user_id","type":"integer"},{"name":"name","type":"varchar"},{"name":"roles","type":"array(varchar)"},{"name":"permissions","type":"map(varchar,boolean)"}]}]}]}'+ querySpan:+ type:+ querytype: 1+ results:+ - name: user_id+ sourceColumns:+ "mydb.public.users.user_id": true+ isPlainField: true+ - name: name+ sourceColumns:+ "mydb.public.users.name": true+ isPlainField: true+ - name: is_admin+ sourceColumns:+ "mydb.public.users.roles": true+ isPlainField: false+ sourceColumns:+ "mydb.public.users.user_id": true+ "mydb.public.users.name": true+ "mydb.public.users.roles": true+ "mydb.public.users.permissions": true+ predicateColumns:+ "mydb.public.users.roles": true+ "mydb.public.users.permissions": true\ No newline at end of file