Skip to content

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

feat(bigquery): bigquery query span simple select * (#14136)

h3n4lbbf1ddf9ebc4
diff --git a/backend/plugin/parser/bigquery/query_span_extractor.go b/backend/plugin/parser/bigquery/query_span_extractor.go
index 1544a5b276..f178f06d95 100644
--- a/backend/plugin/parser/bigquery/query_span_extractor.go
+++ b/backend/plugin/parser/bigquery/query_span_extractor.go
@@ -36,11 +36,192 @@ func (q *querySpanExtractor) getQuerySpan(ctx context.Context, stmt string) (*ba
if err != nil {
return nil, err
}
+ allSystems, mixed := isMixedQuery(accessTables)
+ if mixed {
+ return nil, base.MixUserSystemTablesError
+ }
+ if allSystems {
+ return &base.QuerySpan{
+ SourceColumns: base.SourceColumnSet{},
+ Results: []base.QuerySpanResult{},
+ }, nil
+ }
+
+ // TODO(zp): statement type check.
+ querySpanResult, err := q.getQuerySpanResult(tree.(*parser.RootContext).Stmts().AllStmt()[0])
+ if err != nil {
+ return nil, err
+ }
+
return &base.QuerySpan{
+ Results: querySpanResult,
SourceColumns: accessTables,
}, nil
}
+func (q *querySpanExtractor) getQuerySpanResult(tree parser.IStmtContext) ([]base.QuerySpanResult, error) {
+ if tree.Query_statement() == nil {
+ return nil, errors.Errorf("unsupported non-query statement")
+ }
+
+ tableSource, err := q.extractTableSourceFromQuery(tree.Query_statement().Query())
+ if err != nil {
+ return nil, err
+ }
+
+ return tableSource.GetQuerySpanResult(), nil
+}
+
+func (q *querySpanExtractor) extractTableSourceFromQuery(query parser.IQueryContext) (base.TableSource, error) {
+ queryWithoutPipe := query.Query_without_pipe_operators()
+ if queryWithoutPipe == nil {
+ return nil, errors.Errorf("unsupported query with pipe operators")
+ }
+ return q.extractTableSourceFromQueryWithoutPipe(queryWithoutPipe)
+}
+
+func (q *querySpanExtractor) extractTableSourceFromQueryWithoutPipe(queryWithoutPipe parser.IQuery_without_pipe_operatorsContext) (base.TableSource, error) {
+ // TODO(zp): handle CTE.
+
+ return q.extractTableSourceFromQueryPrimaryOrSetOperation(queryWithoutPipe.Query_primary_or_set_operation())
+}
+
+func (q *querySpanExtractor) extractTableSourceFromQueryPrimaryOrSetOperation(queryPrimaryOrSetOperation parser.IQuery_primary_or_set_operationContext) (base.TableSource, error) {
+ if queryPrimaryOrSetOperation.Query_primary() != nil {
+ return q.extractTableSourceFromQueryPrimary(queryPrimaryOrSetOperation.Query_primary())
+ }
+ // TODO(zp): handle set operation.
+ return nil, nil
+}
+
+func (q *querySpanExtractor) extractTableSourceFromQueryPrimary(queryPrimary parser.IQuery_primaryContext) (base.TableSource, error) {
+ if queryPrimary.Select_() != nil {
+ return q.extractTableSourceFromSelect(queryPrimary.Select_())
+ }
+ // TODO(zp): handle parenthesized query.
+ return nil, nil
+}
+
+func (q *querySpanExtractor) extractTableSourceFromSelect(selectCtx parser.ISelectContext) (base.TableSource, error) {
+ var fromFields []base.QuerySpanResult
+ var resultFields []base.QuerySpanResult
+ if selectCtx.From_clause() != nil {
+ tableSource, err := q.extractTableSourceFromFromClause(selectCtx.From_clause())
+ if err != nil {
+ return nil, err
+ }
+ fromFields = tableSource.GetQuerySpanResult()
+ }
+
+ itemList := selectCtx.Select_clause().Select_list().AllSelect_list_item()
+ for _, item := range itemList {
+ // TODO(zp): handle other select item.
+ if item.Select_column_star() != nil {
+ resultFields = append(resultFields, fromFields...)
+ }
+ }
+ return &base.PseudoTable{
+ Name: "",
+ Columns: resultFields,
+ }, nil
+}
+
+func (q *querySpanExtractor) extractTableSourceFromFromClause(fromClause parser.IFrom_clauseContext) (base.TableSource, error) {
+ contents := fromClause.From_clause_contents()
+ tableSource, err := q.extractTableSourceFromTablePrimary(contents.Table_primary())
+ if err != nil {
+ return nil, err
+ }
+ return tableSource, nil
+ // TODO(zp): handle suffix, alias.
+}
+
+func (q *querySpanExtractor) extractTableSourceFromTablePrimary(tablePrimary parser.ITable_primaryContext) (base.TableSource, error) {
+ if tablePrimary.Tvf_with_suffixes() != nil {
+ // We do not support table value function because we do not have the returnning columns information.
+ return nil, errors.Errorf("unsupported table value function: %s", tablePrimary.GetText())
+ }
+ if tablePrimary.Table_path_expression() != nil {
+ return q.extractTableSourceFromTablePathExpression(tablePrimary.Table_path_expression())
+ }
+
+ // TODO(zp): handle other case
+ return nil, nil
+}
+
+func (q *querySpanExtractor) extractTableSourceFromTablePathExpression(tablePathExpression parser.ITable_path_expressionContext) (base.TableSource, error) {
+ base := tablePathExpression.Table_path_expression_base()
+ if base.Unnest_expression() != nil {
+ // We do not support unnest expression because we do not have the returnning columns information.
+ return nil, errors.Errorf("unsupported unnest expression: %s", base.GetText())
+ }
+ var tableName string
+ datasetName := q.defaultDatabase
+
+ if slashedOrDashedPathExpression := base.Maybe_slashed_or_dashed_path_expression(); slashedOrDashedPathExpression != nil {
+ if slashedOrDashedPathExpression.Maybe_dashed_path_expression() != nil {
+ if maybeDashedPathExpr := slashedOrDashedPathExpression.Maybe_dashed_path_expression(); maybeDashedPathExpr != nil {
+ // TODO(zp): support dashed path expression, for example, REGION-us
+ if maybeDashedPathExpr.Dashed_path_expression() != nil {
+ return nil, errors.Errorf("unsupported dashed path expression: %s", base.GetText())
+ }
+ // REFACTOR(zp): refactor the code to extract table name and dataset name.
+ allIdentifiers := maybeDashedPathExpr.Path_expression().AllIdentifier()
+ if len(allIdentifiers) > 0 {
+ tableName = unquoteIdentifier(allIdentifiers[len(allIdentifiers)-1])
+ if len(allIdentifiers) > 1 {
+ datasetName = unquoteIdentifier(allIdentifiers[len(allIdentifiers)-2])
+ }
+ }
+ }
+ if slashedOrDashedPathExpression.Slashed_path_expression() != nil {
+ return nil, errors.Errorf("unsupported slashed path expression: %s", base.GetText())
+ }
+ }
+ }
+
+ tabelSource, err := q.findTableSchema(datasetName, tableName)
+ if err != nil {
+ return nil, err
+ }
+ // TODO(zp): add in q.from
+ return tabelSource, nil
+}
+
+func (q *querySpanExtractor) findTableSchema(datasetName string, tableName string) (base.TableSource, error) {
+ // https://cloud.google.com/bigquery/docs/reference/standard-sql/lexical#case_sensitivity
+ // Dataset and table names are case-sensitive unless the is_case_insensitive option is set to TRUE.
+ _, databaseMetadata, err := q.gCtx.GetDatabaseMetadataFunc(q.ctx, q.gCtx.InstanceID, datasetName)
+ if err != nil {
+ return nil, err
+ }
+ if databaseMetadata == nil {
+ return nil, errors.Errorf("dataset %q not found", datasetName)
+ }
+
+ schema := databaseMetadata.GetSchema("")
+ if schema == nil {
+ return nil, errors.Errorf("table %q not found", tableName)
+ }
+
+ table := schema.GetTable(tableName)
+ if table == nil {
+ return nil, errors.Errorf("table %q not found", tableName)
+ }
+
+ var columns []string
+ for _, column := range table.GetColumns() {
+ columns = append(columns, column.Name)
+ }
+ return &base.PhysicalTable{
+ Server: "",
+ Database: datasetName,
+ Schema: "",
+ Name: tableName,
+ Columns: columns,
+ }, nil
+}
+
func getAccessTables(defaultDatabase string, tree antlr.Tree) (base.SourceColumnSet, error) {
l := newAccessTableListener(defaultDatabase)
result := make(base.SourceColumnSet)
@@ -91,6 +272,10 @@ func (l *accessTableListener) EnterTable_path_expression(ctx *parser.Table_path_
}
// Table name syntax: https://cloud.google.com/bigquery/docs/reference/standard-sql/lexical
+ // Most of the time, the syntax can be [project_id.][dataset_id.]table_id.
+ // One difference is that the user access INFORMATION_SCHEMA in dataset,
+ // the syntax would be [project_id.]([region_id.]|[dataset_id.])INFORMATION_SCHEMA.VIEW_NAME.
+ // In this case, we treat the INFORMATION_SCHEMA as schema name.
allIdentifiers := pathExpr.AllIdentifier()
if len(allIdentifiers) == 0 {
return
@@ -104,7 +289,12 @@ func (l *accessTableListener) EnterTable_path_expression(ctx *parser.Table_path_
columnSource.Table = tableName
if len(allIdentifiers) >= 2 {
- columnSource.Database = unquoteIdentifier(allIdentifiers[len(allIdentifiers)-2])
+ identifier := unquoteIdentifier(allIdentifiers[len(allIdentifiers)-2])
+ if strings.EqualFold(identifier, "INFORMATION_SCHEMA") {
+ columnSource.Schema = identifier
+ } else {
+ columnSource.Database = identifier
+ }
}
l.sourceColumnSet[columnSource] = true
@@ -116,3 +306,24 @@ func unquoteIdentifier(identifier parser.IIdentifierContext) string {
}
return identifier.GetText()
}
+
+func isMixedQuery(m base.SourceColumnSet) (bool, bool) {
+ hasSystem, hasUser := false, false
+ for table := range m {
+ if isSystemResource(table) {
+ hasSystem = true
+ } else {
+ hasUser = true
+ }
+ }
+
+ if hasSystem && hasUser {
+ return false, true
+ }
+
+ return !hasUser && hasSystem, false
+}
+
+func isSystemResource(resource base.ColumnResource) bool {
+ return strings.EqualFold(resource.Schema, "INFORMATION_SCHEMA")
+}
diff --git a/backend/plugin/parser/bigquery/test-data/query-span/standard.yaml b/backend/plugin/parser/bigquery/test-data/query-span/standard.yaml
index aa9c148b49..7a79ed909f 100644
--- a/backend/plugin/parser/bigquery/test-data/query-span/standard.yaml
+++ b/backend/plugin/parser/bigquery/test-data/query-span/standard.yaml
@@ -1,6 +1,6 @@
- description: Simple select asterisk statement
statement: SELECT * FROM people;
- defaultDatabase: db
+ defaultDatabase: ds1
metadata: |-
{
"name": "ds1",
@@ -24,10 +24,24 @@
]
}
querySpan:
- results: []
+ 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: db
+ database: ds1
schema: ""
table: people
column: ""
diff --git a/go.mod b/go.mod
index 3140a74d06..c2f39ff87e 100644
--- a/go.mod
+++ b/go.mod
@@ -19,7 +19,7 @@ require (
github.com/beltran/gohive v1.7.0
github.com/blang/semver/v4 v4.0.0
github.com/buger/jsonparser v1.1.1
- github.com/bytebase/google-sql-parser v0.0.0-20241016165455-798a47e89841
+ github.com/bytebase/google-sql-parser v0.0.0-20241018075546-9b64719ac75b
github.com/bytebase/mysql-parser v0.0.0-20240810145851-ab2c11629c24
github.com/bytebase/plsql-parser v0.0.0-20240929073008-6b57c2e2525d
github.com/bytebase/postgresql-parser v0.0.0-20241008085234-a95eacac994a
diff --git a/go.sum b/go.sum
index a500e56ad0..ad97973b52 100644
--- a/go.sum
+++ b/go.sum
@@ -817,8 +817,8 @@ github.com/bytebase/go-obo v0.0.0-20231026081615-705a7fffbfd2 h1:nEHZi8S7PHT4GxP
github.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-20241016165455-798a47e89841 h1:LDgX6n04eWjTSApyhnmkU6/676AJDDnP7ilke97VpvE=
-github.com/bytebase/google-sql-parser v0.0.0-20241016165455-798a47e89841/go.mod h1:H+oTK2I5O8AGiB6ZMGMBDP9jk4d3CFJDP1lsbAurH6A=
+github.com/bytebase/google-sql-parser v0.0.0-20241018075546-9b64719ac75b h1:De82LaxGq1olk9e79mSFK5wvazxjoVIMkgq3TT6fczI=
+github.com/bytebase/google-sql-parser v0.0.0-20241018075546-9b64719ac75b/go.mod h1:H+oTK2I5O8AGiB6ZMGMBDP9jk4d3CFJDP1lsbAurH6A=
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=