Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

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.go
index 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.QuerySpanResult
for i, leftSpanResult := range leftQuerySpanResult {
@@ -286,7 +286,7 @@ func (q *querySpanExtractor) extractTableSourceFromSelect(node *pgquery.Node_Sel
return 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 ... case
if columnRef.Table.Name == "" {
var columns []base.QuerySpanResult
for _, tableSource := range fromFieldList {
@@ -295,14 +295,30 @@ func (q *querySpanExtractor) extractTableSourceFromSelect(node *pgquery.Node_Sel
result.Columns = append(result.Columns, columns...)
} else {
schemaName, tableName, _ := extractSchemaTableColumnName(columnRef)
+ find := false
for _, tableSource := range fromFieldList {
if schemaName == "" || schemaName == tableSource.GetSchemaName() {
if tableName == tableSource.GetTableName() {
+ find = true
result.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_JoinE
if 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 *pgqu
if 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, nil
case *pgquery.Node_AExpr:
var nodeList []*pgquery.Node
nodeList = 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, fieldNa
for 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.yaml
index 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: public
table: t
column: ""
+- 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 clause
statement: SELECT * FROM t AS t1 JOIN t AS t2 USING(a);
connectedDatabase: db
diff --git a/backend/plugin/parser/tidb/query_span_extractor.go b/backend/plugin/parser/tidb/query_span_extractor.go
index 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.Table
for _, 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 := false
if sameDatabase && sameTable {
result.Columns = append(result.Columns, tableSource.GetQuerySpanResult()...)
+ find = true
break
}
+ 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.Exp
switch 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, nil
case *tidbast.BinaryOperationExpr:
return q.extractSourceColumnSetFromExpressionList([]tidbast.ExprNode{node.L, node.R})
case *tidbast.UnaryOperationExpr:
@@ -495,7 +521,54 @@ func (q *querySpanExtractor) extractSourceColumnSetFromExpression(in tidbast.Exp
return 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, field
for 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.yaml
index 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: t
column: ""
+- 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 clause
statement: SELECT * FROM t AS t1 JOIN t AS t2 USING(a);
connectedDatabase: db