Skip to content

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

feat: affected rows in release check (#15205)

boojack6d1f1d0e5a2e
diff --git a/backend/api/v1/release_service.go b/backend/api/v1/release_service.go
index 3bcda3d380..2cfe58bd68 100644
--- a/backend/api/v1/release_service.go
+++ b/backend/api/v1/release_service.go
@@ -18,6 +18,7 @@ import (
"github.com/bytebase/bytebase/backend/plugin/advisor"
"github.com/bytebase/bytebase/backend/plugin/advisor/catalog"
"github.com/bytebase/bytebase/backend/plugin/db"
+ "github.com/bytebase/bytebase/backend/runner/plancheck"
"github.com/bytebase/bytebase/backend/runner/schemasync"
"github.com/bytebase/bytebase/backend/store"
"github.com/bytebase/bytebase/backend/utils"
@@ -355,6 +356,21 @@ func (s *ReleaseService) CheckRelease(ctx context.Context, request *v1pb.CheckRe
if stopChecking {
break
}
+
+ checkResult := &v1pb.CheckReleaseResponse_CheckResult{
+ File: file.Path,
+ Target: fmt.Sprintf("instances/%s/databases/%s", instance.ResourceID, database.DatabaseName),
+ }
+ // Get SQL summary report for the statement and target database.
+ // Including affected rows.
+ summaryReport, err := plancheck.GetSQLSummaryReport(ctx, s.store, s.sheetManager, s.dbFactory, database, file.Statement)
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, "failed to get SQL summary report, error: %v", err)
+ }
+ if summaryReport != nil {
+ checkResult.AffectedRows = summaryReport.AffectedRows
+ response.AffectedRows += summaryReport.AffectedRows
+ }
// Check if file has been applied to database.
revisions, err := s.store.ListRevisions(ctx, &store.FindRevisionMessage{
InstanceID: &database.InstanceID,
@@ -370,19 +386,18 @@ func (s *ReleaseService) CheckRelease(ctx context.Context, request *v1pb.CheckRe
continue
}
- adviceStatus, advices, err := s.runSQLReviewCheckForFile(ctx, catalog, instance, database, file)
+ adviceStatus, sqlReviewAdvices, err := s.runSQLReviewCheckForFile(ctx, catalog, instance, database, file)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to check SQL review: %v", err)
}
// If the advice status is not SUCCESS, we will add the file and advices to the response.
if adviceStatus != storepb.Advice_SUCCESS {
- response.Results = append(response.Results, &v1pb.CheckReleaseResponse_CheckResult{
- File: file.Path,
- Target: fmt.Sprintf("instances/%s/databases/%s", instance.ResourceID, database.DatabaseName),
- Advices: advices,
- })
+ checkResult.Advices = sqlReviewAdvices
}
- for _, advice := range advices {
+ response.Results = append(response.Results, checkResult)
+
+ // Check if we need to stop checking for the rest of files.
+ for _, advice := range sqlReviewAdvices {
switch advice.Status {
case v1pb.Advice_ERROR:
if errorAdviceCount < common.MaximumAdvicePerStatus {
@@ -452,7 +467,7 @@ func (s *ReleaseService) runSQLReviewCheckForFile(
defer driver.Close(ctx)
connection := driver.GetDB()
- classificationConfig := GetClassificationByProject(ctx, s.store, database.ProjectID)
+ classificationConfig := getClassificationByProject(ctx, s.store, database.ProjectID)
context := advisor.SQLReviewCheckContext{
Charset: dbMetadata.CharacterSet,
Collation: dbMetadata.Collation,
diff --git a/backend/api/v1/sql_service.go b/backend/api/v1/sql_service.go
index 4756b4171b..d57b1f4f41 100644
--- a/backend/api/v1/sql_service.go
+++ b/backend/api/v1/sql_service.go
@@ -1339,7 +1339,7 @@ func (s *SQLService) Check(ctx context.Context, request *v1pb.CheckRequest) (*v1
}, nil
}
-func GetClassificationByProject(ctx context.Context, stores *store.Store, projectID string) *storepb.DataClassificationSetting_DataClassificationConfig {
+func getClassificationByProject(ctx context.Context, stores *store.Store, projectID string) *storepb.DataClassificationSetting_DataClassificationConfig {
project, err := stores.GetProjectV2(ctx, &store.FindProjectMessage{
ResourceID: &projectID,
})
@@ -1413,7 +1413,7 @@ func (s *SQLService) SQLReviewCheck(
defer driver.Close(ctx)
connection := driver.GetDB()
- classificationConfig := GetClassificationByProject(ctx, s.store, database.ProjectID)
+ classificationConfig := getClassificationByProject(ctx, s.store, database.ProjectID)
context := advisor.SQLReviewCheckContext{
Charset: dbMetadata.CharacterSet,
Collation: dbMetadata.Collation,
diff --git a/backend/runner/plancheck/statement_advise_executor.go b/backend/runner/plancheck/statement_advise_executor.go
index efd2105082..8fd61c13f4 100644
--- a/backend/runner/plancheck/statement_advise_executor.go
+++ b/backend/runner/plancheck/statement_advise_executor.go
@@ -3,14 +3,15 @@ package plancheck
import (
"context"
"fmt"
+ "log/slog"
"github.com/pkg/errors"
"github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/common/log"
"github.com/bytebase/bytebase/backend/component/dbfactory"
"github.com/bytebase/bytebase/backend/component/sheet"
- v1api "github.com/bytebase/bytebase/backend/api/v1"
enterprise "github.com/bytebase/bytebase/backend/enterprise/api"
api "github.com/bytebase/bytebase/backend/legacyapi"
"github.com/bytebase/bytebase/backend/plugin/advisor"
@@ -189,7 +190,7 @@ func (e *StatementAdviseExecutor) runReview(
materials := utils.GetSecretMapFromDatabaseMessage(database)
// To avoid leaking the rendered statement, the error message should use the original statement and not the rendered statement.
renderedStatement := utils.RenderStatement(statement, materials)
- classificationConfig := v1api.GetClassificationByProject(ctx, e.store, database.ProjectID)
+ classificationConfig := getClassificationByProject(ctx, e.store, database.ProjectID)
adviceList, err := advisor.SQLReviewCheck(e.sheetManager, renderedStatement, reviewConfig.SqlReviewRules, advisor.SQLReviewCheckContext{
Charset: dbSchema.GetMetadata().CharacterSet,
@@ -268,3 +269,25 @@ func (e *StatementAdviseExecutor) buildListDatabaseNamesFunc() base.ListDatabase
return names, nil
}
}
+
+func getClassificationByProject(ctx context.Context, stores *store.Store, projectID string) *storepb.DataClassificationSetting_DataClassificationConfig {
+ project, err := stores.GetProjectV2(ctx, &store.FindProjectMessage{
+ ResourceID: &projectID,
+ })
+ if err != nil {
+ slog.Warn("failed to find project", slog.String("project", projectID), log.BBError(err))
+ return nil
+ }
+ if project == nil {
+ return nil
+ }
+ if project.DataClassificationConfigID == "" {
+ return nil
+ }
+ classificationConfig, err := stores.GetDataClassificationConfigByID(ctx, project.DataClassificationConfigID)
+ if err != nil {
+ slog.Warn("failed to find classification", slog.String("project", projectID), slog.String("classification", project.DataClassificationConfigID), log.BBError(err))
+ return nil
+ }
+ return classificationConfig
+}
diff --git a/backend/runner/plancheck/statement_report_executor.go b/backend/runner/plancheck/statement_report_executor.go
index 83b00792c0..c4f0c6df42 100644
--- a/backend/runner/plancheck/statement_report_executor.go
+++ b/backend/runner/plancheck/statement_report_executor.go
@@ -96,27 +96,48 @@ func (e *StatementReportExecutor) Run(ctx context.Context, config *storepb.PlanC
return nil, errors.Errorf("database not found %q", config.DatabaseName)
}
- results, err := e.runReport(ctx, instance, database, statement)
- if err != nil {
- return nil, err
- }
-
- if len(results) == 0 {
+ // Check statement syntax error.
+ _, syntaxAdvices := e.sheetManager.GetASTsForChecks(instance.Engine, statement)
+ if len(syntaxAdvices) > 0 {
+ advice := syntaxAdvices[0]
return []*storepb.PlanCheckRunResult_Result{
{
- Status: storepb.PlanCheckRunResult_Result_SUCCESS,
- Title: "OK",
- Content: "",
- Code: common.Ok.Int32(),
- Report: nil,
+ Status: storepb.PlanCheckRunResult_Result_ERROR,
+ Title: advice.Title,
+ Content: advice.Content,
+ Code: advice.Code,
+ Report: &storepb.PlanCheckRunResult_Result_SqlReviewReport_{
+ SqlReviewReport: &storepb.PlanCheckRunResult_Result_SqlReviewReport{
+ Line: advice.GetStartPosition().GetLine(),
+ Column: advice.GetStartPosition().GetColumn(),
+ StartPosition: advice.StartPosition,
+ EndPosition: advice.EndPosition,
+ },
+ },
},
}, nil
}
- return results, nil
+
+ planCheckRunResult := &storepb.PlanCheckRunResult_Result{
+ Status: storepb.PlanCheckRunResult_Result_SUCCESS,
+ Code: common.Ok.Int32(),
+ Title: "OK",
+ }
+ summaryReport, err := GetSQLSummaryReport(ctx, e.store, e.sheetManager, e.dbFactory, database, statement)
+ if err != nil {
+ return nil, err
+ }
+ if summaryReport != nil {
+ planCheckRunResult.Report = &storepb.PlanCheckRunResult_Result_SqlSummaryReport_{
+ SqlSummaryReport: summaryReport,
+ }
+ }
+ return []*storepb.PlanCheckRunResult_Result{planCheckRunResult}, nil
}
-func (e *StatementReportExecutor) runReport(ctx context.Context, instance *store.InstanceMessage, database *store.DatabaseMessage, statement string) ([]*storepb.PlanCheckRunResult_Result, error) {
- databaseSchema, err := e.store.GetDBSchema(ctx, database.InstanceID, database.DatabaseName)
+// GetSQLSummaryReport gets the SQL summary report for the given statement and database.
+func GetSQLSummaryReport(ctx context.Context, stores *store.Store, sheetManager *sheet.Manager, dbFactory *dbfactory.DBFactory, database *store.DatabaseMessage, statement string) (*storepb.PlanCheckRunResult_Result_SqlSummaryReport, error) {
+ databaseSchema, err := stores.GetDBSchema(ctx, database.InstanceID, database.DatabaseName)
if err != nil {
return nil, err
}
@@ -126,41 +147,28 @@ func (e *StatementReportExecutor) runReport(ctx context.Context, instance *store
if databaseSchema.GetMetadata() == nil {
return nil, errors.Errorf("database schema metadata not found: %d", database.UID)
}
+ instance, err := stores.GetInstanceV2(ctx, &store.FindInstanceMessage{ResourceID: &database.InstanceID})
+ if err != nil {
+ return nil, err
+ }
+ if instance == nil {
+ return nil, errors.Errorf("instance not found: %s", database.InstanceID)
+ }
- materials := utils.GetSecretMapFromDatabaseMessage(database)
- // To avoid leaking the rendered statement, the error message should use the original statement and not the rendered statement.
- renderedStatement := utils.RenderStatement(statement, materials)
-
- asts, advices := e.sheetManager.GetASTsForChecks(instance.Engine, statement)
- if len(advices) > 0 {
- advice := advices[0]
- // nolint:nilerr
- return []*storepb.PlanCheckRunResult_Result{
- {
- Status: storepb.PlanCheckRunResult_Result_ERROR,
- Title: advice.Title,
- Content: advice.Content,
- Code: advice.Code,
- Report: &storepb.PlanCheckRunResult_Result_SqlReviewReport_{
- SqlReviewReport: &storepb.PlanCheckRunResult_Result_SqlReviewReport{
- Line: advice.GetStartPosition().GetLine(),
- Column: advice.GetStartPosition().GetColumn(),
- StartPosition: advice.StartPosition,
- EndPosition: advice.EndPosition,
- },
- },
- },
- }, nil
+ asts, syntaxAdvices := sheetManager.GetASTsForChecks(instance.Engine, statement)
+ if len(syntaxAdvices) > 0 {
+ // Return nil as it should already be checked before running this function.
+ return nil, nil
}
var explainCalculator getAffectedRowsFromExplain
var sqlTypes []string
var defaultSchema string
- useDatabaseOwner, err := getUseDatabaseOwner(ctx, e.store, instance, database)
+ useDatabaseOwner, err := getUseDatabaseOwner(ctx, stores, instance, database)
if err != nil {
return nil, err
}
- driver, err := e.dbFactory.GetAdminDatabaseDriver(ctx, instance, database, db.ConnectionContext{
+ driver, err := dbFactory.GetAdminDatabaseDriver(ctx, instance, database, db.ConnectionContext{
UseDatabaseOwner: useDatabaseOwner,
})
if err != nil {
@@ -252,25 +260,19 @@ func (e *StatementReportExecutor) runReport(ctx context.Context, instance *store
return nil, nil
}
+ materials := utils.GetSecretMapFromDatabaseMessage(database)
+ // To avoid leaking the rendered statement, the error message should use the original statement and not the rendered statement.
+ renderedStatement := utils.RenderStatement(statement, materials)
changeSummary, err := base.ExtractChangedResources(instance.Engine, database.DatabaseName, defaultSchema, databaseSchema, asts, renderedStatement)
if err != nil {
return nil, errors.Wrapf(err, "failed to extract changed resources")
}
totalAffectedRows := calculateAffectedRows(ctx, changeSummary, explainCalculator)
- return []*storepb.PlanCheckRunResult_Result{
- {
- Status: storepb.PlanCheckRunResult_Result_SUCCESS,
- Code: common.Ok.Int32(),
- Title: "OK",
- Report: &storepb.PlanCheckRunResult_Result_SqlSummaryReport_{
- SqlSummaryReport: &storepb.PlanCheckRunResult_Result_SqlSummaryReport{
- StatementTypes: sqlTypes,
- AffectedRows: int32(totalAffectedRows),
- ChangedResources: changeSummary.ChangedResources.Build(),
- },
- },
- },
+ return &storepb.PlanCheckRunResult_Result_SqlSummaryReport{
+ StatementTypes: sqlTypes,
+ AffectedRows: int32(totalAffectedRows),
+ ChangedResources: changeSummary.ChangedResources.Build(),
}, nil
}