Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(query-span): handle bigquery query span table wild in projection (#14227)
h3n4le464f4b5c7eb
diff --git a/backend/plugin/parser/bigquery/query_span_extractor.go b/backend/plugin/parser/bigquery/query_span_extractor.goindex 11701548a2..50b5e83fbc 100644--- a/backend/plugin/parser/bigquery/query_span_extractor.go+++ b/backend/plugin/parser/bigquery/query_span_extractor.go@@ -298,7 +298,6 @@ func (q *querySpanExtractor) extractTableSourceFromQueryPrimary(queryPrimary parreturn tableSource, nil}- // TODO(zp): handle parenthesized query.return nil, nil}@@ -315,11 +314,18 @@ func (q *querySpanExtractor) extractTableSourceFromSelect(selectCtx parser.ISeleitemList := selectCtx.Select_clause().Select_list().AllSelect_list_item()for _, item := range itemList {- // TODO(zp): handle other select item.- if item.Select_column_star() != nil {+ switch {+ case item.Select_column_star() != nil:resultFields = append(resultFields, fromFields...)- }- if v := item.Select_column_expr(); v != nil {+ case item.Select_column_dot_star() != nil:+ v := item.Select_column_dot_star()+ wildFields, err := q.extractWildFromExpr(v.Expression_higher_prec_than_and())+ if err != nil {+ return nil, err+ }+ resultFields = append(resultFields, wildFields...)+ case item.Select_column_expr() != nil:+ v := item.Select_column_expr()var expression parser.IExpressionContextif v.Expression() != nil {expression = v.Expression()@@ -454,6 +460,138 @@ func (q *querySpanExtractor) extractSourceColumnSetFromExpr(ctx antlr.ParserRulereturn name, baseSet, nil}+func (q *querySpanExtractor) extractWildFromExpr(ctx antlr.ParserRuleContext) ([]base.QuerySpanResult, error) {+ if ctx == nil {+ return []base.QuerySpanResult{}, nil+ }++ // BigQuery support project the field from json, for example, SELECT a.b.c FROM ..., the AST looks like:+ // /+ // └── expression+ // └── expression_higher_prec_than_and+ // ├── expression_higher_prec_than_and+ // │ ├── expression_higher_prec_than_and+ // │ │ ├── expression_higher_prec_than_and+ // │ │ ├── DOT_SYMBOL+ // │ │ └── identifier(a)+ // │ ├── DOT_SYMBOL+ // │ └── identifier(b)+ // ├── DOT_SYMBOL+ // └── identifier(c)+ // We use DFS algorithm here to find the tallest [expression_higher_prec_than_and DOT_SYMBOL identifier] subtree and+ // treat it as identifier.+ switch ctx := ctx.(type) {+ // TODO(zp): handle subquery+ case *parser.Parenthesized_queryContext:+ subqueryExtractor := &querySpanExtractor{+ ctx: q.ctx,+ defaultDatabase: q.defaultDatabase,+ gCtx: q.gCtx,+ ctes: q.ctes,+ outerTableSources: append(q.outerTableSources, q.tableSourceFrom...),+ tableSourceFrom: []base.TableSource{},+ }+ tableSource, err := subqueryExtractor.extractTableSourceFromParenthesizedQuery(ctx)+ if err != nil {+ return nil, err+ }+ spanResult := tableSource.GetQuerySpanResult()+ return spanResult, nil+ case *parser.Expression_higher_prec_than_andContext:+ possibleColumnResources := getPossibleColumnResources(ctx)+ for _, columnResources := range possibleColumnResources {+ l := len(columnResources)+ if l == 1 {+ // a.*, a can be the table name or the field name.+ results, ok := q.getAllTableColumnSources("", columnResources[0])+ if !ok {+ results, err := q.getFieldColumnSource("", "", columnResources[0])+ if err != nil {+ return nil, err+ }+ return []base.QuerySpanResult{+ {+ Name: columnResources[0],+ SourceColumns: results,+ },+ }, nil+ }+ return results, nil+ }+ if l >= 2 {+ // a.b.*, can be resolved as+ // 1. a is the table name, b is the field name.+ // 2. a is the field name, b is the field name.+ results, err := q.getFieldColumnSource("", columnResources[0], columnResources[1])+ if err != nil {+ results, err := q.getFieldColumnSource("", "", columnResources[0])+ if err != nil {+ return nil, err+ }+ return []base.QuerySpanResult{+ {+ Name: columnResources[0],+ SourceColumns: results,+ },+ }, nil+ }+ return []base.QuerySpanResult{+ {+ Name: columnResources[1],+ SourceColumns: results,+ },+ }, nil+ }+ }+ return nil, nil+ default:+ return nil, errors.Errorf("unsupported type in wild expr: %T", ctx)+ }+}++func (q *querySpanExtractor) getAllTableColumnSources(datasetName, tableName string) ([]base.QuerySpanResult, bool) {+ findInTableSource := func(tableSource base.TableSource) ([]base.QuerySpanResult, bool) {+ if datasetName != "" && !strings.EqualFold(datasetName, tableSource.GetDatabaseName()) {+ return nil, false+ }+ if tableName != "" && !strings.EqualFold(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 querySpanResult, ok := findInTableSource(q.outerTableSources[i]); ok {+ return querySpanResult, true+ }+ }++ for i := len(q.tableSourceFrom) - 1; i >= 0; i-- {+ if querySpanResult, ok := findInTableSource(q.tableSourceFrom[i]); ok {+ return querySpanResult, true+ }+ }++ return nil, false+}+func (q *querySpanExtractor) getFieldColumnSource(databaseName, tableName, fieldName string) (base.SourceColumnSet, error) {// Bigquery column name is case-insensitive.findInTableSource := func(tableSource base.TableSource) (base.SourceColumnSet, bool) {diff --git a/backend/plugin/parser/bigquery/test-data/query-span/standard.yaml b/backend/plugin/parser/bigquery/test-data/query-span/standard.yamlindex 2438991047..f539df1929 100644--- a/backend/plugin/parser/bigquery/test-data/query-span/standard.yaml+++ b/backend/plugin/parser/bigquery/test-data/query-span/standard.yaml@@ -544,6 +544,54 @@schema: ""table: peoplecolumn: ""+- description: Wild projecter+ statement: SELECT s.* FROM people s;+ defaultDatabase: ds1+ metadata: |-+ {+ "name": "ds1",+ "schemas": [+ {+ "name": "",+ "tables": [+ {+ "name": "people",+ "columns": [+ {+ "name": "ID"+ },+ {+ "name": "NAME"+ }+ ]+ }+ ]+ }+ ]+ }+ querySpan:+ type: 0+ results:+ - name: ID+ sourcecolumns:+ - server: ""+ database: ds1+ schema: ""+ table: people+ column: ID+ - name: NAME+ sourcecolumns:+ - server: ""+ database: ds1+ schema: ""+ table: people+ column: NAME+ sourcecolumns:+ - server: ""+ database: ds1+ schema: ""+ table: people+ column: ""- description: Simple projecterstatement: SELECT ID, NAME FROM people;defaultDatabase: ds1diff --git a/go.mod b/go.modindex d0adaad734..f6db5ef150 100644--- a/go.mod+++ b/go.mod@@ -23,7 +23,7 @@ require (github.com/beltran/gohive v1.7.0github.com/blang/semver/v4 v4.0.0github.com/buger/jsonparser v1.1.1- github.com/bytebase/google-sql-parser v0.0.0-20241023112038-76da71baef63+ github.com/bytebase/google-sql-parser v0.0.0-20241028100034-870171a587edgithub.com/bytebase/mysql-parser v0.0.0-20240810145851-ab2c11629c24github.com/bytebase/plsql-parser v0.0.0-20240929073008-6b57c2e2525dgithub.com/bytebase/postgresql-parser v0.0.0-20241008085234-a95eacac994adiff --git a/go.sum b/go.sumindex 6fbd90f9a0..a90c0ac844 100644--- a/go.sum+++ b/go.sum@@ -817,8 +817,8 @@ github.com/bytebase/go-obo v0.0.0-20231026081615-705a7fffbfd2 h1:nEHZi8S7PHT4GxPgithub.com/bytebase/go-obo v0.0.0-20231026081615-705a7fffbfd2/go.mod h1:wjDx6Xm9q7dFtHJvIlrI99JytznLw5wQ4R+9mNXJwGI=github.com/bytebase/gohive v0.0.0-20240422092929-d76993a958a4 h1:5o+GWOu+j68eAODMw7/lFJavWCCiPMeqEHuOGx0YmoU=github.com/bytebase/gohive v0.0.0-20240422092929-d76993a958a4/go.mod h1:sV29Oj7v/xsXJjJwLRYimdnEX6aZOA1ofAlZ+D/snOo=-github.com/bytebase/google-sql-parser v0.0.0-20241023112038-76da71baef63 h1:Th5Tm9CZ/8BL+WYGR7xHxr8RLO/mC05v5dfOKfYQ8cY=-github.com/bytebase/google-sql-parser v0.0.0-20241023112038-76da71baef63/go.mod h1:H+oTK2I5O8AGiB6ZMGMBDP9jk4d3CFJDP1lsbAurH6A=+github.com/bytebase/google-sql-parser v0.0.0-20241028100034-870171a587ed h1:+tV1vP/PpUDQBX6etRgpVwwvvxljmf9mfw+Qv//Yicc=+github.com/bytebase/google-sql-parser v0.0.0-20241028100034-870171a587ed/go.mod h1:edPCw84OriRDnBl+JdtruQ1XoX6dbYR/AkhxyGFRHwg=github.com/bytebase/gosasl v0.0.0-20240422091407-6b7481e86f08 h1:S1GgjJLspz4E4z4CvomGvKgxyv0ATfZm27qHM418jWc=github.com/bytebase/gosasl v0.0.0-20240422091407-6b7481e86f08/go.mod h1:Qx8cW6jkI8riyzmklj80kAIkv+iezFUTBiGU0qHhHes=github.com/bytebase/mysql-parser v0.0.0-20240810145851-ab2c11629c24 h1:tI2/dg8P5DkwVODgDtqzOoFhmhUBFxSKpMyoyGOq1YU=