Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
fix(span): table asterisk in target field and from contains join for pg (#10712)
h3n4l344019e35200
diff --git a/backend/plugin/parser/pg/query_span_extractor.go b/backend/plugin/parser/pg/query_span_extractor.goindex 0c4c9d19a7..d622b8f20a 100644--- a/backend/plugin/parser/pg/query_span_extractor.go+++ b/backend/plugin/parser/pg/query_span_extractor.go@@ -239,7 +239,7 @@ func (q *querySpanExtractor) extractTableSourceFromSelect(node *pgquery.Node_Sel}leftQuerySpanResult, rightQuerySpanResult := leftSpanResults.GetQuerySpanResult(), rightSpanResults.GetQuerySpanResult()if len(leftQuerySpanResult) != len(rightQuerySpanResult) {- return nil, errors.Wrapf(err, "left select has %d columns, but right select has %d columns", len(leftQuerySpanResult), len(leftQuerySpanResult))+ return nil, errors.Errorf("left select has %d columns, but right select has %d columns", len(leftQuerySpanResult), len(rightQuerySpanResult))}var result []base.QuerySpanResultfor i, leftSpanResult := range leftQuerySpanResult {@@ -286,7 +286,7 @@ func (q *querySpanExtractor) extractTableSourceFromSelect(node *pgquery.Node_Selreturn nil, errors.Wrapf(err, "failed to convert column ref to column name def: %+v", fieldNode.ColumnRef.Fields)}if columnRef.ColumnName == "*" {- // SELECT * FROM ... case+ // SELECT [x].* FROM ... caseif columnRef.Table.Name == "" {var columns []base.QuerySpanResultfor _, tableSource := range fromFieldList {@@ -295,14 +295,30 @@ func (q *querySpanExtractor) extractTableSourceFromSelect(node *pgquery.Node_Selresult.Columns = append(result.Columns, columns...)} else {schemaName, tableName, _ := extractSchemaTableColumnName(columnRef)+ find := falsefor _, tableSource := range fromFieldList {if schemaName == "" || schemaName == tableSource.GetSchemaName() {if tableName == tableSource.GetTableName() {+ find = trueresult.Columns = append(result.Columns, tableSource.GetQuerySpanResult()...)break}}}+ if !find {+ sources, ok := q.getAllTableColumnSources(schemaName, tableName)+ if ok {+ result.Columns = append(result.Columns, sources...)+ find = true+ }+ }+ if !find {+ return nil, &parsererror.ResourceNotFoundError{+ Err: errors.New("failed to find table to calculate asterisk"),+ Schema: &schemaName,+ Table: &tableName,+ }+ }}} else {sourceColumnSet, err := q.extractSourceColumnSetFromExpressionNode(resTarget.ResTarget.Val)@@ -346,10 +362,12 @@ func (q *querySpanExtractor) extractTableSourceFromJoin(node *pgquery.Node_JoinEif err != nil {return nil, errors.Wrapf(err, "failed to extract span result from left join: %+v", node.JoinExpr.Larg)}+ q.tableSourcesFrom = append(q.tableSourcesFrom, leftTableSource)rightTableSource, err := q.extractTableSourceFromNode(node.JoinExpr.Rarg)if err != nil {return nil, errors.Wrapf(err, "failed to extract span result from right join: %+v", node.JoinExpr.Rarg)}+ q.tableSourcesFrom = append(q.tableSourcesFrom, rightTableSource)return q.mergeJoinTableSource(node, leftTableSource, rightTableSource)}@@ -634,7 +652,18 @@ func (q *querySpanExtractor) extractSourceColumnSetFromExpressionNode(node *pgquif err != nil {return base.SourceColumnSet{}, err}- return q.getFieldColumnSource(extractSchemaTableColumnName(columnNameDef)), nil+ schema, table, column := extractSchemaTableColumnName(columnNameDef)+ sources, ok := q.getFieldColumnSource(schema, table, column)+ if !ok {+ return base.SourceColumnSet{}, &parsererror.ResourceNotFoundError{+ Err: errors.New("cannot find the column ref"),+ Database: &q.connectedDB,+ Schema: &schema,+ Table: &table,+ Column: &column,+ }+ }+ return sources, nilcase *pgquery.Node_AExpr:var nodeList []*pgquery.NodenodeList = append(nodeList, node.AExpr.Lexpr)@@ -728,7 +757,50 @@ func (q *querySpanExtractor) extractSourceColumnSetFromExpressionNodeList(list [return result, nil}-func (q *querySpanExtractor) getFieldColumnSource(schemaName, tableName, fieldName string) base.SourceColumnSet {+func (q *querySpanExtractor) getAllTableColumnSources(schemaName, tableName string) ([]base.QuerySpanResult, bool) {+ findInTableSource := func(tableSource base.TableSource) ([]base.QuerySpanResult, bool) {+ if schemaName != "" && schemaName != tableSource.GetSchemaName() {+ return nil, false+ }+ if tableName != "" && tableName != tableSource.GetTableName() {+ return nil, false+ }+ // If the table name is empty, we should check if there are ambiguous fields,+ // but we delegate this responsibility to the db-server, we do the fail-open strategy here.++ return tableSource.GetQuerySpanResult(), true+ }++ // One sub-query may have multi-outer schemas and the multi-outer schemas can use the same name, such as:+ //+ // select (+ // select (+ // select max(a) > x1.a from t+ // )+ // from t1 as x1+ // limit 1+ // )+ // from t as x1;+ //+ // This query has two tables can be called `x1`, and the expression x1.a uses the closer x1 table.+ // This is the reason we loop the slice in reversed order.++ for i := len(q.outerTableSources) - 1; i >= 0; i-- {+ if sourceColumnSet, ok := findInTableSource(q.outerTableSources[i]); ok {+ return sourceColumnSet, true+ }+ }++ for _, tableSource := range q.tableSourcesFrom {+ if sourceColumnSet, ok := findInTableSource(tableSource); ok {+ return sourceColumnSet, true+ }+ }++ return []base.QuerySpanResult{}, false+}++func (q *querySpanExtractor) getFieldColumnSource(schemaName, tableName, fieldName string) (base.SourceColumnSet, bool) {findInTableSource := func(tableSource base.TableSource) (base.SourceColumnSet, bool) {if schemaName != "" && schemaName != tableSource.GetSchemaName() {return nil, false@@ -764,17 +836,17 @@ func (q *querySpanExtractor) getFieldColumnSource(schemaName, tableName, fieldNafor i := len(q.outerTableSources) - 1; i >= 0; i-- {if sourceColumnSet, ok := findInTableSource(q.outerTableSources[i]); ok {- return sourceColumnSet+ return sourceColumnSet, true}}for _, tableSource := range q.tableSourcesFrom {if sourceColumnSet, ok := findInTableSource(tableSource); ok {- return sourceColumnSet+ return sourceColumnSet, true}}- return base.SourceColumnSet{}+ return base.SourceColumnSet{}, false}func (q *querySpanExtractor) findTableSchema(schemaName string, tableName string) (base.TableSource, error) {diff --git a/backend/plugin/parser/pg/test-data/query_span.yaml b/backend/plugin/parser/pg/test-data/query_span.yamlindex 9feda4d08a..e9ef66988e 100644--- a/backend/plugin/parser/pg/test-data/query_span.yaml+++ b/backend/plugin/parser/pg/test-data/query_span.yaml@@ -527,6 +527,78 @@schema: publictable: tcolumn: ""+- description: Test for SELECT partial FROM JOIN clause+ statement: SELECT t1.*, t2.c, 0 FROM t1 JOIN t2 ON 1 = 1;+ connectedDatabase: db+ metadata: |-+ {+ "name": "db",+ "schemas": [+ {+ "name": "public",+ "tables": [+ {+ "name": "t1",+ "columns": [+ {+ "name": "a"+ },+ {+ "name": "b"+ }+ ]+ },+ {+ "name": "t2",+ "columns": [+ {+ "name": "c"+ },+ {+ "name": "d"+ }+ ]+ }+ ]+ }+ ]+ }+ querySpan:+ results:+ - name: a+ sourcecolumns:+ - server: ""+ database: db+ schema: public+ table: t1+ column: a+ - name: b+ sourcecolumns:+ - server: ""+ database: db+ schema: public+ table: t1+ column: b+ - name: c+ sourcecolumns:+ - server: ""+ database: db+ schema: public+ table: t2+ column: c+ - name: ?column?+ sourcecolumns: []+ sourcecolumns:+ - server: ""+ database: db+ schema: public+ table: t1+ column: ""+ - server: ""+ database: db+ schema: public+ table: t2+ column: ""- description: Test for JOIN with USING clausestatement: SELECT * FROM t AS t1 JOIN t AS t2 USING(a);connectedDatabase: dbdiff --git a/backend/plugin/parser/tidb/query_span_extractor.go b/backend/plugin/parser/tidb/query_span_extractor.goindex 05c9c1c899..0a7fb2d1bf 100644--- a/backend/plugin/parser/tidb/query_span_extractor.go+++ b/backend/plugin/parser/tidb/query_span_extractor.go@@ -362,10 +362,26 @@ func (q *querySpanExtractor) extractSelect(node *tidbast.SelectStmt) (base.Tablefor _, tableSource := range fromFieldList {sameDatabase := (field.WildCard.Schema.O == tableSource.GetDatabaseName() || (field.WildCard.Schema.O == "" && tableSource.GetDatabaseName() == q.connectedDB))sameTable := field.WildCard.Table.O == tableSource.GetTableName()+ find := falseif sameDatabase && sameTable {result.Columns = append(result.Columns, tableSource.GetQuerySpanResult()...)+ find = truebreak}+ if !find {+ sources, ok := q.getAllTableColumnSources(field.WildCard.Schema.O, field.WildCard.Table.O)+ if ok {+ result.Columns = append(result.Columns, sources...)+ find = true+ }+ }+ if !find {+ return nil, &parsererror.ResourceNotFoundError{+ Err: errors.New("failed to find table to calculate asterisk"),+ Database: &field.WildCard.Schema.O,+ Table: &field.WildCard.Table.O,+ }+ }}}} else {@@ -404,7 +420,17 @@ func (q *querySpanExtractor) extractSourceColumnSetFromExpression(in tidbast.Expswitch node := in.(type) {case *tidbast.ColumnNameExpr:- return q.getFieldColumnSource(node.Name.Schema.O, node.Name.Table.O, node.Name.Name.O), nil+ database, table, column := node.Name.Schema.O, node.Name.Table.O, node.Name.Name.O+ sources, ok := q.getFieldColumnSource(database, table, column)+ if !ok {+ return base.SourceColumnSet{}, &parsererror.ResourceNotFoundError{+ Err: errors.New("cannot find the column ref"),+ Database: &database,+ Table: &table,+ Column: &column,+ }+ }+ return sources, nilcase *tidbast.BinaryOperationExpr:return q.extractSourceColumnSetFromExpressionList([]tidbast.ExprNode{node.L, node.R})case *tidbast.UnaryOperationExpr:@@ -495,7 +521,54 @@ func (q *querySpanExtractor) extractSourceColumnSetFromExpression(in tidbast.Expreturn base.SourceColumnSet{}, nil}-func (q *querySpanExtractor) getFieldColumnSource(databaseName, tableName, fieldName string) base.SourceColumnSet {+func (q *querySpanExtractor) getAllTableColumnSources(databaseName, tableName string) ([]base.QuerySpanResult, bool) {+ findInTableSource := func(tableSource base.TableSource) ([]base.QuerySpanResult, bool) {+ if databaseName != "" && databaseName != tableSource.GetDatabaseName() {+ return nil, false+ }+ if databaseName == "" && tableSource.GetDatabaseName() != "" && tableSource.GetDatabaseName() != q.connectedDB {+ return nil, false+ }+ if tableName != "" && tableName != tableSource.GetTableName() {+ return nil, false+ }+ // If the table name is empty, we should check if there are ambiguous fields,+ // but we delegate this responsibility to the db-server, we do the fail-open strategy here.++ return tableSource.GetQuerySpanResult(), true+ }++ // One sub-query may have multi-outer schemas and the multi-outer schemas can use the same name, such as:+ //+ // select (+ // select (+ // select max(a) > x1.a from t+ // )+ // from t1 as x1+ // limit 1+ // )+ // from t as x1;+ //+ // This query has two tables can be called `x1`, and the expression x1.a uses the closer x1 table.+ // This is the reason we loop the slice in reversed order.++ for i := len(q.outerTableSources) - 1; i >= 0; i-- {+ tableSource := q.outerTableSources[i]+ if sourceColumnSet, ok := findInTableSource(tableSource); ok {+ return sourceColumnSet, true+ }+ }++ for _, tableSource := range q.tableSourcesFrom {+ if sourceColumnSet, ok := findInTableSource(tableSource); ok {+ return sourceColumnSet, true+ }+ }++ return nil, false+}++func (q *querySpanExtractor) getFieldColumnSource(databaseName, tableName, fieldName string) (base.SourceColumnSet, bool) {findInTableSource := func(tableSource base.TableSource) (base.SourceColumnSet, bool) {if databaseName != "" && databaseName != tableSource.GetDatabaseName() {return nil, false@@ -535,17 +608,17 @@ func (q *querySpanExtractor) getFieldColumnSource(databaseName, tableName, fieldfor i := len(q.outerTableSources) - 1; i >= 0; i-- {tableSource := q.outerTableSources[i]if sourceColumnSet, ok := findInTableSource(tableSource); ok {- return sourceColumnSet+ return sourceColumnSet, true}}for _, tableSource := range q.tableSourcesFrom {if sourceColumnSet, ok := findInTableSource(tableSource); ok {- return sourceColumnSet+ return sourceColumnSet, true}}- return base.SourceColumnSet{}+ return base.SourceColumnSet{}, false}func (q *querySpanExtractor) extractJoin(node *tidbast.Join) (base.TableSource, error) {@@ -557,10 +630,13 @@ func (q *querySpanExtractor) extractJoin(node *tidbast.Join) (base.TableSource,if err != nil {return nil, errors.Wrap(err, "failed to extract table source from left table")}+ q.tableSourcesFrom = append(q.tableSourcesFrom, leftTableSource)rightTableSource, err := q.extractTableSourceFromNode(node.Right)if err != nil {return nil, errors.Wrap(err, "failed to extract table source from right table")}+ q.tableSourcesFrom = append(q.tableSourcesFrom, rightTableSource)+ q.tableSourcesFrom = append(q.tableSourcesFrom, rightTableSource)return q.mergeJoinTableSource(node, leftTableSource, rightTableSource)}diff --git a/backend/plugin/parser/tidb/test-data/query_span.yaml b/backend/plugin/parser/tidb/test-data/query_span.yamlindex 8ba02bb688..ce00231dd3 100644--- a/backend/plugin/parser/tidb/test-data/query_span.yaml+++ b/backend/plugin/parser/tidb/test-data/query_span.yaml@@ -527,6 +527,78 @@schema: ""table: tcolumn: ""+- description: Test for SELECT partial FROM JOIN clause+ statement: SELECT t1.*, t2.c, 0 FROM t1 JOIN t2 ON 1 = 1;+ connectedDatabase: db+ metadata: |-+ {+ "name": "db",+ "schemas": [+ {+ "name": "",+ "tables": [+ {+ "name": "t1",+ "columns": [+ {+ "name": "a"+ },+ {+ "name": "b"+ }+ ]+ },+ {+ "name": "t2",+ "columns": [+ {+ "name": "c"+ },+ {+ "name": "d"+ }+ ]+ }+ ]+ }+ ]+ }+ querySpan:+ results:+ - name: a+ sourcecolumns:+ - server: ""+ database: db+ schema: ""+ table: t1+ column: a+ - name: b+ sourcecolumns:+ - server: ""+ database: db+ schema: ""+ table: t1+ column: b+ - name: c+ sourcecolumns:+ - server: ""+ database: db+ schema: ""+ table: t2+ column: c+ - name: "0"+ sourcecolumns: []+ sourcecolumns:+ - server: ""+ database: db+ schema: ""+ table: t1+ column: ""+ - server: ""+ database: db+ schema: ""+ table: t2+ column: ""- description: Test for JOIN with USING clausestatement: SELECT * FROM t AS t1 JOIN t AS t2 USING(a);connectedDatabase: db