Skip to content

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

refactor: consolidate plan check runs to single record per plan (#18593)

p0ny6ebdc6ac1194
diff --git a/backend/api/v1/plan_service.go b/backend/api/v1/plan_service.go
index 1317cc2235..a80da7defd 100644
--- a/backend/api/v1/plan_service.go
+++ b/backend/api/v1/plan_service.go
@@ -254,13 +254,15 @@ func (s *PlanService) CreatePlan(ctx context.Context, request *connect.Request[v
return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to create plan, error: %v", err))
}
- // Don't create plan checks if the plan comes from releases.
- planCheckRuns, err := getPlanCheckRunsFromPlan(project, plan, databaseGroup)
+ // Create consolidated plan check run if applicable.
+ planCheckRun, err := getPlanCheckRunFromPlan(project, plan, databaseGroup)
if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to get plan check runs for plan, error: %v", err))
+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to get plan check run for plan, error: %v", err))
}
- if err := s.store.CreatePlanCheckRuns(ctx, plan, planCheckRuns...); err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to create plan check runs, error: %v", err))
+ if planCheckRun != nil {
+ if err := s.store.CreatePlanCheckRuns(ctx, plan, planCheckRun); err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to create plan check run, error: %v", err))
+ }
}
// Tickle plan check scheduler.
s.stateCfg.PlanCheckTickleChan <- 0
@@ -411,12 +413,14 @@ func (s *PlanService) UpdatePlan(ctx context.Context, request *connect.Request[v
}
if planCheckRunsTrigger {
- planCheckRuns, err := getPlanCheckRunsFromPlan(project, updatedPlan, databaseGroup)
+ planCheckRun, err := getPlanCheckRunFromPlan(project, updatedPlan, databaseGroup)
if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to get plan check runs for plan, error: %v", err))
+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to get plan check run for plan, error: %v", err))
}
- if err := s.store.CreatePlanCheckRuns(ctx, updatedPlan, planCheckRuns...); err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to create plan check runs, error: %v", err))
+ if planCheckRun != nil {
+ if err := s.store.CreatePlanCheckRuns(ctx, updatedPlan, planCheckRun); err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to create plan check run, error: %v", err))
+ }
}
// Tickle plan check scheduler.
s.stateCfg.PlanCheckTickleChan <- 0
@@ -664,12 +668,14 @@ func (s *PlanService) RunPlanChecks(ctx context.Context, request *connect.Reques
}
}
}
- planCheckRuns, err := getPlanCheckRunsFromPlan(project, plan, databaseGroup)
+ planCheckRun, err := getPlanCheckRunFromPlan(project, plan, databaseGroup)
if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to get plan check runs for plan, error: %v", err))
+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to get plan check run for plan, error: %v", err))
}
- if err := s.store.CreatePlanCheckRuns(ctx, plan, planCheckRuns...); err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to create plan check runs, error: %v", err))
+ if planCheckRun != nil {
+ if err := s.store.CreatePlanCheckRuns(ctx, plan, planCheckRun); err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to create plan check run, error: %v", err))
+ }
}
// Tickle plan check scheduler.
@@ -727,7 +733,7 @@ func (s *PlanService) BatchCancelPlanCheckRuns(ctx context.Context, request *con
switch planCheckRun.Status {
case store.PlanCheckRunStatusRunning:
default:
- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("planCheckRun %v(%v) is not running", planCheckRun.UID, planCheckRun.Type))
+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("planCheckRun %v is not running", planCheckRun.UID))
}
}
// Cancel the plan check runs.
diff --git a/backend/api/v1/plan_service_converter.go b/backend/api/v1/plan_service_converter.go
index c4ffeabacb..507c566137 100644
--- a/backend/api/v1/plan_service_converter.go
+++ b/backend/api/v1/plan_service_converter.go
@@ -260,33 +260,67 @@ func convertPlanSpecExportDataConfig(config *v1pb.Plan_Spec_ExportDataConfig) *s
func convertToPlanCheckRuns(projectID string, planUID int64, runs []*store.PlanCheckRunMessage) []*v1pb.PlanCheckRun {
var planCheckRuns []*v1pb.PlanCheckRun
for _, run := range runs {
- converted := convertToPlanCheckRun(projectID, planUID, run)
- planCheckRuns = append(planCheckRuns, converted)
+ // Expand consolidated run into virtual records for backward compatibility
+ expanded := expandPlanCheckRun(projectID, planUID, run)
+ planCheckRuns = append(planCheckRuns, expanded...)
}
return planCheckRuns
}
-func convertToPlanCheckRun(projectID string, planUID int64, run *store.PlanCheckRunMessage) *v1pb.PlanCheckRun {
- converted := &v1pb.PlanCheckRun{
- Name: common.FormatPlanCheckRun(projectID, planUID, int64(run.UID)),
- CreateTime: timestamppb.New(run.CreatedAt),
- Type: convertToPlanCheckRunType(run.Type),
- Status: convertToPlanCheckRunStatus(run.Status),
- Target: common.FormatDatabase(run.Config.InstanceId, run.Config.DatabaseName),
- Sheet: common.FormatSheet(projectID, run.Config.GetSheetSha256()),
- Results: convertToPlanCheckRunResults(run.Result.Results),
- Error: run.Result.Error,
- }
- return converted
+// expandPlanCheckRun expands a consolidated plan check run into multiple virtual
+// records for API backward compatibility. Each target/type combination becomes
+// a separate API response record.
+func expandPlanCheckRun(projectID string, planUID int64, run *store.PlanCheckRunMessage) []*v1pb.PlanCheckRun {
+ var runs []*v1pb.PlanCheckRun
+
+ // Group results by target and type
+ type key struct {
+ target string
+ checkType storepb.PlanCheckType
+ }
+ resultsByKey := make(map[key][]*storepb.PlanCheckRunResult_Result)
+ for _, result := range run.Result.GetResults() {
+ k := key{
+ target: result.Target,
+ checkType: result.Type,
+ }
+ resultsByKey[k] = append(resultsByKey[k], result)
+ }
+
+ // Build virtual records from targets
+ virtualID := 0
+ for _, target := range run.Config.GetTargets() {
+ for _, checkType := range target.Types {
+ virtualID++
+ k := key{
+ target: target.Target,
+ checkType: checkType,
+ }
+ results := resultsByKey[k]
+
+ runs = append(runs, &v1pb.PlanCheckRun{
+ Name: common.FormatPlanCheckRun(projectID, planUID, int64(run.UID)*1000+int64(virtualID)),
+ CreateTime: timestamppb.New(run.CreatedAt),
+ Type: convertPlanCheckType(checkType),
+ Status: convertToPlanCheckRunStatus(run.Status),
+ Target: target.Target,
+ Sheet: common.FormatSheet(projectID, target.SheetSha256),
+ Results: convertToPlanCheckRunResults(results),
+ Error: run.Result.Error,
+ })
+ }
+ }
+
+ return runs
}
-func convertToPlanCheckRunType(t store.PlanCheckRunType) v1pb.PlanCheckRun_Type {
+func convertPlanCheckType(t storepb.PlanCheckType) v1pb.PlanCheckRun_Type {
switch t {
- case store.PlanCheckDatabaseStatementAdvise:
+ case storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_ADVISE:
return v1pb.PlanCheckRun_DATABASE_STATEMENT_ADVISE
- case store.PlanCheckDatabaseStatementSummaryReport:
+ case storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_SUMMARY_REPORT:
return v1pb.PlanCheckRun_DATABASE_STATEMENT_SUMMARY_REPORT
- case store.PlanCheckDatabaseGhostSync:
+ case storepb.PlanCheckType_PLAN_CHECK_TYPE_GHOST_SYNC:
return v1pb.PlanCheckRun_DATABASE_GHOST_SYNC
default:
return v1pb.PlanCheckRun_TYPE_UNSPECIFIED
diff --git a/backend/api/v1/plan_service_plan_check.go b/backend/api/v1/plan_service_plan_check.go
index 83232e6bab..3394f29e35 100644
--- a/backend/api/v1/plan_service_plan_check.go
+++ b/backend/api/v1/plan_service_plan_check.go
@@ -1,24 +1,23 @@
package v1
import (
- "fmt"
-
"github.com/pkg/errors"
- "github.com/bytebase/bytebase/backend/common"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
"github.com/bytebase/bytebase/backend/store"
)
-func getPlanCheckRunsFromPlan(project *store.ProjectMessage, plan *store.PlanMessage, databaseGroup *v1pb.DatabaseGroup) ([]*store.PlanCheckRunMessage, error) {
- var planCheckRuns []*store.PlanCheckRunMessage
+// getPlanCheckRunFromPlan returns a single consolidated plan check run for a plan.
+func getPlanCheckRunFromPlan(project *store.ProjectMessage, plan *store.PlanMessage, databaseGroup *v1pb.DatabaseGroup) (*store.PlanCheckRunMessage, error) {
+ var targets []*storepb.PlanCheckRunConfig_CheckTarget
+
for _, spec := range plan.Config.Specs {
switch config := spec.Config.(type) {
case *storepb.PlanConfig_Spec_CreateDatabaseConfig:
// No checks for create database.
case *storepb.PlanConfig_Spec_ExportDataConfig:
- // No checks export data.
+ // No checks for export data.
case *storepb.PlanConfig_Spec_ChangeDatabaseConfig:
// Skip plan checks for releases.
if config.ChangeDatabaseConfig.Release != "" {
@@ -34,70 +33,47 @@ func getPlanCheckRunsFromPlan(project *store.ProjectMessage, plan *store.PlanMes
databases = config.ChangeDatabaseConfig.Targets
}
+ // Apply sampling upfront
+ if samplingSize := project.Setting.GetCiSamplingSize(); samplingSize > 0 {
+ if len(databases) > int(samplingSize) {
+ databases = databases[:samplingSize]
+ }
+ }
+
+ enableSDL := config.ChangeDatabaseConfig.Type == storepb.PlanConfig_ChangeDatabaseConfig_SDL
+ enableGhost := config.ChangeDatabaseConfig.Type == storepb.PlanConfig_ChangeDatabaseConfig_MIGRATE && config.ChangeDatabaseConfig.EnableGhost
+
for _, target := range databases {
- instanceID, databaseName, err := common.GetInstanceDatabaseID(target)
- if err != nil {
- return nil, errors.Wrapf(err, "failed to parse %q", target)
+ types := []storepb.PlanCheckType{
+ storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_ADVISE,
+ storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_SUMMARY_REPORT,
}
- enableSDL := config.ChangeDatabaseConfig.Type == storepb.PlanConfig_ChangeDatabaseConfig_SDL
- planCheckRuns = append(planCheckRuns, &store.PlanCheckRunMessage{
- PlanUID: plan.UID,
- Status: store.PlanCheckRunStatusRunning,
- Type: store.PlanCheckDatabaseStatementAdvise,
- Config: &storepb.PlanCheckRunConfig{
- SheetSha256: config.ChangeDatabaseConfig.SheetSha256,
- InstanceId: instanceID,
- DatabaseName: databaseName,
- EnablePriorBackup: config.ChangeDatabaseConfig.EnablePriorBackup,
- EnableGhost: config.ChangeDatabaseConfig.EnableGhost,
- EnableSdl: enableSDL,
- },
- })
- planCheckRuns = append(planCheckRuns, &store.PlanCheckRunMessage{
- PlanUID: plan.UID,
- Status: store.PlanCheckRunStatusRunning,
- Type: store.PlanCheckDatabaseStatementSummaryReport,
- Config: &storepb.PlanCheckRunConfig{
- SheetSha256: config.ChangeDatabaseConfig.SheetSha256,
- InstanceId: instanceID,
- DatabaseName: databaseName,
- EnableGhost: config.ChangeDatabaseConfig.EnableGhost,
- EnableSdl: enableSDL,
- },
- })
- if config.ChangeDatabaseConfig.Type == storepb.PlanConfig_ChangeDatabaseConfig_MIGRATE && config.ChangeDatabaseConfig.EnableGhost {
- planCheckRuns = append(planCheckRuns, &store.PlanCheckRunMessage{
- PlanUID: plan.UID,
- Status: store.PlanCheckRunStatusRunning,
- Type: store.PlanCheckDatabaseGhostSync,
- Config: &storepb.PlanCheckRunConfig{
- SheetSha256: config.ChangeDatabaseConfig.SheetSha256,
- InstanceId: instanceID,
- DatabaseName: databaseName,
- EnableGhost: config.ChangeDatabaseConfig.EnableGhost,
- EnableSdl: enableSDL,
- GhostFlags: config.ChangeDatabaseConfig.GhostFlags,
- },
- })
+ if enableGhost {
+ types = append(types, storepb.PlanCheckType_PLAN_CHECK_TYPE_GHOST_SYNC)
}
+
+ targets = append(targets, &storepb.PlanCheckRunConfig_CheckTarget{
+ Target: target,
+ SheetSha256: config.ChangeDatabaseConfig.SheetSha256,
+ EnablePriorBackup: config.ChangeDatabaseConfig.EnablePriorBackup,
+ EnableGhost: config.ChangeDatabaseConfig.EnableGhost,
+ EnableSdl: enableSDL,
+ GhostFlags: config.ChangeDatabaseConfig.GhostFlags,
+ Types: types,
+ })
}
default:
return nil, errors.Errorf("unknown spec config type %T", config)
}
}
- if project.Setting.GetCiSamplingSize() > 0 {
- var updatedRuns []*store.PlanCheckRunMessage
- countMap := make(map[string]int32)
- for _, run := range planCheckRuns {
- key := fmt.Sprintf("%s/%s", run.Type, run.Config.GetSheetSha256())
- if countMap[key] >= project.Setting.GetCiSamplingSize() {
- continue
- }
- updatedRuns = append(updatedRuns, run)
- countMap[key]++
- }
- planCheckRuns = updatedRuns
+ if len(targets) == 0 {
+ return nil, nil
}
- return planCheckRuns, nil
+
+ return &store.PlanCheckRunMessage{
+ PlanUID: plan.UID,
+ Status: store.PlanCheckRunStatusRunning,
+ Config: &storepb.PlanCheckRunConfig{Targets: targets},
+ }, nil
}
diff --git a/backend/api/v1/plan_service_test.go b/backend/api/v1/plan_service_test.go
index 72b3d4bbb9..ae949743c1 100644
--- a/backend/api/v1/plan_service_test.go
+++ b/backend/api/v1/plan_service_test.go
@@ -225,7 +225,6 @@ func TestParsePlanCheckRunFilter(t *testing.T) {
// Compare other fields that should remain unchanged
a.Equal(test.want.PlanUID, find.PlanUID, "PlanUID should match")
a.Equal(test.want.UIDs, find.UIDs, "UIDs should match")
- a.Equal(test.want.Type, find.Type, "Type should match")
})
}
}
diff --git a/backend/generated-go/store/plan_check_run.pb.go b/backend/generated-go/store/plan_check_run.pb.go
index 3f3897445f..27da8ba525 100644
--- a/backend/generated-go/store/plan_check_run.pb.go
+++ b/backend/generated-go/store/plan_check_run.pb.go
@@ -21,19 +21,61 @@ const (
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
+type PlanCheckType int32
+
+const (
+ PlanCheckType_PLAN_CHECK_TYPE_UNSPECIFIED PlanCheckType = 0
+ PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_ADVISE PlanCheckType = 1
+ PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_SUMMARY_REPORT PlanCheckType = 2
+ PlanCheckType_PLAN_CHECK_TYPE_GHOST_SYNC PlanCheckType = 3
+)
+
+// Enum value maps for PlanCheckType.
+var (
+ PlanCheckType_name = map[int32]string{
+ 0: "PLAN_CHECK_TYPE_UNSPECIFIED",
+ 1: "PLAN_CHECK_TYPE_STATEMENT_ADVISE",
+ 2: "PLAN_CHECK_TYPE_STATEMENT_SUMMARY_REPORT",
+ 3: "PLAN_CHECK_TYPE_GHOST_SYNC",
+ }
+ PlanCheckType_value = map[string]int32{
+ "PLAN_CHECK_TYPE_UNSPECIFIED": 0,
+ "PLAN_CHECK_TYPE_STATEMENT_ADVISE": 1,
+ "PLAN_CHECK_TYPE_STATEMENT_SUMMARY_REPORT": 2,
+ "PLAN_CHECK_TYPE_GHOST_SYNC": 3,
+ }
+)
+
+func (x PlanCheckType) Enum() *PlanCheckType {
+ p := new(PlanCheckType)
+ *p = x
+ return p
+}
+
+func (x PlanCheckType) String() string {
+ return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
+}
+
+func (PlanCheckType) Descriptor() protoreflect.EnumDescriptor {
+ return file_store_plan_check_run_proto_enumTypes[0].Descriptor()
+}
+
+func (PlanCheckType) Type() protoreflect.EnumType {
+ return &file_store_plan_check_run_proto_enumTypes[0]
+}
+
+func (x PlanCheckType) Number() protoreflect.EnumNumber {
+ return protoreflect.EnumNumber(x)
+}
+
+// Deprecated: Use PlanCheckType.Descriptor instead.
+func (PlanCheckType) EnumDescriptor() ([]byte, []int) {
+ return file_store_plan_check_run_proto_rawDescGZIP(), []int{0}
+}
+
type PlanCheckRunConfig struct {
- state protoimpl.MessageState `protogen:"open.v1"`
- // The SHA256 hash of the sheet content (hex-encoded).
- SheetSha256 string `protobuf:"bytes,1,opt,name=sheet_sha256,json=sheetSha256,proto3" json:"sheet_sha256,omitempty"`
- InstanceId string `protobuf:"bytes,2,opt,name=instance_id,json=instanceId,proto3" json:"instance_id,omitempty"`
- DatabaseName string `protobuf:"bytes,3,opt,name=database_name,json=databaseName,proto3" json:"database_name,omitempty"`
- GhostFlags map[string]string `protobuf:"bytes,4,rep,name=ghost_flags,json=ghostFlags,proto3" json:"ghost_flags,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
- // If set, a backup of the modified data will be created automatically before any changes are applied.
- EnablePriorBackup bool `protobuf:"varint,5,opt,name=enable_prior_backup,json=enablePriorBackup,proto3" json:"enable_prior_backup,omitempty"`
- // Whether to use gh-ost for online schema migration.
- EnableGhost bool `protobuf:"varint,6,opt,name=enable_ghost,json=enableGhost,proto3" json:"enable_ghost,omitempty"`
- // Whether this is a Schema Definition Language (SDL) change.
- EnableSdl bool `protobuf:"varint,7,opt,name=enable_sdl,json=enableSdl,proto3" json:"enable_sdl,omitempty"`
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Targets []*PlanCheckRunConfig_CheckTarget `protobuf:"bytes,1,rep,name=targets,proto3" json:"targets,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -68,55 +110,13 @@ func (*PlanCheckRunConfig) Descriptor() ([]byte, []int) {
return file_store_plan_check_run_proto_rawDescGZIP(), []int{0}
}
-func (x *PlanCheckRunConfig) GetSheetSha256() string {
- if x != nil {
- return x.SheetSha256
- }
- return ""
-}
-
-func (x *PlanCheckRunConfig) GetInstanceId() string {
- if x != nil {
- return x.InstanceId
- }
- return ""
-}
-
-func (x *PlanCheckRunConfig) GetDatabaseName() string {
- if x != nil {
- return x.DatabaseName
- }
- return ""
-}
-
-func (x *PlanCheckRunConfig) GetGhostFlags() map[string]string {
+func (x *PlanCheckRunConfig) GetTargets() []*PlanCheckRunConfig_CheckTarget {
if x != nil {
- return x.GhostFlags
+ return x.Targets
}
return nil
}
-func (x *PlanCheckRunConfig) GetEnablePriorBackup() bool {
- if x != nil {
- return x.EnablePriorBackup
- }
- return false
-}
-
-func (x *PlanCheckRunConfig) GetEnableGhost() bool {
- if x != nil {
- return x.EnableGhost
- }
- return false
-}
-
-func (x *PlanCheckRunConfig) GetEnableSdl() bool {
- if x != nil {
- return x.EnableSdl
- }
- return false
-}
-
type PlanCheckRunResult struct {
state protoimpl.MessageState `protogen:"open.v1"`
Results []*PlanCheckRunResult_Result `protobuf:"bytes,1,rep,name=results,proto3" json:"results,omitempty"`
@@ -370,12 +370,109 @@ func (x *ChangedResourceTable) GetTableRows() int64 {
return 0
}
+type PlanCheckRunConfig_CheckTarget struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ // Format: instances/{instance}/databases/{database}
+ Target string `protobuf:"bytes,1,opt,name=target,proto3" json:"target,omitempty"`
+ SheetSha256 string `protobuf:"bytes,2,opt,name=sheet_sha256,json=sheetSha256,proto3" json:"sheet_sha256,omitempty"`
+ EnablePriorBackup bool `protobuf:"varint,3,opt,name=enable_prior_backup,json=enablePriorBackup,proto3" json:"enable_prior_backup,omitempty"`
+ EnableGhost bool `protobuf:"varint,4,opt,name=enable_ghost,json=enableGhost,proto3" json:"enable_ghost,omitempty"`
+ EnableSdl bool `protobuf:"varint,5,opt,name=enable_sdl,json=enableSdl,proto3" json:"enable_sdl,omitempty"`
+ GhostFlags map[string]string `protobuf:"bytes,6,rep,name=ghost_flags,json=ghostFlags,proto3" json:"ghost_flags,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+ Types []PlanCheckType `protobuf:"varint,7,rep,packed,name=types,proto3,enum=bytebase.store.PlanCheckType" json:"types,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *PlanCheckRunConfig_CheckTarget) Reset() {
+ *x = PlanCheckRunConfig_CheckTarget{}
+ mi := &file_store_plan_check_run_proto_msgTypes[6]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *PlanCheckRunConfig_CheckTarget) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*PlanCheckRunConfig_CheckTarget) ProtoMessage() {}
+
+func (x *PlanCheckRunConfig_CheckTarget) ProtoReflect() protoreflect.Message {
+ mi := &file_store_plan_check_run_proto_msgTypes[6]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use PlanCheckRunConfig_CheckTarget.ProtoReflect.Descriptor instead.
+func (*PlanCheckRunConfig_CheckTarget) Descriptor() ([]byte, []int) {
+ return file_store_plan_check_run_proto_rawDescGZIP(), []int{0, 0}
+}
+
+func (x *PlanCheckRunConfig_CheckTarget) GetTarget() string {
+ if x != nil {
+ return x.Target
+ }
+ return ""
+}
+
+func (x *PlanCheckRunConfig_CheckTarget) GetSheetSha256() string {
+ if x != nil {
+ return x.SheetSha256
+ }
+ return ""
+}
+
+func (x *PlanCheckRunConfig_CheckTarget) GetEnablePriorBackup() bool {
+ if x != nil {
+ return x.EnablePriorBackup
+ }
+ return false
+}
+
+func (x *PlanCheckRunConfig_CheckTarget) GetEnableGhost() bool {
+ if x != nil {
+ return x.EnableGhost
+ }
+ return false
+}
+
+func (x *PlanCheckRunConfig_CheckTarget) GetEnableSdl() bool {
+ if x != nil {
+ return x.EnableSdl
+ }
+ return false
+}
+
+func (x *PlanCheckRunConfig_CheckTarget) GetGhostFlags() map[string]string {
+ if x != nil {
+ return x.GhostFlags
+ }
+ return nil
+}
+
+func (x *PlanCheckRunConfig_CheckTarget) GetTypes() []PlanCheckType {
+ if x != nil {
+ return x.Types
+ }
+ return nil
+}
+
type PlanCheckRunResult_Result struct {
state protoimpl.MessageState `protogen:"open.v1"`
Status Advice_Status `protobuf:"varint,1,opt,name=status,proto3,enum=bytebase.store.Advice_Status" json:"status,omitempty"`
Title string `protobuf:"bytes,2,opt,name=title,proto3" json:"title,omitempty"`
Content string `protobuf:"bytes,3,opt,name=content,proto3" json:"content,omitempty"`
Code int32 `protobuf:"varint,4,opt,name=code,proto3" json:"code,omitempty"`
+ // Target identification for consolidated results
+ // Format: instances/{instance}/databases/{database}
+ Target string `protobuf:"bytes,7,opt,name=target,proto3" json:"target,omitempty"`
+ Type PlanCheckType `protobuf:"varint,8,opt,name=type,proto3,enum=bytebase.store.PlanCheckType" json:"type,omitempty"`
// Types that are valid to be assigned to Report:
//
// *PlanCheckRunResult_Result_SqlSummaryReport_
@@ -387,7 +484,7 @@ type PlanCheckRunResult_Result struct {
func (x *PlanCheckRunResult_Result) Reset() {
*x = PlanCheckRunResult_Result{}
- mi := &file_store_plan_check_run_proto_msgTypes[7]
+ mi := &file_store_plan_check_run_proto_msgTypes[8]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -399,7 +496,7 @@ func (x *PlanCheckRunResult_Result) String() string {
func (*PlanCheckRunResult_Result) ProtoMessage() {}
func (x *PlanCheckRunResult_Result) ProtoReflect() protoreflect.Message {
- mi := &file_store_plan_check_run_proto_msgTypes[7]
+ mi := &file_store_plan_check_run_proto_msgTypes[8]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -443,6 +540,20 @@ func (x *PlanCheckRunResult_Result) GetCode() int32 {
return 0
}
+func (x *PlanCheckRunResult_Result) GetTarget() string {
+ if x != nil {
+ return x.Target
+ }
+ return ""
+}
+
+func (x *PlanCheckRunResult_Result) GetType() PlanCheckType {
+ if x != nil {
+ return x.Type
+ }
+ return PlanCheckType_PLAN_CHECK_TYPE_UNSPECIFIED
+}
+
func (x *PlanCheckRunResult_Result) GetReport() isPlanCheckRunResult_Result_Report {
if x != nil {
return x.Report
@@ -496,7 +607,7 @@ type PlanCheckRunResult_Result_SqlSummaryReport struct {
func (x *PlanCheckRunResult_Result_SqlSummaryReport) Reset() {
*x = PlanCheckRunResult_Result_SqlSummaryReport{}
- mi := &file_store_plan_check_run_proto_msgTypes[8]
+ mi := &file_store_plan_check_run_proto_msgTypes[9]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -508,7 +619,7 @@ func (x *PlanCheckRunResult_Result_SqlSummaryReport) String() string {
func (*PlanCheckRunResult_Result_SqlSummaryReport) ProtoMessage() {}
func (x *PlanCheckRunResult_Result_SqlSummaryReport) ProtoReflect() protoreflect.Message {
- mi := &file_store_plan_check_run_proto_msgTypes[8]
+ mi := &file_store_plan_check_run_proto_msgTypes[9]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -556,7 +667,7 @@ type PlanCheckRunResult_Result_SqlReviewReport struct {
func (x *PlanCheckRunResult_Result_SqlReviewReport) Reset() {
*x = PlanCheckRunResult_Result_SqlReviewReport{}
- mi := &file_store_plan_check_run_proto_msgTypes[9]
+ mi := &file_store_plan_check_run_proto_msgTypes[10]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -568,7 +679,7 @@ func (x *PlanCheckRunResult_Result_SqlReviewReport) String() string {
func (*PlanCheckRunResult_Result_SqlReviewReport) ProtoMessage() {}
func (x *PlanCheckRunResult_Result_SqlReviewReport) ProtoReflect() protoreflect.Message {
- mi := &file_store_plan_check_run_proto_msgTypes[9]
+ mi := &file_store_plan_check_run_proto_msgTypes[10]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -602,29 +713,32 @@ var File_store_plan_check_run_proto protoreflect.FileDescriptor
const file_store_plan_check_run_proto_rawDesc = "" +
"\n" +
- "\x1astore/plan_check_run.proto\x12\x0ebytebase.store\x1a\x12store/advice.proto\x1a\x12store/common.proto\"\x83\x03\n" +
- "\x12PlanCheckRunConfig\x12!\n" +
- "\fsheet_sha256\x18\x01 \x01(\tR\vsheetSha256\x12\x1f\n" +
- "\vinstance_id\x18\x02 \x01(\tR\n" +
- "instanceId\x12#\n" +
- "\rdatabase_name\x18\x03 \x01(\tR\fdatabaseName\x12S\n" +
- "\vghost_flags\x18\x04 \x03(\v22.bytebase.store.PlanCheckRunConfig.GhostFlagsEntryR\n" +
- "ghostFlags\x12.\n" +
- "\x13enable_prior_backup\x18\x05 \x01(\bR\x11enablePriorBackup\x12!\n" +
- "\fenable_ghost\x18\x06 \x01(\bR\venableGhost\x12\x1d\n" +
+ "\x1astore/plan_check_run.proto\x12\x0ebytebase.store\x1a\x12store/advice.proto\x1a\x12store/common.proto\"\xf0\x03\n" +
+ "\x12PlanCheckRunConfig\x12H\n" +
+ "\atargets\x18\x01 \x03(\v2..bytebase.store.PlanCheckRunConfig.CheckTargetR\atargets\x1a\x8f\x03\n" +
+ "\vCheckTarget\x12\x16\n" +
+ "\x06target\x18\x01 \x01(\tR\x06target\x12!\n" +
+ "\fsheet_sha256\x18\x02 \x01(\tR\vsheetSha256\x12.\n" +
+ "\x13enable_prior_backup\x18\x03 \x01(\bR\x11enablePriorBackup\x12!\n" +
+ "\fenable_ghost\x18\x04 \x01(\bR\venableGhost\x12\x1d\n" +
"\n" +
- "enable_sdl\x18\a \x01(\bR\tenableSdl\x1a=\n" +
+ "enable_sdl\x18\x05 \x01(\bR\tenableSdl\x12_\n" +
+ "\vghost_flags\x18\x06 \x03(\v2>.bytebase.store.PlanCheckRunConfig.CheckTarget.GhostFlagsEntryR\n" +
+ "ghostFlags\x123\n" +
+ "\x05types\x18\a \x03(\x0e2\x1d.bytebase.store.PlanCheckTypeR\x05types\x1a=\n" +
"\x0fGhostFlagsEntry\x12\x10\n" +
"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
- "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"\x98\x06\n" +
+ "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"\xe3\x06\n" +
"\x12PlanCheckRunResult\x12C\n" +
"\aresults\x18\x01 \x03(\v2).bytebase.store.PlanCheckRunResult.ResultR\aresults\x12\x14\n" +
- "\x05error\x18\x02 \x01(\tR\x05error\x1a\xa6\x05\n" +
+ "\x05error\x18\x02 \x01(\tR\x05error\x1a\xf1\x05\n" +
"\x06Result\x125\n" +
"\x06status\x18\x01 \x01(\x0e2\x1d.bytebase.store.Advice.StatusR\x06status\x12\x14\n" +
"\x05title\x18\x02 \x01(\tR\x05title\x12\x18\n" +
"\acontent\x18\x03 \x01(\tR\acontent\x12\x12\n" +
- "\x04code\x18\x04 \x01(\x05R\x04code\x12j\n" +
+ "\x04code\x18\x04 \x01(\x05R\x04code\x12\x16\n" +
+ "\x06target\x18\a \x01(\tR\x06target\x121\n" +
+ "\x04type\x18\b \x01(\x0e2\x1d.bytebase.store.PlanCheckTypeR\x04type\x12j\n" +
"\x12sql_summary_report\x18\x05 \x01(\v2:.bytebase.store.PlanCheckRunResult.Result.SqlSummaryReportH\x00R\x10sqlSummaryReport\x12g\n" +
"\x11sql_review_report\x18\x06 \x01(\v29.bytebase.store.PlanCheckRunResult.Result.SqlReviewReportH\x00R\x0fsqlReviewReport\x1a\xaf\x01\n" +
"\x10SqlSummaryReport\x12'\n" +
@@ -646,7 +760,12 @@ const file_store_plan_check_run_proto_rawDesc = "" +
"\x14ChangedResourceTable\x12\x12\n" +
"\x04name\x18\x01 \x01(\tR\x04name\x12\x1d\n" +
"\n" +
- "table_rows\x18\x02 \x01(\x03R\ttableRowsB\x94\x01\n" +
+ "table_rows\x18\x02 \x01(\x03R\ttableRows*\xa4\x01\n" +
+ "\rPlanCheckType\x12\x1f\n" +
+ "\x1bPLAN_CHECK_TYPE_UNSPECIFIED\x10\x00\x12$\n" +
+ " PLAN_CHECK_TYPE_STATEMENT_ADVISE\x10\x01\x12,\n" +
+ "(PLAN_CHECK_TYPE_STATEMENT_SUMMARY_REPORT\x10\x02\x12\x1e\n" +
+ "\x1aPLAN_CHECK_TYPE_GHOST_SYNC\x10\x03B\x94\x01\n" +
"\x12com.bytebase.storeB\x11PlanCheckRunProtoP\x01Z\x12generated-go/store\xa2\x02\x03BSX\xaa\x02\x0eBytebase.Store\xca\x02\x0eBytebase\\Store\xe2\x02\x1aBytebase\\Store\\GPBMetadata\xea\x02\x0fBytebase::Storeb\x06proto3"
var (
@@ -661,38 +780,44 @@ func file_store_plan_check_run_proto_rawDescGZIP() []byte {
return file_store_plan_check_run_proto_rawDescData
}
-var file_store_plan_check_run_proto_msgTypes = make([]protoimpl.MessageInfo, 10)
+var file_store_plan_check_run_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
+var file_store_plan_check_run_proto_msgTypes = make([]protoimpl.MessageInfo, 11)
var file_store_plan_check_run_proto_goTypes = []any{
- (*PlanCheckRunConfig)(nil), // 0: bytebase.store.PlanCheckRunConfig
- (*PlanCheckRunResult)(nil), // 1: bytebase.store.PlanCheckRunResult
- (*ChangedResources)(nil), // 2: bytebase.store.ChangedResources
- (*ChangedResourceDatabase)(nil), // 3: bytebase.store.ChangedResourceDatabase
- (*ChangedResourceSchema)(nil), // 4: bytebase.store.ChangedResourceSchema
- (*ChangedResourceTable)(nil), // 5: bytebase.store.ChangedResourceTable
- nil, // 6: bytebase.store.PlanCheckRunConfig.GhostFlagsEntry
- (*PlanCheckRunResult_Result)(nil), // 7: bytebase.store.PlanCheckRunResult.Result
- (*PlanCheckRunResult_Result_SqlSummaryReport)(nil), // 8: bytebase.store.PlanCheckRunResult.Result.SqlSummaryReport
- (*PlanCheckRunResult_Result_SqlReviewReport)(nil), // 9: bytebase.store.PlanCheckRunResult.Result.SqlReviewReport
- (Advice_Status)(0), // 10: bytebase.store.Advice.Status
- (*Position)(nil), // 11: bytebase.store.Position
+ (PlanCheckType)(0), // 0: bytebase.store.PlanCheckType
+ (*PlanCheckRunConfig)(nil), // 1: bytebase.store.PlanCheckRunConfig
+ (*PlanCheckRunResult)(nil), // 2: bytebase.store.PlanCheckRunResult
+ (*ChangedResources)(nil), // 3: bytebase.store.ChangedResources
+ (*ChangedResourceDatabase)(nil), // 4: bytebase.store.ChangedResourceDatabase
+ (*ChangedResourceSchema)(nil), // 5: bytebase.store.ChangedResourceSchema
+ (*ChangedResourceTable)(nil), // 6: bytebase.store.ChangedResourceTable
+ (*PlanCheckRunConfig_CheckTarget)(nil), // 7: bytebase.store.PlanCheckRunConfig.CheckTarget
+ nil, // 8: bytebase.store.PlanCheckRunConfig.CheckTarget.GhostFlagsEntry
+ (*PlanCheckRunResult_Result)(nil), // 9: bytebase.store.PlanCheckRunResult.Result
+ (*PlanCheckRunResult_Result_SqlSummaryReport)(nil), // 10: bytebase.store.PlanCheckRunResult.Result.SqlSummaryReport
+ (*PlanCheckRunResult_Result_SqlReviewReport)(nil), // 11: bytebase.store.PlanCheckRunResult.Result.SqlReviewReport
+ (Advice_Status)(0), // 12: bytebase.store.Advice.Status
+ (*Position)(nil), // 13: bytebase.store.Position
}
var file_store_plan_check_run_proto_depIdxs = []int32{
- 6, // 0: bytebase.store.PlanCheckRunConfig.ghost_flags:type_name -> bytebase.store.PlanCheckRunConfig.GhostFlagsEntry
- 7, // 1: bytebase.store.PlanCheckRunResult.results:type_name -> bytebase.store.PlanCheckRunResult.Result
- 3, // 2: bytebase.store.ChangedResources.databases:type_name -> bytebase.store.ChangedResourceDatabase
- 4, // 3: bytebase.store.ChangedResourceDatabase.schemas:type_name -> bytebase.store.ChangedResourceSchema
- 5, // 4: bytebase.store.ChangedResourceSchema.tables:type_name -> bytebase.store.ChangedResourceTable
- 10, // 5: bytebase.store.PlanCheckRunResult.Result.status:type_name -> bytebase.store.Advice.Status
- 8, // 6: bytebase.store.PlanCheckRunResult.Result.sql_summary_report:type_name -> bytebase.store.PlanCheckRunResult.Result.SqlSummaryReport
- 9, // 7: bytebase.store.PlanCheckRunResult.Result.sql_review_report:type_name -> bytebase.store.PlanCheckRunResult.Result.SqlReviewReport
- 2, // 8: bytebase.store.PlanCheckRunResult.Result.SqlSummaryReport.changed_resources:type_name -> bytebase.store.ChangedResources
- 11, // 9: bytebase.store.PlanCheckRunResult.Result.SqlReviewReport.start_position:type_name -> bytebase.store.Position
- 11, // 10: bytebase.store.PlanCheckRunResult.Result.SqlReviewReport.end_position:type_name -> bytebase.store.Position
- 11, // [11:11] is the sub-list for method output_type
- 11, // [11:11] is the sub-list for method input_type
- 11, // [11:11] is the sub-list for extension type_name
- 11, // [11:11] is the sub-list for extension extendee
- 0, // [0:11] is the sub-list for field type_name
+ 7, // 0: bytebase.store.PlanCheckRunConfig.targets:type_name -> bytebase.store.PlanCheckRunConfig.CheckTarget
+ 9, // 1: bytebase.store.PlanCheckRunResult.results:type_name -> bytebase.store.PlanCheckRunResult.Result
+ 4, // 2: bytebase.store.ChangedResources.databases:type_name -> bytebase.store.ChangedResourceDatabase
+ 5, // 3: bytebase.store.ChangedResourceDatabase.schemas:type_name -> bytebase.store.ChangedResourceSchema
+ 6, // 4: bytebase.store.ChangedResourceSchema.tables:type_name -> bytebase.store.ChangedResourceTable
+ 8, // 5: bytebase.store.PlanCheckRunConfig.CheckTarget.ghost_flags:type_name -> bytebase.store.PlanCheckRunConfig.CheckTarget.GhostFlagsEntry
+ 0, // 6: bytebase.store.PlanCheckRunConfig.CheckTarget.types:type_name -> bytebase.store.PlanCheckType
+ 12, // 7: bytebase.store.PlanCheckRunResult.Result.status:type_name -> bytebase.store.Advice.Status
+ 0, // 8: bytebase.store.PlanCheckRunResult.Result.type:type_name -> bytebase.store.PlanCheckType
+ 10, // 9: bytebase.store.PlanCheckRunResult.Result.sql_summary_report:type_name -> bytebase.store.PlanCheckRunResult.Result.SqlSummaryReport
+ 11, // 10: bytebase.store.PlanCheckRunResult.Result.sql_review_report:type_name -> bytebase.store.PlanCheckRunResult.Result.SqlReviewReport
+ 3, // 11: bytebase.store.PlanCheckRunResult.Result.SqlSummaryReport.changed_resources:type_name -> bytebase.store.ChangedResources
+ 13, // 12: bytebase.store.PlanCheckRunResult.Result.SqlReviewReport.start_position:type_name -> bytebase.store.Position
+ 13, // 13: bytebase.store.PlanCheckRunResult.Result.SqlReviewReport.end_position:type_name -> bytebase.store.Position
+ 14, // [14:14] is the sub-list for method output_type
+ 14, // [14:14] is the sub-list for method input_type
+ 14, // [14:14] is the sub-list for extension type_name
+ 14, // [14:14] is the sub-list for extension extendee
+ 0, // [0:14] is the sub-list for field type_name
}
func init() { file_store_plan_check_run_proto_init() }
@@ -702,7 +827,7 @@ func file_store_plan_check_run_proto_init() {
}
file_store_advice_proto_init()
file_store_common_proto_init()
- file_store_plan_check_run_proto_msgTypes[7].OneofWrappers = []any{
+ file_store_plan_check_run_proto_msgTypes[8].OneofWrappers = []any{
(*PlanCheckRunResult_Result_SqlSummaryReport_)(nil),
(*PlanCheckRunResult_Result_SqlReviewReport_)(nil),
}
@@ -711,13 +836,14 @@ func file_store_plan_check_run_proto_init() {
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_store_plan_check_run_proto_rawDesc), len(file_store_plan_check_run_proto_rawDesc)),
- NumEnums: 0,
- NumMessages: 10,
+ NumEnums: 1,
+ NumMessages: 11,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_store_plan_check_run_proto_goTypes,
DependencyIndexes: file_store_plan_check_run_proto_depIdxs,
+ EnumInfos: file_store_plan_check_run_proto_enumTypes,
MessageInfos: file_store_plan_check_run_proto_msgTypes,
}.Build()
File_store_plan_check_run_proto = out.File
diff --git a/backend/generated-go/store/plan_check_run_equal.pb.go b/backend/generated-go/store/plan_check_run_equal.pb.go
index 1da4844c8d..f409ee6826 100644
--- a/backend/generated-go/store/plan_check_run_equal.pb.go
+++ b/backend/generated-go/store/plan_check_run_equal.pb.go
@@ -3,20 +3,26 @@
package store
-func (x *PlanCheckRunConfig) Equal(y *PlanCheckRunConfig) bool {
+func (x *PlanCheckRunConfig_CheckTarget) Equal(y *PlanCheckRunConfig_CheckTarget) bool {
if x == y {
return true
}
if x == nil || y == nil {
return x == nil && y == nil
}
+ if x.Target != y.Target {
+ return false
+ }
if x.SheetSha256 != y.SheetSha256 {
return false
}
- if x.InstanceId != y.InstanceId {
+ if x.EnablePriorBackup != y.EnablePriorBackup {
+ return false
+ }
+ if x.EnableGhost != y.EnableGhost {
return false
}
- if x.DatabaseName != y.DatabaseName {
+ if x.EnableSdl != y.EnableSdl {
return false
}
if len(x.GhostFlags) != len(y.GhostFlags) {
@@ -31,15 +37,32 @@ func (x *PlanCheckRunConfig) Equal(y *PlanCheckRunConfig) bool {
return false
}
}
- if x.EnablePriorBackup != y.EnablePriorBackup {
+ if len(x.Types) != len(y.Types) {
return false
}
- if x.EnableGhost != y.EnableGhost {
- return false
+ for i := 0; i < len(x.Types); i++ {
+ if x.Types[i] != y.Types[i] {
+ return false
+ }
}
- if x.EnableSdl != y.EnableSdl {
+ return true
+}
+
+func (x *PlanCheckRunConfig) Equal(y *PlanCheckRunConfig) bool {
+ if x == y {
+ return true
+ }
+ if x == nil || y == nil {
+ return x == nil && y == nil
+ }
+ if len(x.Targets) != len(y.Targets) {
return false
}
+ for i := 0; i < len(x.Targets); i++ {
+ if !x.Targets[i].Equal(y.Targets[i]) {
+ return false
+ }
+ }
return true
}
@@ -102,6 +125,12 @@ func (x *PlanCheckRunResult_Result) Equal(y *PlanCheckRunResult_Result) bool {
if x.Code != y.Code {
return false
}
+ if x.Target != y.Target {
+ return false
+ }
+ if x.Type != y.Type {
+ return false
+ }
if !x.GetSqlSummaryReport().Equal(y.GetSqlSummaryReport()) {
return false
}
diff --git a/backend/migrator/migration/3.14/0006##consolidate_plan_check_runs.sql b/backend/migrator/migration/3.14/0006##consolidate_plan_check_runs.sql
new file mode 100644
index 0000000000..e60d420ee2
--- /dev/null
+++ b/backend/migrator/migration/3.14/0006##consolidate_plan_check_runs.sql
@@ -0,0 +1,87 @@
+-- Consolidate plan_check_run records: one record per plan instead of N×types
+
+-- Step 1: Create temp table with deduplicated latest records (last 30 days only)
+CREATE TEMP TABLE plan_check_run_deduped AS
+SELECT DISTINCT ON (plan_id, type, config->>'instanceId', config->>'databaseName')
+ id, plan_id, type, status, config, result, created_at, updated_at
+FROM plan_check_run
+WHERE created_at >= NOW() - INTERVAL '30 days'
+ AND status != 'CANCELED'
+ORDER BY plan_id, type, config->>'instanceId', config->>'databaseName', created_at DESC;
+
+-- Step 2: Drop type column first (no longer needed)
+ALTER TABLE plan_check_run DROP COLUMN type;
+
+-- Step 3: Delete all old records
+DELETE FROM plan_check_run;
+
+-- Step 4: Insert consolidated records (one per plan)
+INSERT INTO plan_check_run (plan_id, status, config, result, created_at, updated_at)
+SELECT
+ plan_id,
+ -- Status aggregation
+ CASE
+ WHEN bool_or(status = 'RUNNING') THEN 'RUNNING'
+ WHEN bool_or(status = 'FAILED') THEN 'FAILED'
+ ELSE 'DONE'
+ END,
+ -- Config: if any RUNNING, empty (will be re-run); otherwise aggregate
+ CASE
+ WHEN bool_or(status = 'RUNNING') THEN '{"targets": []}'::jsonb
+ ELSE jsonb_build_object('targets', (
+ SELECT jsonb_agg(target)
+ FROM (
+ SELECT jsonb_build_object(
+ 'target', 'instances/' || (d2.config->>'instanceId') || '/databases/' || (d2.config->>'databaseName'),
+ 'sheetSha256', d2.config->>'sheetSha256',
+ 'enablePriorBackup', COALESCE((d2.config->>'enablePriorBackup')::boolean, false),
+ 'enableGhost', COALESCE((d2.config->>'enableGhost')::boolean, false),
+ 'enableSdl', COALESCE((d2.config->>'enableSdl')::boolean, false),
+ 'ghostFlags', COALESCE(d2.config->'ghostFlags', '{}'::jsonb),
+ 'types', array_agg(
+ CASE d2.type
+ WHEN 'bb.plan-check.database.statement.advise' THEN 'PLAN_CHECK_TYPE_STATEMENT_ADVISE'
+ WHEN 'bb.plan-check.database.statement.summary.report' THEN 'PLAN_CHECK_TYPE_STATEMENT_SUMMARY_REPORT'
+ WHEN 'bb.plan-check.database.ghost.sync' THEN 'PLAN_CHECK_TYPE_GHOST_SYNC'
+ END
+ )
+ ) as target
+ FROM plan_check_run_deduped d2
+ WHERE d2.plan_id = d.plan_id
+ GROUP BY
+ d2.config->>'instanceId',
+ d2.config->>'databaseName',
+ d2.config->>'sheetSha256',
+ d2.config->>'enablePriorBackup',
+ d2.config->>'enableGhost',
+ d2.config->>'enableSdl',
+ d2.config->'ghostFlags'
+ ) targets
+ ))
+ END,
+ -- Results: empty if RUNNING, otherwise aggregate with type tagging
+ CASE
+ WHEN bool_or(status = 'RUNNING') THEN '{"results": []}'::jsonb
+ ELSE jsonb_build_object('results', (
+ SELECT COALESCE(jsonb_agg(
+ r || jsonb_build_object(
+ 'target', 'instances/' || (d3.config->>'instanceId') || '/databases/' || (d3.config->>'databaseName'),
+ 'type', CASE d3.type
+ WHEN 'bb.plan-check.database.statement.advise' THEN 'PLAN_CHECK_TYPE_STATEMENT_ADVISE'
+ WHEN 'bb.plan-check.database.statement.summary.report' THEN 'PLAN_CHECK_TYPE_STATEMENT_SUMMARY_REPORT'
+ WHEN 'bb.plan-check.database.ghost.sync' THEN 'PLAN_CHECK_TYPE_GHOST_SYNC'
+ END
+ )
+ ), '[]'::jsonb)
+ FROM plan_check_run_deduped d3
+ LEFT JOIN LATERAL jsonb_array_elements(d3.result->'results') r ON true
+ WHERE d3.plan_id = d.plan_id
+ ))
+ END,
+ MAX(created_at),
+ MAX(updated_at)
+FROM plan_check_run_deduped d
+GROUP BY plan_id;
+
+-- Step 5: Cleanup temp table
+DROP TABLE plan_check_run_deduped;
diff --git a/backend/migrator/migration/LATEST.sql b/backend/migrator/migration/LATEST.sql
index e8ae780cf9..881aff182b 100644
--- a/backend/migrator/migration/LATEST.sql
+++ b/backend/migrator/migration/LATEST.sql
@@ -289,7 +289,6 @@ CREATE TABLE plan_check_run (
updated_at timestamptz NOT NULL DEFAULT now(),
plan_id bigint NOT NULL REFERENCES plan(id),
status text NOT NULL CHECK (status IN ('RUNNING', 'DONE', 'FAILED', 'CANCELED')),
- type text NOT NULL CHECK (type LIKE 'bb.plan-check.%'),
-- Stored as PlanCheckRunConfig (proto/store/store/plan_check_run.proto)
config jsonb NOT NULL DEFAULT '{}',
-- Stored as PlanCheckRunResult (proto/store/store/plan_check_run.proto)
diff --git a/backend/migrator/migrator_test.go b/backend/migrator/migrator_test.go
index 077562ba8b..8e362aa1ae 100644
--- a/backend/migrator/migrator_test.go
+++ b/backend/migrator/migrator_test.go
@@ -12,7 +12,7 @@ import (
func TestLatestVersion(t *testing.T) {
files, err := getSortedVersionedFiles()
require.NoError(t, err)
- require.Equal(t, semver.MustParse("3.14.5"), *files[len(files)-1].version)
+ require.Equal(t, semver.MustParse("3.14.6"), *files[len(files)-1].version)
}
func TestVersionUnique(t *testing.T) {
diff --git a/backend/runner/approval/runner.go b/backend/runner/approval/runner.go
index e8f822e5d7..f9d6387a42 100644
--- a/backend/runner/approval/runner.go
+++ b/backend/runner/approval/runner.go
@@ -444,41 +444,39 @@ func (r *Runner) buildCELVariablesForDatabaseChange(ctx context.Context, issue *
return nil, false, errors.Errorf("plan %v not found", *issue.PlanUID)
}
- // Check plan check runs status
- planCheckRuns, err := r.store.ListPlanCheckRuns(ctx, &store.FindPlanCheckRunMessage{
- PlanUID: &plan.UID,
- Type: &[]store.PlanCheckRunType{store.PlanCheckDatabaseStatementSummaryReport},
- })
+ // Check plan check run status (consolidated model: one run per plan)
+ planCheckRun, err := r.store.GetPlanCheckRun(ctx, plan.UID)
if err != nil {
- return nil, false, errors.Wrapf(err, "failed to list plan check runs for plan %v", plan.UID)
+ return nil, false, errors.Wrapf(err, "failed to get plan check run for plan %v", plan.UID)
}
type Key struct {
InstanceID string
DatabaseName string
}
- latestPlanCheckRun := map[Key]*store.PlanCheckRunMessage{}
- for _, run := range planCheckRuns {
- key := Key{
- InstanceID: run.Config.InstanceId,
- DatabaseName: run.Config.DatabaseName,
- }
- latestPlanCheckRun[key] = run
- }
+ latestPlanCheckRun := map[Key]*storepb.PlanCheckRunResult_Result{}
- // Wait for plan check runs to complete
- var planCheckRunDone int
- for _, run := range latestPlanCheckRun {
- if run.Status != store.PlanCheckRunStatusRunning {
- planCheckRunDone++
- }
- }
- planCheckRunCount := len(latestPlanCheckRun)
- if planCheckRunCount < common.MinimumCompletedPlanCheckRun && planCheckRunCount != planCheckRunDone {
+ // Wait for plan check to complete if running
+ if planCheckRun != nil && planCheckRun.Status == store.PlanCheckRunStatusRunning {
return nil, false, nil // Not ready yet, retry later
}
- if planCheckRunCount >= common.MinimumCompletedPlanCheckRun && planCheckRunDone < common.MinimumCompletedPlanCheckRun {
- return nil, false, nil // Not ready yet, retry later
+
+ // Build map from results, filtering for STATEMENT_SUMMARY_REPORT
+ if planCheckRun != nil {
+ for _, result := range planCheckRun.Result.Results {
+ if result.Type != storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_SUMMARY_REPORT {
+ continue
+ }
+ instanceID, databaseName, err := common.GetInstanceDatabaseID(result.Target)
+ if err != nil {
+ continue
+ }
+ key := Key{
+ InstanceID: instanceID,
+ DatabaseName: databaseName,
+ }
+ latestPlanCheckRun[key] = result
+ }
}
// Build CEL variables for each task
@@ -542,7 +540,7 @@ func (r *Runner) buildCELVariablesForDatabaseChange(ctx context.Context, issue *
}
// Add summary report data if available
- run, ok := latestPlanCheckRun[Key{
+ result, ok := latestPlanCheckRun[Key{
InstanceID: instance.ResourceID,
DatabaseName: databaseName,
}]
@@ -551,7 +549,7 @@ func (r *Runner) buildCELVariablesForDatabaseChange(ctx context.Context, issue *
continue
}
- report := findSQLSummaryReport(run.Result.Results)
+ report := result.GetSqlSummaryReport()
if report == nil {
celVarsList = append(celVarsList, celVars)
continue
@@ -793,15 +791,6 @@ func updateIssueApprovalPayload(ctx context.Context, s *store.Store, issue *stor
return nil
}
-func findSQLSummaryReport(results []*storepb.PlanCheckRunResult_Result) *storepb.PlanCheckRunResult_Result_SqlSummaryReport {
- for _, result := range results {
- if report := result.GetSqlSummaryReport(); report != nil {
- return report
- }
- }
- return nil
-}
-
// expandCELVars creates CEL variable maps for each combination of statement types and table names.
func expandCELVars(base map[string]any, statementTypes, tableNames []string) []map[string]any {
if len(statementTypes) == 0 {
diff --git a/backend/runner/plancheck/executor.go b/backend/runner/plancheck/executor.go
index cd658b6676..919c9a4300 100644
--- a/backend/runner/plancheck/executor.go
+++ b/backend/runner/plancheck/executor.go
@@ -2,29 +2,10 @@ package plancheck
import (
"context"
- "log/slog"
- "github.com/pkg/errors"
-
- "github.com/bytebase/bytebase/backend/common/log"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
)
-func runExecutorOnce(ctx context.Context, exec Executor, config *storepb.PlanCheckRunConfig) (results []*storepb.PlanCheckRunResult_Result, err error) {
- defer func() {
- if r := recover(); r != nil {
- panicErr, ok := r.(error)
- if !ok {
- panicErr = errors.Errorf("%v", r)
- }
- slog.Error("planCheckExecutor PANIC RECOVER", log.BBError(panicErr), log.BBStack("panic-stack"))
- err = errors.Errorf("planCheckExecutor PANIC RECOVER, err: %v", panicErr)
- }
- }()
-
- return exec.Run(ctx, config)
-}
-
// Executor is the plan check executor.
type Executor interface {
// Run will be called periodically by the plan check scheduler
diff --git a/backend/runner/plancheck/executor_combined.go b/backend/runner/plancheck/executor_combined.go
new file mode 100644
index 0000000000..71c97fd784
--- /dev/null
+++ b/backend/runner/plancheck/executor_combined.go
@@ -0,0 +1,106 @@
+package plancheck
+
+import (
+ "context"
+
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/component/dbfactory"
+ "github.com/bytebase/bytebase/backend/component/sheet"
+ "github.com/bytebase/bytebase/backend/enterprise"
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ "github.com/bytebase/bytebase/backend/store"
+)
+
+// CombinedExecutor processes all plan check types for a consolidated plan check run.
+type CombinedExecutor struct {
+ store *store.Store
+ sheetManager *sheet.Manager
+ dbFactory *dbfactory.DBFactory
+ licenseService *enterprise.LicenseService
+}
+
+// NewCombinedExecutor creates a combined executor.
+func NewCombinedExecutor(
+ store *store.Store,
+ sheetManager *sheet.Manager,
+ dbFactory *dbfactory.DBFactory,
+ licenseService *enterprise.LicenseService,
+) *CombinedExecutor {
+ return &CombinedExecutor{
+ store: store,
+ sheetManager: sheetManager,
+ dbFactory: dbFactory,
+ licenseService: licenseService,
+ }
+}
+
+// Run runs all checks for a consolidated config.
+func (e *CombinedExecutor) Run(ctx context.Context, config *storepb.PlanCheckRunConfig) ([]*storepb.PlanCheckRunResult_Result, error) {
+ var allResults []*storepb.PlanCheckRunResult_Result
+
+ for _, target := range config.Targets {
+ for _, checkType := range target.Types {
+ results, err := e.runCheck(ctx, target, checkType)
+ if err != nil {
+ // Add error result for this target/type, continue to next
+ allResults = append(allResults, &storepb.PlanCheckRunResult_Result{
+ Status: storepb.Advice_ERROR,
+ Target: target.Target,
+ Type: checkType,
+ Title: "Check failed",
+ Content: err.Error(),
+ Code: common.Internal.Int32(),
+ })
+ continue
+ }
+ // Tag results with target info
+ for _, r := range results {
+ r.Target = target.Target
+ r.Type = checkType
+ }
+ allResults = append(allResults, results...)
+ }
+ }
+
+ return allResults, nil
+}
+
+func (e *CombinedExecutor) runCheck(ctx context.Context, target *storepb.PlanCheckRunConfig_CheckTarget, checkType storepb.PlanCheckType) ([]*storepb.PlanCheckRunResult_Result, error) {
+ switch checkType {
+ case storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_ADVISE:
+ return e.runStatementAdvise(ctx, target)
+ case storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_SUMMARY_REPORT:
+ return e.runStatementReport(ctx, target)
+ case storepb.PlanCheckType_PLAN_CHECK_TYPE_GHOST_SYNC:
+ return e.runGhostSync(ctx, target)
+ default:
+ return nil, nil
+ }
+}
+
+func (e *CombinedExecutor) runStatementAdvise(ctx context.Context, target *storepb.PlanCheckRunConfig_CheckTarget) ([]*storepb.PlanCheckRunResult_Result, error) {
+ executor := &StatementAdviseExecutor{
+ store: e.store,
+ sheetManager: e.sheetManager,
+ dbFactory: e.dbFactory,
+ licenseService: e.licenseService,
+ }
+ return executor.RunForTarget(ctx, target)
+}
+
+func (e *CombinedExecutor) runStatementReport(ctx context.Context, target *storepb.PlanCheckRunConfig_CheckTarget) ([]*storepb.PlanCheckRunResult_Result, error) {
+ executor := &StatementReportExecutor{
+ store: e.store,
+ sheetManager: e.sheetManager,
+ dbFactory: e.dbFactory,
+ }
+ return executor.RunForTarget(ctx, target)
+}
+
+func (e *CombinedExecutor) runGhostSync(ctx context.Context, target *storepb.PlanCheckRunConfig_CheckTarget) ([]*storepb.PlanCheckRunResult_Result, error) {
+ executor := &GhostSyncExecutor{
+ store: e.store,
+ dbFactory: e.dbFactory,
+ }
+ return executor.RunForTarget(ctx, target)
+}
diff --git a/backend/runner/plancheck/ghost_sync_executor.go b/backend/runner/plancheck/ghost_sync_executor.go
index 4b289890f6..11c4ecce25 100644
--- a/backend/runner/plancheck/ghost_sync_executor.go
+++ b/backend/runner/plancheck/ghost_sync_executor.go
@@ -37,8 +37,8 @@ type GhostSyncExecutor struct {
dbFactory *dbfactory.DBFactory
}
-// Run runs the gh-ost sync check executor.
-func (e *GhostSyncExecutor) Run(ctx context.Context, config *storepb.PlanCheckRunConfig) (results []*storepb.PlanCheckRunResult_Result, err error) {
+// RunForTarget runs the gh-ost sync check for a single target.
+func (e *GhostSyncExecutor) RunForTarget(ctx context.Context, target *storepb.PlanCheckRunConfig_CheckTarget) (results []*storepb.PlanCheckRunResult_Result, err error) {
// gh-ost dry run could panic.
// It may be bytebase who panicked, but that's rare. So
// capture the error and send it into the result list.
@@ -62,20 +62,25 @@ func (e *GhostSyncExecutor) Run(ctx context.Context, config *storepb.PlanCheckRu
}
}()
- instance, err := e.store.GetInstance(ctx, &store.FindInstanceMessage{ResourceID: &config.InstanceId})
+ instanceID, databaseName, err := common.GetInstanceDatabaseID(target.Target)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to parse target %s", target.Target)
+ }
+
+ instance, err := e.store.GetInstance(ctx, &store.FindInstanceMessage{ResourceID: &instanceID})
if err != nil {
- return nil, errors.Wrapf(err, "failed to get instance %s", config.InstanceId)
+ return nil, errors.Wrapf(err, "failed to get instance %s", instanceID)
}
if instance == nil {
- return nil, errors.Errorf("instance %s not found", config.InstanceId)
+ return nil, errors.Errorf("instance %s not found", instanceID)
}
- database, err := e.store.GetDatabase(ctx, &store.FindDatabaseMessage{InstanceID: &instance.ResourceID, DatabaseName: &config.DatabaseName})
+ database, err := e.store.GetDatabase(ctx, &store.FindDatabaseMessage{InstanceID: &instance.ResourceID, DatabaseName: &databaseName})
if err != nil {
- return nil, errors.Wrapf(err, "failed to get database %q", config.DatabaseName)
+ return nil, errors.Wrapf(err, "failed to get database %q", databaseName)
}
if database == nil {
- return nil, errors.Errorf("database not found %q", config.DatabaseName)
+ return nil, errors.Errorf("database not found %q", databaseName)
}
adminDataSource := utils.DataSourceFromInstanceWithType(instance, storepb.DataSourceType_ADMIN)
@@ -83,12 +88,12 @@ func (e *GhostSyncExecutor) Run(ctx context.Context, config *storepb.PlanCheckRu
return nil, common.Errorf(common.Internal, "admin data source not found for instance %s", instance.ResourceID)
}
- sheet, err := e.store.GetSheetFull(ctx, config.SheetSha256)
+ sheet, err := e.store.GetSheetFull(ctx, target.SheetSha256)
if err != nil {
- return nil, errors.Wrapf(err, "failed to get sheet %s", config.SheetSha256)
+ return nil, errors.Wrapf(err, "failed to get sheet %s", target.SheetSha256)
}
if sheet == nil {
- return nil, errors.Errorf("sheet %s not found", config.SheetSha256)
+ return nil, errors.Errorf("sheet %s not found", target.SheetSha256)
}
statement := sheet.Statement
@@ -131,7 +136,7 @@ func (e *GhostSyncExecutor) Run(ctx context.Context, config *storepb.PlanCheckRu
}, nil
}
- migrationContext, err := ghost.NewMigrationContext(ctx, rand.Intn(10000000), database, adminDataSource, tableName, fmt.Sprintf("_dryrun_%d", time.Now().Unix()), statement, true, config.GhostFlags, 20000000)
+ migrationContext, err := ghost.NewMigrationContext(ctx, rand.Intn(10000000), database, adminDataSource, tableName, fmt.Sprintf("_dryrun_%d", time.Now().Unix()), statement, true, target.GhostFlags, 20000000)
if err != nil {
return nil, common.Wrapf(err, common.Internal, "failed to create migration context")
}
@@ -195,3 +200,13 @@ func (e *GhostSyncExecutor) Run(ctx context.Context, config *storepb.PlanCheckRu
},
}, nil
}
+
+// Run runs the gh-ost sync check executor.
+//
+// Deprecated: Use RunForTarget instead. This method is kept for backward compatibility.
+func (e *GhostSyncExecutor) Run(ctx context.Context, config *storepb.PlanCheckRunConfig) (results []*storepb.PlanCheckRunResult_Result, err error) {
+ if len(config.Targets) == 0 {
+ return nil, nil
+ }
+ return e.RunForTarget(ctx, config.Targets[0])
+}
diff --git a/backend/runner/plancheck/scheduler.go b/backend/runner/plancheck/scheduler.go
index 0e1b37c7a8..4b5d724de2 100644
--- a/backend/runner/plancheck/scheduler.go
+++ b/backend/runner/plancheck/scheduler.go
@@ -22,12 +22,12 @@ const (
)
// NewScheduler creates a new plan check scheduler.
-func NewScheduler(s *store.Store, licenseService *enterprise.LicenseService, stateCfg *state.State) *Scheduler {
+func NewScheduler(s *store.Store, licenseService *enterprise.LicenseService, stateCfg *state.State, executor *CombinedExecutor) *Scheduler {
return &Scheduler{
store: s,
licenseService: licenseService,
stateCfg: stateCfg,
- executors: make(map[store.PlanCheckRunType]Executor),
+ executor: executor,
}
}
@@ -36,7 +36,7 @@ type Scheduler struct {
store *store.Store
licenseService *enterprise.LicenseService
stateCfg *state.State
- executors map[store.PlanCheckRunType]Executor
+ executor *CombinedExecutor
}
// Run runs the scheduler.
@@ -57,17 +57,6 @@ func (s *Scheduler) Run(ctx context.Context, wg *sync.WaitGroup) {
}
}
-// Register registers a plan check executor.
-func (s *Scheduler) Register(planCheckRunType store.PlanCheckRunType, executor Executor) {
- if executor == nil {
- panic("plan check scheduler: Register executor is nil for plan check run type: " + planCheckRunType)
- }
- if _, dup := s.executors[planCheckRunType]; dup {
- panic("plan check scheduler: Register called twice for plan check run type: " + planCheckRunType)
- }
- s.executors[planCheckRunType] = executor
-}
-
func (s *Scheduler) runOnce(ctx context.Context) {
defer func() {
if r := recover(); r != nil {
@@ -95,11 +84,6 @@ func (s *Scheduler) runOnce(ctx context.Context) {
}
func (s *Scheduler) runPlanCheckRun(ctx context.Context, planCheckRun *store.PlanCheckRunMessage) {
- executor, ok := s.executors[planCheckRun.Type]
- if !ok {
- slog.Error("Skip running plan check for unknown type", slog.Int("uid", planCheckRun.UID), slog.Int64("plan_uid", planCheckRun.PlanUID), slog.String("type", string(planCheckRun.Type)))
- return
- }
// Skip the plan check run if it is already running.
if _, ok := s.stateCfg.RunningPlanChecks.Load(planCheckRun.UID); ok {
return
@@ -116,7 +100,7 @@ func (s *Scheduler) runPlanCheckRun(ctx context.Context, planCheckRun *store.Pla
defer cancel()
s.stateCfg.RunningPlanCheckRunsCancelFunc.Store(planCheckRun.UID, cancel)
- results, err := runExecutorOnce(ctxWithCancel, executor, planCheckRun.Config)
+ results, err := s.executor.Run(ctxWithCancel, planCheckRun.Config)
if err != nil {
if errors.Is(err, context.Canceled) {
s.markPlanCheckRunCanceled(ctx, planCheckRun, err.Error())
diff --git a/backend/runner/plancheck/statement_advise_executor.go b/backend/runner/plancheck/statement_advise_executor.go
index 05ffa20e46..8c06c545cd 100644
--- a/backend/runner/plancheck/statement_advise_executor.go
+++ b/backend/runner/plancheck/statement_advise_executor.go
@@ -43,14 +43,14 @@ type StatementAdviseExecutor struct {
licenseService *enterprise.LicenseService
}
-// Run will run the plan check statement advise executor once, and run its sub-advisors one-by-one.
-func (e *StatementAdviseExecutor) Run(ctx context.Context, config *storepb.PlanCheckRunConfig) ([]*storepb.PlanCheckRunResult_Result, error) {
- fullSheet, err := e.store.GetSheetFull(ctx, config.SheetSha256)
+// RunForTarget runs the statement advise check for a single target.
+func (e *StatementAdviseExecutor) RunForTarget(ctx context.Context, target *storepb.PlanCheckRunConfig_CheckTarget) ([]*storepb.PlanCheckRunResult_Result, error) {
+ fullSheet, err := e.store.GetSheetFull(ctx, target.SheetSha256)
if err != nil {
return nil, err
}
if fullSheet == nil {
- return nil, errors.Errorf("sheet full %s not found", config.SheetSha256)
+ return nil, errors.Errorf("sheet full %s not found", target.SheetSha256)
}
if fullSheet.Size > common.MaxSheetCheckSize {
return []*storepb.PlanCheckRunResult_Result{
@@ -62,16 +62,21 @@ func (e *StatementAdviseExecutor) Run(ctx context.Context, config *storepb.PlanC
},
}, nil
}
- enablePriorBackup := config.EnablePriorBackup
- enableGhost := config.EnableGhost
- enableSDL := config.EnableSdl
+ enablePriorBackup := target.EnablePriorBackup
+ enableGhost := target.EnableGhost
+ enableSDL := target.EnableSdl
+
+ instanceID, databaseName, err := common.GetInstanceDatabaseID(target.Target)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to parse target %s", target.Target)
+ }
- instance, err := e.store.GetInstance(ctx, &store.FindInstanceMessage{ResourceID: &config.InstanceId})
+ instance, err := e.store.GetInstance(ctx, &store.FindInstanceMessage{ResourceID: &instanceID})
if err != nil {
- return nil, errors.Wrapf(err, "failed to get instance %s", config.InstanceId)
+ return nil, errors.Wrapf(err, "failed to get instance %s", instanceID)
}
if instance == nil {
- return nil, errors.Errorf("instance %s not found", config.InstanceId)
+ return nil, errors.Errorf("instance %s not found", instanceID)
}
if !common.EngineSupportStatementAdvise(instance.Metadata.GetEngine()) {
return []*storepb.PlanCheckRunResult_Result{
@@ -84,12 +89,12 @@ func (e *StatementAdviseExecutor) Run(ctx context.Context, config *storepb.PlanC
}, nil
}
- database, err := e.store.GetDatabase(ctx, &store.FindDatabaseMessage{InstanceID: &instance.ResourceID, DatabaseName: &config.DatabaseName})
+ database, err := e.store.GetDatabase(ctx, &store.FindDatabaseMessage{InstanceID: &instance.ResourceID, DatabaseName: &databaseName})
if err != nil {
- return nil, errors.Wrapf(err, "failed to get database %q", config.DatabaseName)
+ return nil, errors.Wrapf(err, "failed to get database %q", databaseName)
}
if database == nil {
- return nil, errors.Errorf("database not found %q", config.DatabaseName)
+ return nil, errors.Errorf("database not found %q", databaseName)
}
results, err := e.runReview(ctx, instance, database, fullSheet.Statement, enablePriorBackup, enableGhost, enableSDL)
@@ -111,6 +116,16 @@ func (e *StatementAdviseExecutor) Run(ctx context.Context, config *storepb.PlanC
return results, nil
}
+// Run will run the plan check statement advise executor once, and run its sub-advisors one-by-one.
+//
+// Deprecated: Use RunForTarget instead. This method is kept for backward compatibility.
+func (e *StatementAdviseExecutor) Run(ctx context.Context, config *storepb.PlanCheckRunConfig) ([]*storepb.PlanCheckRunResult_Result, error) {
+ if len(config.Targets) == 0 {
+ return nil, nil
+ }
+ return e.RunForTarget(ctx, config.Targets[0])
+}
+
func (e *StatementAdviseExecutor) runReview(
ctx context.Context,
instance *store.InstanceMessage,
diff --git a/backend/runner/plancheck/statement_report_executor.go b/backend/runner/plancheck/statement_report_executor.go
index 91041c495c..f4653a617f 100644
--- a/backend/runner/plancheck/statement_report_executor.go
+++ b/backend/runner/plancheck/statement_report_executor.go
@@ -46,14 +46,14 @@ type StatementReportExecutor struct {
dbFactory *dbfactory.DBFactory
}
-// Run runs the statement report executor.
-func (e *StatementReportExecutor) Run(ctx context.Context, config *storepb.PlanCheckRunConfig) ([]*storepb.PlanCheckRunResult_Result, error) {
- fullSheet, err := e.store.GetSheetFull(ctx, config.SheetSha256)
+// RunForTarget runs the statement report check for a single target.
+func (e *StatementReportExecutor) RunForTarget(ctx context.Context, target *storepb.PlanCheckRunConfig_CheckTarget) ([]*storepb.PlanCheckRunResult_Result, error) {
+ fullSheet, err := e.store.GetSheetFull(ctx, target.SheetSha256)
if err != nil {
return nil, err
}
if fullSheet == nil {
- return nil, errors.Errorf("sheet full %s not found", config.SheetSha256)
+ return nil, errors.Errorf("sheet full %s not found", target.SheetSha256)
}
if fullSheet.Size > common.MaxSheetCheckSize {
return []*storepb.PlanCheckRunResult_Result{
@@ -66,12 +66,17 @@ func (e *StatementReportExecutor) Run(ctx context.Context, config *storepb.PlanC
}, nil
}
- instance, err := e.store.GetInstance(ctx, &store.FindInstanceMessage{ResourceID: &config.InstanceId})
+ instanceID, databaseName, err := common.GetInstanceDatabaseID(target.Target)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to parse target %s", target.Target)
+ }
+
+ instance, err := e.store.GetInstance(ctx, &store.FindInstanceMessage{ResourceID: &instanceID})
if err != nil {
- return nil, errors.Wrapf(err, "failed to get instance %v", config.InstanceId)
+ return nil, errors.Wrapf(err, "failed to get instance %v", instanceID)
}
if instance == nil {
- return nil, errors.Errorf("instance %s not found", config.InstanceId)
+ return nil, errors.Errorf("instance %s not found", instanceID)
}
if !common.EngineSupportStatementReport(instance.Metadata.GetEngine()) {
return []*storepb.PlanCheckRunResult_Result{
@@ -84,12 +89,12 @@ func (e *StatementReportExecutor) Run(ctx context.Context, config *storepb.PlanC
}, nil
}
- database, err := e.store.GetDatabase(ctx, &store.FindDatabaseMessage{InstanceID: &instance.ResourceID, DatabaseName: &config.DatabaseName})
+ database, err := e.store.GetDatabase(ctx, &store.FindDatabaseMessage{InstanceID: &instance.ResourceID, DatabaseName: &databaseName})
if err != nil {
- return nil, errors.Wrapf(err, "failed to get database %q", config.DatabaseName)
+ return nil, errors.Wrapf(err, "failed to get database %q", databaseName)
}
if database == nil {
- return nil, errors.Errorf("database not found %q", config.DatabaseName)
+ return nil, errors.Errorf("database not found %q", databaseName)
}
// Check statement syntax error.
@@ -129,6 +134,16 @@ func (e *StatementReportExecutor) Run(ctx context.Context, config *storepb.PlanC
return []*storepb.PlanCheckRunResult_Result{planCheckRunResult}, nil
}
+// Run runs the statement report executor.
+//
+// Deprecated: Use RunForTarget instead. This method is kept for backward compatibility.
+func (e *StatementReportExecutor) Run(ctx context.Context, config *storepb.PlanCheckRunConfig) ([]*storepb.PlanCheckRunResult_Result, error) {
+ if len(config.Targets) == 0 {
+ return nil, nil
+ }
+ return e.RunForTarget(ctx, config.Targets[0])
+}
+
// 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, &store.FindDBSchemaMessage{
diff --git a/backend/runner/taskrun/auto_rollout_scheduler.go b/backend/runner/taskrun/auto_rollout_scheduler.go
index b7c05b87b6..f599af7457 100644
--- a/backend/runner/taskrun/auto_rollout_scheduler.go
+++ b/backend/runner/taskrun/auto_rollout_scheduler.go
@@ -127,21 +127,20 @@ func (s *Scheduler) scheduleAutoRolloutTask(ctx context.Context, taskUID int) er
if plan == nil {
return true, nil
}
- latestRuns, err := s.store.ListPlanCheckRuns(ctx, &store.FindPlanCheckRunMessage{
- PlanUID: &plan.UID,
- })
+ planCheckRun, err := s.store.GetPlanCheckRun(ctx, plan.UID)
if err != nil {
- return false, errors.Wrapf(err, "failed to list latest plan check runs")
+ return false, errors.Wrapf(err, "failed to get plan check run")
}
- for _, run := range latestRuns {
- if run.Status != store.PlanCheckRunStatusDone {
+ if planCheckRun == nil {
+ return true, nil // No checks configured
+ }
+ if planCheckRun.Status != store.PlanCheckRunStatusDone {
+ return false, nil
+ }
+ for _, result := range planCheckRun.Result.Results {
+ if result.Status == storepb.Advice_ERROR {
return false, nil
}
- for _, result := range run.Result.Results {
- if result.Status == storepb.Advice_ERROR {
- return false, nil
- }
- }
}
return true, nil
}()
diff --git a/backend/server/server.go b/backend/server/server.go
index fcb49bea97..cf29f8760f 100644
--- a/backend/server/server.go
+++ b/backend/server/server.go
@@ -193,13 +193,8 @@ func NewServer(ctx context.Context, profile *config.Profile) (*Server, error) {
s.taskScheduler.Register(storepb.Task_DATABASE_EXPORT, taskrun.NewDataExportExecutor(stores, s.dbFactory, s.licenseService, s.stateCfg, s.schemaSyncer, profile))
s.taskScheduler.Register(storepb.Task_DATABASE_SDL, taskrun.NewSchemaDeclareExecutor(stores, s.dbFactory, s.licenseService, s.stateCfg, s.schemaSyncer, profile))
- s.planCheckScheduler = plancheck.NewScheduler(stores, s.licenseService, s.stateCfg)
- statementAdviseExecutor := plancheck.NewStatementAdviseExecutor(stores, sheetManager, s.dbFactory, s.licenseService)
- s.planCheckScheduler.Register(store.PlanCheckDatabaseStatementAdvise, statementAdviseExecutor)
- ghostSyncExecutor := plancheck.NewGhostSyncExecutor(stores, s.dbFactory)
- s.planCheckScheduler.Register(store.PlanCheckDatabaseGhostSync, ghostSyncExecutor)
- statementReportExecutor := plancheck.NewStatementReportExecutor(stores, sheetManager, s.dbFactory)
- s.planCheckScheduler.Register(store.PlanCheckDatabaseStatementSummaryReport, statementReportExecutor)
+ combinedExecutor := plancheck.NewCombinedExecutor(stores, sheetManager, s.dbFactory, s.licenseService)
+ s.planCheckScheduler = plancheck.NewScheduler(stores, s.licenseService, s.stateCfg, combinedExecutor)
// Data cleaner
s.dataCleaner = cleaner.NewDataCleaner(stores)
diff --git a/backend/store/plan_check_run.go b/backend/store/plan_check_run.go
index 286a200245..ffd983f08f 100644
--- a/backend/store/plan_check_run.go
+++ b/backend/store/plan_check_run.go
@@ -12,18 +12,6 @@ import (
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
)
-// PlanCheckRunType is the type of a plan check run.
-type PlanCheckRunType string
-
-const (
- // PlanCheckDatabaseStatementAdvise is the plan check type for schema system review policy.
- PlanCheckDatabaseStatementAdvise PlanCheckRunType = "bb.plan-check.database.statement.advise"
- // PlanCheckDatabaseStatementSummaryReport is the plan check type for statement summary report.
- PlanCheckDatabaseStatementSummaryReport PlanCheckRunType = "bb.plan-check.database.statement.summary.report"
- // PlanCheckDatabaseGhostSync is the plan check type for the gh-ost sync task.
- PlanCheckDatabaseGhostSync PlanCheckRunType = "bb.plan-check.database.ghost.sync"
-)
-
// PlanCheckRunStatus is the status of a plan check run.
type PlanCheckRunStatus string
@@ -47,7 +35,6 @@ type PlanCheckRunMessage struct {
PlanUID int64
Status PlanCheckRunStatus
- Type PlanCheckRunType
Config *storepb.PlanCheckRunConfig
Result *storepb.PlanCheckRunResult
}
@@ -57,7 +44,6 @@ type FindPlanCheckRunMessage struct {
PlanUID *int64
UIDs *[]int
Status *[]PlanCheckRunStatus
- Type *[]PlanCheckRunType
ResultStatus *[]storepb.Advice_Status
}
@@ -84,11 +70,11 @@ func (s *Store) CreatePlanCheckRuns(ctx context.Context, plan *PlanMessage, crea
}
// Insert new plan check runs
- q = qb.Q().Space("INSERT INTO plan_check_run (plan_id, status, type, config, result) VALUES")
+ q = qb.Q().Space("INSERT INTO plan_check_run (plan_id, status, config, result) VALUES")
for i, create := range creates {
config, err := protojson.Marshal(create.Config)
if err != nil {
- return errors.Wrapf(err, "faield to marshal create config %v", create.Config)
+ return errors.Wrapf(err, "failed to marshal create config")
}
result, err := protojson.Marshal(create.Result)
if err != nil {
@@ -97,7 +83,7 @@ func (s *Store) CreatePlanCheckRuns(ctx context.Context, plan *PlanMessage, crea
if i > 0 {
q.Space(",")
}
- q.Space("(?, ?, ?, ?, ?)", create.PlanUID, create.Status, create.Type, config, result)
+ q.Space("(?, ?, ?, ?)", create.PlanUID, create.Status, config, result)
}
query, args, err = q.ToSQL()
if err != nil {
@@ -118,7 +104,6 @@ SELECT
plan_check_run.updated_at,
plan_check_run.plan_id,
plan_check_run.status,
- plan_check_run.type,
plan_check_run.config,
plan_check_run.result
FROM plan_check_run
@@ -132,9 +117,6 @@ WHERE TRUE`)
if v := find.Status; v != nil {
q.Space("AND plan_check_run.status = ANY(?)", *v)
}
- if v := find.Type; v != nil {
- q.Space("AND plan_check_run.type = ANY(?)", *v)
- }
if v := find.ResultStatus; v != nil {
statusStrings := make([]string, len(*v))
for i, status := range *v {
@@ -166,7 +148,6 @@ WHERE TRUE`)
&planCheckRun.UpdatedAt,
&planCheckRun.PlanUID,
&planCheckRun.Status,
- &planCheckRun.Type,
&config,
&result,
); err != nil {
@@ -188,6 +169,19 @@ WHERE TRUE`)
return planCheckRuns, nil
}
+// GetPlanCheckRun returns the plan check run for a plan.
+func (s *Store) GetPlanCheckRun(ctx context.Context, planUID int64) (*PlanCheckRunMessage, error) {
+ runs, err := s.ListPlanCheckRuns(ctx, &FindPlanCheckRunMessage{PlanUID: &planUID})
+ if err != nil {
+ return nil, err
+ }
+ if len(runs) == 0 {
+ return nil, nil
+ }
+ // With consolidated model, there should be only one record per plan
+ return runs[0], nil
+}
+
// UpdatePlanCheckRun updates a plan check run.
func (s *Store) UpdatePlanCheckRun(ctx context.Context, status PlanCheckRunStatus, result *storepb.PlanCheckRunResult, uid int) error {
resultBytes, err := protojson.Marshal(result)
diff --git a/docs/plans/2025-12-23-consolidated-plan-check-runs-design.md b/docs/plans/2025-12-23-consolidated-plan-check-runs-design.md
new file mode 100644
index 0000000000..e0c94529cd
--- /dev/null
+++ b/docs/plans/2025-12-23-consolidated-plan-check-runs-design.md
@@ -0,0 +1,326 @@
+# Consolidated Plan Check Runs Design
+
+## Problem
+
+Currently, plan check runs create `#specs × #databases × #types` records per plan:
+- 100 databases × 2-3 types = 200-300 rows per plan
+- Causes DB row explosion affecting performance/storage
+- CI sampling size is a post-hoc band-aid
+
+## Solution
+
+Consolidate to **one record per plan** containing all check configs and results.
+
+## Key Decisions
+
+| Decision | Choice |
+|----------|--------|
+| Records per plan | One (all types combined) |
+| Execution model | Sequential, single executor (optimize to parallel later if needed) |
+| Sampling | Applied at config generation time, not post-hoc |
+| Result structure | Flat array with metadata tags (instance_id, database_name, check_type) |
+| Status model | Record-level for execution; per-result for check outcomes |
+| Migration | SQL-only with aggregation |
+
+## Data Model Changes
+
+### PlanCheckRunConfig (proto)
+
+```protobuf
+enum PlanCheckType {
+ PLAN_CHECK_TYPE_UNSPECIFIED = 0;
+ PLAN_CHECK_TYPE_STATEMENT_ADVISE = 1;
+ PLAN_CHECK_TYPE_STATEMENT_SUMMARY_REPORT = 2;
+ PLAN_CHECK_TYPE_GHOST_SYNC = 3;
+}
+
+message PlanCheckRunConfig {
+ repeated CheckTarget targets = 1;
+
+ message CheckTarget {
+ string instance_id = 1;
+ string database_name = 2;
+ string sheet_sha256 = 3;
+ bool enable_prior_backup = 4;
+ bool enable_ghost = 5;
+ bool enable_sdl = 6;
+ map<string, string> ghost_flags = 7;
+ repeated PlanCheckType check_types = 8;
+ }
+}
+```
+
+### PlanCheckRunResult.Result (proto)
+
+Add fields to existing Result message:
+```protobuf
+message Result {
+ // existing fields...
+ string instance_id = 7;
+ string database_name = 8;
+ PlanCheckType check_type = 9;
+}
+```
+
+### Store Changes
+
+- Remove `Type` field from `PlanCheckRunMessage`
+- Add `GetPlanCheckRun(ctx, planUID)` for single-record access
+- Update `CreatePlanCheckRuns` → `CreatePlanCheckRun` (singular)
+
+## Executor Changes
+
+### New Combined Executor
+
+```go
+// backend/runner/plancheck/executor_combined.go
+type CombinedExecutor struct {
+ statementAdviseExecutor *StatementAdviseExecutor
+ summaryReportExecutor *SummaryReportExecutor
+ ghostSyncExecutor *GhostSyncExecutor
+}
+
+func (e *CombinedExecutor) Run(ctx context.Context, config *storepb.PlanCheckRunConfig) ([]*storepb.PlanCheckRunResult_Result, error) {
+ var results []*storepb.PlanCheckRunResult_Result
+
+ for _, target := range config.Targets {
+ for _, checkType := range target.CheckTypes {
+ targetResults, err := e.runCheck(ctx, target, checkType)
+ if err != nil {
+ // Add error result, continue to next
+ results = append(results, &storepb.PlanCheckRunResult_Result{
+ Status: storepb.Advice_ERROR,
+ InstanceId: target.InstanceId,
+ DatabaseName: target.DatabaseName,
+ CheckType: checkType,
+ Title: "Check failed",
+ Content: err.Error(),
+ })
+ continue
+ }
+ results = append(results, targetResults...)
+ }
+ }
+ return results, nil
+}
+```
+
+### Scheduler Simplification
+
+- Remove type-based executor map
+- Single executor handles all plan check runs
+- Record status: RUNNING → DONE (or FAILED on infra error)
+
+## Config Generation
+
+```go
+func getPlanCheckRunFromPlan(project *store.ProjectMessage, plan *store.PlanMessage, databaseGroup *v1pb.DatabaseGroup) (*store.PlanCheckRunMessage, error) {
+ var targets []*storepb.PlanCheckRunConfig_CheckTarget
+
+ for _, spec := range plan.Config.Specs {
+ switch config := spec.Config.(type) {
+ case *storepb.PlanConfig_Spec_ChangeDatabaseConfig:
+ if config.ChangeDatabaseConfig.Release != "" {
+ continue
+ }
+
+ databases := resolveDatabases(config, databaseGroup)
+
+ // Apply sampling upfront
+ if samplingSize := project.Setting.GetCiSamplingSize(); samplingSize > 0 {
+ if len(databases) > int(samplingSize) {
+ databases = databases[:samplingSize]
+ }
+ }
+
+ for _, db := range databases {
+ target := &storepb.PlanCheckRunConfig_CheckTarget{
+ InstanceId: instanceID,
+ DatabaseName: databaseName,
+ SheetSha256: config.ChangeDatabaseConfig.SheetSha256,
+ EnablePriorBackup: config.ChangeDatabaseConfig.EnablePriorBackup,
+ EnableGhost: config.ChangeDatabaseConfig.EnableGhost,
+ EnableSdl: enableSDL,
+ CheckTypes: []storepb.CheckType{STATEMENT_ADVISE, STATEMENT_SUMMARY_REPORT},
+ }
+ if config.ChangeDatabaseConfig.EnableGhost {
+ target.CheckTypes = append(target.CheckTypes, GHOST_SYNC)
+ }
+ targets = append(targets, target)
+ }
+ }
+ }
+
+ if len(targets) == 0 {
+ return nil, nil
+ }
+
+ return &store.PlanCheckRunMessage{
+ PlanUID: plan.UID,
+ Status: store.PlanCheckRunStatusRunning,
+ Config: &storepb.PlanCheckRunConfig{Targets: targets},
+ }, nil
+}
+```
+
+## Consumer Updates
+
+### approval/runner.go
+
+```go
+// Before: query by type, iterate records
+planCheckRuns, _ := r.store.ListPlanCheckRuns(ctx, &store.FindPlanCheckRunMessage{
+ PlanUID: &plan.UID,
+ Type: &[]store.PlanCheckRunType{store.PlanCheckDatabaseStatementSummaryReport},
+})
+
+// After: single record, filter results
+planCheckRun, _ := r.store.GetPlanCheckRun(ctx, plan.UID)
+if planCheckRun.Status == store.PlanCheckRunStatusRunning {
+ return nil, false, nil
+}
+for _, result := range planCheckRun.Result.Results {
+ if result.CheckType == storepb.CheckType_STATEMENT_SUMMARY_REPORT {
+ // existing logic
+ }
+}
+```
+
+### auto_rollout_scheduler.go
+
+```go
+// Simplified single-record check
+planCheckRun, _ := s.store.GetPlanCheckRun(ctx, plan.UID)
+if planCheckRun == nil {
+ return true, nil
+}
+if planCheckRun.Status != store.PlanCheckRunStatusDone {
+ return false, nil
+}
+for _, result := range planCheckRun.Result.Results {
+ if result.Status == storepb.Advice_ERROR {
+ return false, nil
+ }
+}
+return true, nil
+```
+
+### API ListPlanCheckRuns
+
+Keep API backward compatible. Internally transform single record to list of virtual `PlanCheckRun` objects grouped by type.
+
+## Status & Results Model
+
+| Status | Results | Meaning |
+|--------|---------|---------|
+| RUNNING | Empty `[]` | Executor still processing |
+| DONE | All results | All checks completed |
+| FAILED | Partial results + error | Infrastructure error, partial work preserved |
+
+- CANCELED records are discarded (rare, user-initiated)
+- If any record is RUNNING during migration → consolidated is RUNNING, Bytebase re-runs
+
+## Migration Script
+
+```sql
+-- Step 1: Deduplicate - keep latest per (plan, type, instance, database), last 30 days, exclude CANCELED
+CREATE TEMP TABLE plan_check_run_deduped AS
+SELECT DISTINCT ON (plan_id, type, config->>'instanceId', config->>'databaseName')
+ *
+FROM plan_check_run
+WHERE created_at >= NOW() - INTERVAL '30 days'
+ AND status != 'CANCELED'
+ORDER BY plan_id, type, config->>'instanceId', config->>'databaseName', created_at DESC;
+
+-- Step 2: Delete all old records
+DELETE FROM plan_check_run;
+
+-- Step 3: Insert consolidated records (one per plan)
+INSERT INTO plan_check_run (plan_id, status, config, result, created_at, updated_at)
+SELECT
+ plan_id,
+ -- Status aggregation
+ CASE
+ WHEN bool_or(status = 'RUNNING') THEN 'RUNNING'
+ WHEN bool_or(status = 'FAILED') THEN 'FAILED'
+ ELSE 'DONE'
+ END,
+ -- Config: if any RUNNING, empty (will be re-run); otherwise aggregate
+ CASE
+ WHEN bool_or(status = 'RUNNING') THEN '{"targets": []}'::jsonb
+ ELSE jsonb_build_object('targets', (
+ SELECT jsonb_agg(target)
+ FROM (
+ SELECT jsonb_build_object(
+ 'instanceId', config->>'instanceId',
+ 'databaseName', config->>'databaseName',
+ 'sheetSha256', config->>'sheetSha256',
+ 'enablePriorBackup', COALESCE((config->>'enablePriorBackup')::boolean, false),
+ 'enableGhost', COALESCE((config->>'enableGhost')::boolean, false),
+ 'enableSdl', COALESCE((config->>'enableSdl')::boolean, false),
+ 'ghostFlags', COALESCE(config->'ghostFlags', '{}'::jsonb),
+ 'checkTypes', array_agg(type)
+ ) as target
+ FROM plan_check_run_deduped d2
+ WHERE d2.plan_id = d.plan_id
+ GROUP BY
+ config->>'instanceId',
+ config->>'databaseName',
+ config->>'sheetSha256',
+ config->>'enablePriorBackup',
+ config->>'enableGhost',
+ config->>'enableSdl',
+ config->'ghostFlags'
+ ) targets
+ ))
+ END,
+ -- Results: empty if RUNNING, otherwise aggregate with type tagging
+ CASE
+ WHEN bool_or(status = 'RUNNING') THEN '{"results": []}'::jsonb
+ ELSE jsonb_build_object('results', (
+ SELECT COALESCE(jsonb_agg(
+ r || jsonb_build_object(
+ 'instanceId', d3.config->>'instanceId',
+ 'databaseName', d3.config->>'databaseName',
+ 'checkType', d3.type
+ )
+ ), '[]'::jsonb)
+ FROM plan_check_run_deduped d3
+ LEFT JOIN LATERAL jsonb_array_elements(d3.result->'results') r ON true
+ WHERE d3.plan_id = d.plan_id
+ ))
+ END,
+ MAX(created_at),
+ MAX(updated_at)
+FROM plan_check_run_deduped d
+GROUP BY plan_id;
+
+-- Step 4: Cleanup
+DROP TABLE plan_check_run_deduped;
+
+-- Step 5: Drop type column
+ALTER TABLE plan_check_run DROP COLUMN IF EXISTS type;
+```
+
+## Files Affected
+
+| Area | Files |
+|------|-------|
+| Proto | `proto/store/plan_check_run.proto` |
+| Store | `backend/store/plan_check_run.go` |
+| Config gen | `backend/api/v1/plan_service_plan_check.go` |
+| Executor | `backend/runner/plancheck/executor_combined.go` (new) |
+| Scheduler | `backend/runner/plancheck/scheduler.go` |
+| Consumers | `backend/runner/approval/runner.go` |
+| | `backend/runner/taskrun/auto_rollout_scheduler.go` |
+| | `backend/api/v1/plan_service.go` |
+| | `backend/api/v1/plan_service_converter.go` |
+| Migration | `backend/migrator/migration/prod/NEXT_VERSION/...` |
+
+## Risks & Mitigations
+
+| Risk | Mitigation |
+|------|------------|
+| In-flight RUNNING checks during migration | Re-run after migration (cheap, plan checks are idempotent) |
+| API backward compatibility | Transform single record to virtual list in ListPlanCheckRuns |
+| Sequential execution bottleneck | Can evolve to parallel goroutines if needed |
diff --git a/docs/plans/2025-12-23-consolidated-plan-check-runs-impl.md b/docs/plans/2025-12-23-consolidated-plan-check-runs-impl.md
new file mode 100644
index 0000000000..763e0e4b99
--- /dev/null
+++ b/docs/plans/2025-12-23-consolidated-plan-check-runs-impl.md
@@ -0,0 +1,905 @@
+# Consolidated Plan Check Runs Implementation Plan
+
+> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
+
+**Goal:** Consolidate plan check runs from N×types records per plan to a single record, reducing DB row explosion.
+
+**Architecture:** One `plan_check_run` record per plan containing all targets and check types. Single combined executor processes all checks sequentially, aggregating results with instance/database/type tagging.
+
+**Tech Stack:** Go, PostgreSQL, Protocol Buffers, golangci-lint
+
+---
+
+## Task 1: Update Proto - PlanCheckRunConfig
+
+**Files:**
+- Modify: `proto/store/store/plan_check_run.proto`
+
+**Step 1: Add CheckType enum and replace PlanCheckRunConfig**
+
+Replace the entire `PlanCheckRunConfig` message with the new consolidated version:
+
+```protobuf
+enum PlanCheckType {
+ PLAN_CHECK_TYPE_UNSPECIFIED = 0;
+ PLAN_CHECK_TYPE_STATEMENT_ADVISE = 1;
+ PLAN_CHECK_TYPE_STATEMENT_SUMMARY_REPORT = 2;
+ PLAN_CHECK_TYPE_GHOST_SYNC = 3;
+}
+
+message PlanCheckRunConfig {
+ repeated CheckTarget targets = 1;
+
+ message CheckTarget {
+ // Format: instances/{instance}/databases/{database}
+ string target = 1;
+ string sheet_sha256 = 2;
+ bool enable_prior_backup = 3;
+ bool enable_ghost = 4;
+ bool enable_sdl = 5;
+ map<string, string> ghost_flags = 6;
+ repeated PlanCheckType types = 7;
+ }
+}
+```
+
+Note: We reuse the name `PlanCheckRunConfig` but with new structure. Migration handles the conversion.
+
+**Step 2: Add target fields to Result message**
+
+Modify the `Result` message inside `PlanCheckRunResult` (around line 32), add after `code` field:
+
+```protobuf
+message Result {
+ Advice.Status status = 1;
+ string title = 2;
+ string content = 3;
+ int32 code = 4;
+
+ // Target identification for consolidated results
+ // Format: instances/{instance}/databases/{database}
+ string target = 7;
+ PlanCheckType type = 8;
+
+ oneof report {
+ SqlSummaryReport sql_summary_report = 5;
+ SqlReviewReport sql_review_report = 6;
+ }
+ // ... rest unchanged
+}
+```
+
+**Step 3: Generate proto**
+
+Run: `cd proto && buf generate`
+
+**Step 4: Verify generation**
+
+Run: `ls -la ../backend/generated-go/store/plan_check_run.pb.go`
+Expected: File updated with new timestamp
+
+**Step 5: Commit**
+
+```bash
+but commit consolidated-plan-check-runs-design -m "proto: add PlanCheckRunConfigV2 and result target fields"
+```
+
+---
+
+## Task 2: Update Store - PlanCheckRunMessage
+
+**Files:**
+- Modify: `backend/store/plan_check_run.go`
+
+**Step 1: Simplify PlanCheckRunMessage struct**
+
+Around line 42, update the struct (remove Type field, Config uses new structure):
+
+```go
+// PlanCheckRunMessage is the message for a plan check run.
+type PlanCheckRunMessage struct {
+ UID int
+ CreatedAt time.Time
+ UpdatedAt time.Time
+
+ PlanUID int64
+
+ Status PlanCheckRunStatus
+ Config *storepb.PlanCheckRunConfig // New consolidated config with targets
+ Result *storepb.PlanCheckRunResult
+}
+```
+
+**Step 2: Remove PlanCheckRunType constants**
+
+Delete the type constants (lines 18-25):
+
+```go
+// DELETE THESE:
+// PlanCheckDatabaseStatementAdvise
+// PlanCheckDatabaseStatementSummaryReport
+// PlanCheckDatabaseGhostSync
+```
+
+**Step 3: Update CreatePlanCheckRuns**
+
+Simplify the INSERT (remove type column):
+
+```go
+// Insert new plan check runs
+q = qb.Q().Space("INSERT INTO plan_check_run (plan_id, status, config, result) VALUES")
+for i, create := range creates {
+ config, err := protojson.Marshal(create.Config)
+ if err != nil {
+ return errors.Wrapf(err, "failed to marshal create config")
+ }
+ result, err := protojson.Marshal(create.Result)
+ if err != nil {
+ return errors.Wrapf(err, "failed to marshal create result %v", create.Result)
+ }
+ if i > 0 {
+ q.Space(",")
+ }
+ q.Space("(?, ?, ?, ?)", create.PlanUID, create.Status, config, result)
+}
+```
+
+**Step 4: Update ListPlanCheckRuns**
+
+Simplify the scan (remove type):
+
+```go
+for rows.Next() {
+ planCheckRun := PlanCheckRunMessage{
+ Config: &storepb.PlanCheckRunConfig{},
+ Result: &storepb.PlanCheckRunResult{},
+ }
+ var config, result string
+ if err := rows.Scan(
+ &planCheckRun.UID,
+ &planCheckRun.CreatedAt,
+ &planCheckRun.UpdatedAt,
+ &planCheckRun.PlanUID,
+ &planCheckRun.Status,
+ &config,
+ &result,
+ ); err != nil {
+ return nil, err
+ }
+
+ if err := common.ProtojsonUnmarshaler.Unmarshal([]byte(config), planCheckRun.Config); err != nil {
+ return nil, err
+ }
+ if err := common.ProtojsonUnmarshaler.Unmarshal([]byte(result), planCheckRun.Result); err != nil {
+ return nil, err
+ }
+ planCheckRuns = append(planCheckRuns, &planCheckRun)
+}
+```
+
+**Step 5: Update FindPlanCheckRunMessage**
+
+Remove Type filter field:
+
+```go
+type FindPlanCheckRunMessage struct {
+ PlanUID *int64
+ UIDs *[]int
+ Status *[]PlanCheckRunStatus
+ ResultStatus *[]storepb.Advice_Status
+ // Type field removed
+}
+```
+
+**Step 6: Add GetPlanCheckRun helper**
+
+Add after `ListPlanCheckRuns`:
+
+```go
+// GetPlanCheckRun returns the plan check run for a plan.
+func (s *Store) GetPlanCheckRun(ctx context.Context, planUID int64) (*PlanCheckRunMessage, error) {
+ runs, err := s.ListPlanCheckRuns(ctx, &FindPlanCheckRunMessage{PlanUID: &planUID})
+ if err != nil {
+ return nil, err
+ }
+ if len(runs) == 0 {
+ return nil, nil
+ }
+ // With consolidated model, there should be only one record per plan
+ // For backward compatibility during migration, return the first one
+ return runs[0], nil
+}
+```
+
+**Step 7: Run linter**
+
+Run: `golangci-lint run --allow-parallel-runners backend/store/plan_check_run.go`
+Expected: No errors (fix any that appear)
+
+**Step 8: Commit**
+
+```bash
+but commit consolidated-plan-check-runs-design -m "store: simplify PlanCheckRunMessage for consolidated model"
+```
+
+---
+
+## Task 3: Create Combined Executor
+
+**Files:**
+- Create: `backend/runner/plancheck/executor_combined.go`
+
+**Step 1: Create the combined executor file**
+
+```go
+package plancheck
+
+import (
+ "context"
+
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/component/dbfactory"
+ "github.com/bytebase/bytebase/backend/component/sheet"
+ "github.com/bytebase/bytebase/backend/enterprise"
+ "github.com/bytebase/bytebase/backend/store"
+)
+
+// CombinedExecutor processes all plan check types for a consolidated plan check run.
+type CombinedExecutor struct {
+ store *store.Store
+ sheetManager *sheet.Manager
+ dbFactory *dbfactory.DBFactory
+ licenseService *enterprise.LicenseService
+}
+
+// NewCombinedExecutor creates a combined executor.
+func NewCombinedExecutor(
+ store *store.Store,
+ sheetManager *sheet.Manager,
+ dbFactory *dbfactory.DBFactory,
+ licenseService *enterprise.LicenseService,
+) *CombinedExecutor {
+ return &CombinedExecutor{
+ store: store,
+ sheetManager: sheetManager,
+ dbFactory: dbFactory,
+ licenseService: licenseService,
+ }
+}
+
+// Run runs all checks for a consolidated config.
+func (e *CombinedExecutor) Run(ctx context.Context, config *storepb.PlanCheckRunConfig) ([]*storepb.PlanCheckRunResult_Result, error) {
+ var allResults []*storepb.PlanCheckRunResult_Result
+
+ for _, target := range config.Targets {
+ for _, checkType := range target.CheckTypes {
+ results, err := e.runCheck(ctx, target, checkType)
+ if err != nil {
+ // Add error result for this target/type, continue to next
+ allResults = append(allResults, &storepb.PlanCheckRunResult_Result{
+ Status: storepb.Advice_ERROR,
+ InstanceId: target.InstanceId,
+ DatabaseName: target.DatabaseName,
+ CheckType: checkType,
+ Title: "Check failed",
+ Content: err.Error(),
+ Code: common.Internal.Int32(),
+ })
+ continue
+ }
+ // Tag results with target info
+ for _, r := range results {
+ r.InstanceId = target.InstanceId
+ r.DatabaseName = target.DatabaseName
+ r.CheckType = checkType
+ }
+ allResults = append(allResults, results...)
+ }
+ }
+
+ return allResults, nil
+}
+
+func (e *CombinedExecutor) runCheck(ctx context.Context, target *storepb.PlanCheckRunConfig_CheckTarget, checkType storepb.PlanCheckType) ([]*storepb.PlanCheckRunResult_Result, error) {
+ switch checkType {
+ case storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_ADVISE:
+ return e.runStatementAdvise(ctx, target)
+ case storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_SUMMARY_REPORT:
+ return e.runStatementReport(ctx, target)
+ case storepb.PlanCheckType_PLAN_CHECK_TYPE_GHOST_SYNC:
+ return e.runGhostSync(ctx, target)
+ default:
+ return nil, nil
+ }
+}
+
+// Helper methods that call into existing executor logic
+// These will need to be refactored from the existing executors
+func (e *CombinedExecutor) runStatementAdvise(ctx context.Context, target *storepb.PlanCheckRunConfig_CheckTarget) ([]*storepb.PlanCheckRunResult_Result, error) {
+ // Inline the logic from StatementAdviseExecutor.Run
+ // or refactor to share code
+ // For now, create executor instance
+ executor := &StatementAdviseExecutor{
+ store: e.store,
+ sheetManager: e.sheetManager,
+ dbFactory: e.dbFactory,
+ licenseService: e.licenseService,
+ }
+ return executor.runForTarget(ctx, target)
+}
+
+func (e *CombinedExecutor) runStatementReport(ctx context.Context, target *storepb.PlanCheckRunConfig_CheckTarget) ([]*storepb.PlanCheckRunResult_Result, error) {
+ executor := &StatementReportExecutor{
+ store: e.store,
+ sheetManager: e.sheetManager,
+ dbFactory: e.dbFactory,
+ }
+ return executor.runForTarget(ctx, target)
+}
+
+func (e *CombinedExecutor) runGhostSync(ctx context.Context, target *storepb.PlanCheckRunConfig_CheckTarget) ([]*storepb.PlanCheckRunResult_Result, error) {
+ executor := &GhostSyncExecutor{
+ store: e.store,
+ dbFactory: e.dbFactory,
+ }
+ return executor.runForTarget(ctx, target)
+}
+```
+
+**Step 2: Run linter**
+
+Run: `golangci-lint run --allow-parallel-runners backend/runner/plancheck/executor_combined.go`
+Expected: No errors
+
+**Step 3: Commit**
+
+```bash
+but commit consolidated-plan-check-runs-design -m "plancheck: add CombinedExecutor for consolidated runs"
+```
+
+---
+
+## Task 4: Simplify Scheduler
+
+**Files:**
+- Modify: `backend/runner/plancheck/scheduler.go`
+
+**Step 1: Simplify Scheduler struct**
+
+Remove the type-based executor map, use only CombinedExecutor:
+
+```go
+// Scheduler is the plan check run scheduler.
+type Scheduler struct {
+ store *store.Store
+ licenseService *enterprise.LicenseService
+ stateCfg *state.State
+ executor *CombinedExecutor
+}
+
+// NewScheduler creates a new plan check scheduler.
+func NewScheduler(s *store.Store, licenseService *enterprise.LicenseService, stateCfg *state.State, executor *CombinedExecutor) *Scheduler {
+ return &Scheduler{
+ store: s,
+ licenseService: licenseService,
+ stateCfg: stateCfg,
+ executor: executor,
+ }
+}
+```
+
+**Step 2: Remove Register method**
+
+Delete the `Register` method entirely - no longer needed.
+
+**Step 3: Simplify runPlanCheckRun**
+
+Replace the `runPlanCheckRun` method:
+
+```go
+func (s *Scheduler) runPlanCheckRun(ctx context.Context, planCheckRun *store.PlanCheckRunMessage) {
+ // Skip if already running
+ if _, ok := s.stateCfg.RunningPlanChecks.Load(planCheckRun.UID); ok {
+ return
+ }
+
+ s.stateCfg.RunningPlanChecks.Store(planCheckRun.UID, true)
+ go func() {
+ defer func() {
+ s.stateCfg.RunningPlanChecks.Delete(planCheckRun.UID)
+ s.stateCfg.RunningPlanCheckRunsCancelFunc.Delete(planCheckRun.UID)
+ }()
+
+ ctxWithCancel, cancel := context.WithCancel(ctx)
+ defer cancel()
+ s.stateCfg.RunningPlanCheckRunsCancelFunc.Store(planCheckRun.UID, cancel)
+
+ results, err := s.executor.Run(ctxWithCancel, planCheckRun.Config)
+
+ if err != nil {
+ if errors.Is(err, context.Canceled) {
+ s.markPlanCheckRunCanceled(ctx, planCheckRun, err.Error())
+ } else {
+ s.markPlanCheckRunFailed(ctx, planCheckRun, err.Error())
+ }
+ } else {
+ s.markPlanCheckRunDone(ctx, planCheckRun, results)
+ }
+ }()
+}
+```
+
+**Step 4: Add missing import**
+
+Add `"github.com/pkg/errors"` to imports if not present.
+
+**Step 5: Run linter**
+
+Run: `golangci-lint run --allow-parallel-runners backend/runner/plancheck/scheduler.go`
+Expected: No errors
+
+**Step 6: Commit**
+
+```bash
+but commit consolidated-plan-check-runs-design -m "plancheck: simplify scheduler for consolidated model"
+```
+
+---
+
+## Task 5: Update Server Registration
+
+**Files:**
+- Modify: `backend/server/server.go`
+
+**Step 1: Replace executor registrations with CombinedExecutor**
+
+Around line 196-202, replace the old executor setup:
+
+```go
+ // OLD CODE TO REMOVE:
+ // s.planCheckScheduler = plancheck.NewScheduler(stores, s.licenseService, s.stateCfg)
+ // statementAdviseExecutor := plancheck.NewStatementAdviseExecutor(...)
+ // s.planCheckScheduler.Register(store.PlanCheckDatabaseStatementAdvise, statementAdviseExecutor)
+ // ghostSyncExecutor := plancheck.NewGhostSyncExecutor(...)
+ // s.planCheckScheduler.Register(store.PlanCheckDatabaseGhostSync, ghostSyncExecutor)
+ // statementReportExecutor := plancheck.NewStatementReportExecutor(...)
+ // s.planCheckScheduler.Register(store.PlanCheckDatabaseStatementSummaryReport, statementReportExecutor)
+
+ // NEW CODE:
+ combinedExecutor := plancheck.NewCombinedExecutor(stores, sheetManager, s.dbFactory, s.licenseService)
+ s.planCheckScheduler = plancheck.NewScheduler(stores, s.licenseService, s.stateCfg, combinedExecutor)
+```
+
+**Step 2: Run linter**
+
+Run: `golangci-lint run --allow-parallel-runners backend/server/server.go`
+Expected: No errors
+
+**Step 3: Commit**
+
+```bash
+but commit consolidated-plan-check-runs-design -m "server: use CombinedExecutor for plan checks"
+```
+
+---
+
+## Task 6: Update Config Generation
+
+**Files:**
+- Modify: `backend/api/v1/plan_service_plan_check.go`
+
+**Step 1: Rewrite getPlanCheckRunsFromPlan to return single consolidated config**
+
+Replace the entire function:
+
+```go
+func getPlanCheckRunFromPlan(project *store.ProjectMessage, plan *store.PlanMessage, databaseGroup *v1pb.DatabaseGroup) (*store.PlanCheckRunMessage, error) {
+ var targets []*storepb.PlanCheckRunConfig_CheckTarget
+
+ for _, spec := range plan.Config.Specs {
+ switch config := spec.Config.(type) {
+ case *storepb.PlanConfig_Spec_CreateDatabaseConfig:
+ // No checks for create database.
+ case *storepb.PlanConfig_Spec_ExportDataConfig:
+ // No checks for export data.
+ case *storepb.PlanConfig_Spec_ChangeDatabaseConfig:
+ // Skip plan checks for releases.
+ if config.ChangeDatabaseConfig.Release != "" {
+ continue
+ }
+
+ var databases []string
+ if len(config.ChangeDatabaseConfig.Targets) == 1 && databaseGroup != nil && config.ChangeDatabaseConfig.Targets[0] == databaseGroup.Name {
+ for _, m := range databaseGroup.MatchedDatabases {
+ databases = append(databases, m.Name)
+ }
+ } else {
+ databases = config.ChangeDatabaseConfig.Targets
+ }
+
+ // Apply sampling upfront
+ if samplingSize := project.Setting.GetCiSamplingSize(); samplingSize > 0 {
+ if len(databases) > int(samplingSize) {
+ databases = databases[:samplingSize]
+ }
+ }
+
+ enableSDL := config.ChangeDatabaseConfig.Type == storepb.PlanConfig_ChangeDatabaseConfig_SDL
+ enableGhost := config.ChangeDatabaseConfig.Type == storepb.PlanConfig_ChangeDatabaseConfig_MIGRATE && config.ChangeDatabaseConfig.EnableGhost
+
+ for _, target := range databases {
+ instanceID, databaseName, err := common.GetInstanceDatabaseID(target)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to parse %q", target)
+ }
+
+ checkTypes := []storepb.PlanCheckType{
+ storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_ADVISE,
+ storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_SUMMARY_REPORT,
+ }
+ if enableGhost {
+ checkTypes = append(checkTypes, storepb.PlanCheckType_PLAN_CHECK_TYPE_GHOST_SYNC)
+ }
+
+ targets = append(targets, &storepb.PlanCheckRunConfig_CheckTarget{
+ InstanceId: instanceID,
+ DatabaseName: databaseName,
+ SheetSha256: config.ChangeDatabaseConfig.SheetSha256,
+ EnablePriorBackup: config.ChangeDatabaseConfig.EnablePriorBackup,
+ EnableGhost: config.ChangeDatabaseConfig.EnableGhost,
+ EnableSdl: enableSDL,
+ GhostFlags: config.ChangeDatabaseConfig.GhostFlags,
+ CheckTypes: checkTypes,
+ })
+ }
+ default:
+ return nil, errors.Errorf("unknown spec config type %T", config)
+ }
+ }
+
+ if len(targets) == 0 {
+ return nil, nil
+ }
+
+ return &store.PlanCheckRunMessage{
+ PlanUID: plan.UID,
+ Status: store.PlanCheckRunStatusRunning,
+ Config: &storepb.PlanCheckRunConfig{Targets: targets},
+ }, nil
+}
+```
+
+**Step 2: Find and update callers of getPlanCheckRunsFromPlan**
+
+Search for callers:
+Run: `grep -rn "getPlanCheckRunsFromPlan" backend/`
+
+Update each caller to use the new function signature (returns single `*PlanCheckRunMessage` instead of slice).
+
+**Step 3: Run linter**
+
+Run: `golangci-lint run --allow-parallel-runners backend/api/v1/plan_service_plan_check.go`
+Expected: No errors
+
+**Step 4: Commit**
+
+```bash
+but commit consolidated-plan-check-runs-design -m "api: rewrite config generation for consolidated format"
+```
+
+---
+
+## Task 7: Update Consumer - Approval Runner
+
+**Files:**
+- Modify: `backend/runner/approval/runner.go`
+
+**Step 1: Update plan check status check (around line 448)**
+
+Find the `ListPlanCheckRuns` call and update:
+
+```go
+// Check plan check runs status
+planCheckRun, err := r.store.GetPlanCheckRun(ctx, plan.UID)
+if err != nil {
+ return nil, false, errors.Wrapf(err, "failed to get plan check run for plan %v", plan.UID)
+}
+
+// No plan check configured
+if planCheckRun == nil {
+ // Continue with existing logic for no checks
+}
+
+// Wait for plan check to complete
+if planCheckRun.Status == store.PlanCheckRunStatusRunning {
+ return nil, false, nil // Not ready yet, retry later
+}
+
+// Build latestPlanCheckRun map from results
+type Key struct {
+ InstanceID string
+ DatabaseName string
+}
+latestPlanCheckRun := map[Key]*storepb.PlanCheckRunResult_Result{}
+
+for _, result := range planCheckRun.Result.Results {
+ // Only consider summary report results
+ if result.CheckType != storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_SUMMARY_REPORT {
+ continue
+ }
+ key := Key{
+ InstanceID: result.InstanceId,
+ DatabaseName: result.DatabaseName,
+ }
+ latestPlanCheckRun[key] = result
+}
+```
+
+**Step 2: Run linter**
+
+Run: `golangci-lint run --allow-parallel-runners backend/runner/approval/runner.go`
+Expected: No errors
+
+**Step 3: Commit**
+
+```bash
+but commit consolidated-plan-check-runs-design -m "approval: update to use consolidated plan check run"
+```
+
+---
+
+## Task 8: Update Consumer - Auto Rollout Scheduler
+
+**Files:**
+- Modify: `backend/runner/taskrun/auto_rollout_scheduler.go`
+
+**Step 1: Update plan check status check (around line 130)**
+
+Replace the existing check:
+
+```go
+// Check the latest plan checks based on project settings (error only)
+if project.Setting.RequirePlanCheckNoError {
+ pass, err := func() (bool, error) {
+ plan, err := s.store.GetPlan(ctx, &store.FindPlanMessage{PipelineID: &task.PipelineID})
+ if err != nil {
+ return false, errors.Wrapf(err, "failed to get plan")
+ }
+ if plan == nil {
+ return true, nil
+ }
+
+ planCheckRun, err := s.store.GetPlanCheckRun(ctx, plan.UID)
+ if err != nil {
+ return false, errors.Wrapf(err, "failed to get plan check run")
+ }
+ if planCheckRun == nil {
+ return true, nil // No checks configured
+ }
+ if planCheckRun.Status != store.PlanCheckRunStatusDone {
+ return false, nil
+ }
+ for _, result := range planCheckRun.Result.Results {
+ if result.Status == storepb.Advice_ERROR {
+ return false, nil
+ }
+ }
+ return true, nil
+ }()
+ // ... rest unchanged
+}
+```
+
+**Step 2: Run linter**
+
+Run: `golangci-lint run --allow-parallel-runners backend/runner/taskrun/auto_rollout_scheduler.go`
+Expected: No errors
+
+**Step 3: Commit**
+
+```bash
+but commit consolidated-plan-check-runs-design -m "taskrun: update to use consolidated plan check run"
+```
+
+---
+
+## Task 9: Create Migration Script
+
+**Files:**
+- Create: `backend/migrator/migration/3.14/0004##consolidate_plan_check_runs.sql`
+
+**Step 1: Write the migration SQL**
+
+```sql
+-- Consolidate plan_check_run records: one record per plan instead of N×types
+
+-- Step 1: Create temp table with deduplicated latest records (last 30 days only)
+CREATE TEMP TABLE plan_check_run_deduped AS
+SELECT DISTINCT ON (plan_id, type, config->>'instanceId', config->>'databaseName')
+ *
+FROM plan_check_run
+WHERE created_at >= NOW() - INTERVAL '30 days'
+ AND status != 'CANCELED'
+ORDER BY plan_id, type, config->>'instanceId', config->>'databaseName', created_at DESC;
+
+-- Step 2: Delete all old records
+DELETE FROM plan_check_run;
+
+-- Step 3: Insert consolidated records (one per plan)
+INSERT INTO plan_check_run (plan_id, status, type, config, result, created_at, updated_at)
+SELECT
+ plan_id,
+ -- Status aggregation
+ CASE
+ WHEN bool_or(status = 'RUNNING') THEN 'RUNNING'
+ WHEN bool_or(status = 'FAILED') THEN 'FAILED'
+ ELSE 'DONE'
+ END,
+ -- Type is deprecated but keep a value for compatibility
+ 'bb.plan-check.database.statement.advise',
+ -- Config: if any RUNNING, empty (will be re-run); otherwise aggregate
+ CASE
+ WHEN bool_or(status = 'RUNNING') THEN '{"targets": []}'::jsonb
+ ELSE jsonb_build_object('targets', (
+ SELECT jsonb_agg(target)
+ FROM (
+ SELECT jsonb_build_object(
+ 'instanceId', d2.config->>'instanceId',
+ 'databaseName', d2.config->>'databaseName',
+ 'sheetSha256', d2.config->>'sheetSha256',
+ 'enablePriorBackup', COALESCE((d2.config->>'enablePriorBackup')::boolean, false),
+ 'enableGhost', COALESCE((d2.config->>'enableGhost')::boolean, false),
+ 'enableSdl', COALESCE((d2.config->>'enableSdl')::boolean, false),
+ 'ghostFlags', COALESCE(d2.config->'ghostFlags', '{}'::jsonb),
+ 'checkTypes', array_agg(
+ CASE d2.type
+ WHEN 'bb.plan-check.database.statement.advise' THEN 'PLAN_CHECK_TYPE_STATEMENT_ADVISE'
+ WHEN 'bb.plan-check.database.statement.summary.report' THEN 'PLAN_CHECK_TYPE_STATEMENT_SUMMARY_REPORT'
+ WHEN 'bb.plan-check.database.ghost.sync' THEN 'PLAN_CHECK_TYPE_GHOST_SYNC'
+ END
+ )
+ ) as target
+ FROM plan_check_run_deduped d2
+ WHERE d2.plan_id = d.plan_id
+ GROUP BY
+ d2.config->>'instanceId',
+ d2.config->>'databaseName',
+ d2.config->>'sheetSha256',
+ d2.config->>'enablePriorBackup',
+ d2.config->>'enableGhost',
+ d2.config->>'enableSdl',
+ d2.config->'ghostFlags'
+ ) targets
+ ))
+ END,
+ -- Results: empty if RUNNING, otherwise aggregate with type tagging
+ CASE
+ WHEN bool_or(status = 'RUNNING') THEN '{"results": []}'::jsonb
+ ELSE jsonb_build_object('results', (
+ SELECT COALESCE(jsonb_agg(
+ r || jsonb_build_object(
+ 'instanceId', d3.config->>'instanceId',
+ 'databaseName', d3.config->>'databaseName',
+ 'checkType', CASE d3.type
+ WHEN 'bb.plan-check.database.statement.advise' THEN 'PLAN_CHECK_TYPE_STATEMENT_ADVISE'
+ WHEN 'bb.plan-check.database.statement.summary.report' THEN 'PLAN_CHECK_TYPE_STATEMENT_SUMMARY_REPORT'
+ WHEN 'bb.plan-check.database.ghost.sync' THEN 'PLAN_CHECK_TYPE_GHOST_SYNC'
+ END
+ )
+ ), '[]'::jsonb)
+ FROM plan_check_run_deduped d3
+ LEFT JOIN LATERAL jsonb_array_elements(d3.result->'results') r ON true
+ WHERE d3.plan_id = d.plan_id
+ ))
+ END,
+ MAX(created_at),
+ MAX(updated_at)
+FROM plan_check_run_deduped d
+GROUP BY plan_id;
+
+-- Step 4: Cleanup temp table
+DROP TABLE plan_check_run_deduped;
+
+-- Step 5: Drop type column (no longer used)
+ALTER TABLE plan_check_run DROP COLUMN IF EXISTS type;
+```
+
+**Step 2: Update LATEST.sql**
+
+Modify `backend/migrator/migration/LATEST.sql` to remove the `type` column from `plan_check_run` table:
+
+```sql
+CREATE TABLE plan_check_run (
+ id serial PRIMARY KEY,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ updated_at timestamptz NOT NULL DEFAULT now(),
+ plan_id bigint NOT NULL REFERENCES plan(id),
+ status text NOT NULL CHECK (status IN ('RUNNING', 'DONE', 'FAILED', 'CANCELED')),
+ -- type column removed - check types now in config.targets[].checkTypes
+ -- Stored as PlanCheckRunConfig (proto/store/store/plan_check_run.proto)
+ config jsonb NOT NULL DEFAULT '{}',
+ -- Stored as PlanCheckRunResult (proto/store/store/plan_check_run.proto)
+ result jsonb NOT NULL DEFAULT '{}',
+ payload jsonb NOT NULL DEFAULT '{}'
+);
+```
+
+**Step 3: Update migrator test version**
+
+Update `TestLatestVersion` in `backend/migrator/migrator_test.go` if needed.
+
+**Step 4: Commit**
+
+```bash
+but commit consolidated-plan-check-runs-design -m "migration: consolidate plan_check_runs and drop type column"
+```
+
+---
+
+## Task 10: Update API Compatibility Layer
+
+**Files:**
+- Modify: `backend/api/v1/plan_service.go`
+- Modify: `backend/api/v1/plan_service_converter.go`
+
+**Step 1: Update ListPlanCheckRuns API**
+
+In `plan_service.go`, the API now returns results from the single consolidated record. Update to expand results into the API response format that clients expect.
+
+**Step 2: Update converter**
+
+In `plan_service_converter.go`, update plan check run conversion to use new `Config.Targets` structure instead of old single-target config.
+
+**Step 3: Run linter**
+
+Run: `golangci-lint run --allow-parallel-runners backend/api/v1/plan_service.go backend/api/v1/plan_service_converter.go`
+
+**Step 4: Commit**
+
+```bash
+but commit consolidated-plan-check-runs-design -m "api: update for consolidated plan check run format"
+```
+
+---
+
+## Task 11: Build and Test
+
+**Step 1: Build backend**
+
+Run: `go build -ldflags "-w -s" -p=16 -o ./bytebase-build/bytebase ./backend/bin/server/main.go`
+Expected: Build succeeds
+
+**Step 2: Run linter on all changed files**
+
+Run: `golangci-lint run --allow-parallel-runners`
+Expected: No errors (run repeatedly until clean)
+
+**Step 3: Run related tests**
+
+Run: `go test -v -count=1 github.com/bytebase/bytebase/backend/store -run PlanCheck`
+Run: `go test -v -count=1 github.com/bytebase/bytebase/backend/runner/plancheck`
+
+**Step 4: Final commit**
+
+```bash
+but commit consolidated-plan-check-runs-design -m "chore: fix build and lint issues"
+```
+
+---
+
+## Summary
+
+| Task | Description | Key Files |
+|------|-------------|-----------|
+| 1 | Proto changes | `proto/store/store/plan_check_run.proto` |
+| 2 | Store changes | `backend/store/plan_check_run.go` |
+| 3 | Combined executor | `backend/runner/plancheck/executor_combined.go` |
+| 4 | Scheduler update | `backend/runner/plancheck/scheduler.go` |
+| 5 | Server registration | `backend/server/server.go` |
+| 6 | Config generation | `backend/api/v1/plan_service_plan_check.go` |
+| 7 | Approval runner | `backend/runner/approval/runner.go` |
+| 8 | Auto rollout | `backend/runner/taskrun/auto_rollout_scheduler.go` |
+| 9 | Migration | `backend/migrator/migration/3.14/0004##...sql` |
+| 10 | API compat | `backend/api/v1/plan_service*.go` |
+| 11 | Build & test | All |
diff --git a/proto/gen/grpc-doc/store/README.md b/proto/gen/grpc-doc/store/README.md
index 0d26c0614e..6c70aa527a 100644
--- a/proto/gen/grpc-doc/store/README.md
+++ b/proto/gen/grpc-doc/store/README.md
@@ -172,12 +172,15 @@
- [ChangedResourceTable](#bytebase-store-ChangedResourceTable)
- [ChangedResources](#bytebase-store-ChangedResources)
- [PlanCheckRunConfig](#bytebase-store-PlanCheckRunConfig)
- - [PlanCheckRunConfig.GhostFlagsEntry](#bytebase-store-PlanCheckRunConfig-GhostFlagsEntry)
+ - [PlanCheckRunConfig.CheckTarget](#bytebase-store-PlanCheckRunConfig-CheckTarget)
+ - [PlanCheckRunConfig.CheckTarget.GhostFlagsEntry](#bytebase-store-PlanCheckRunConfig-CheckTarget-GhostFlagsEntry)
- [PlanCheckRunResult](#bytebase-store-PlanCheckRunResult)
- [PlanCheckRunResult.Result](#bytebase-store-PlanCheckRunResult-Result)
- [PlanCheckRunResult.Result.SqlReviewReport](#bytebase-store-PlanCheckRunResult-Result-SqlReviewReport)
- [PlanCheckRunResult.Result.SqlSummaryReport](#bytebase-store-PlanCheckRunResult-Result-SqlSummaryReport)
+ - [PlanCheckType](#bytebase-store-PlanCheckType)
+
- [store/policy.proto](#store_policy-proto)
- [Binding](#bytebase-store-Binding)
- [DataSourceQueryPolicy](#bytebase-store-DataSourceQueryPolicy)
@@ -2982,22 +2985,37 @@ Type is the database change type.
| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
-| sheet_sha256 | [string](#string) | | The SHA256 hash of the sheet content (hex-encoded). |
-| instance_id | [string](#string) | | |
-| database_name | [string](#string) | | |
-| ghost_flags | [PlanCheckRunConfig.GhostFlagsEntry](#bytebase-store-PlanCheckRunConfig-GhostFlagsEntry) | repeated | |
-| enable_prior_backup | [bool](#bool) | | If set, a backup of the modified data will be created automatically before any changes are applied. |
-| enable_ghost | [bool](#bool) | | Whether to use gh-ost for online schema migration. |
-| enable_sdl | [bool](#bool) | | Whether this is a Schema Definition Language (SDL) change. |
+| targets | [PlanCheckRunConfig.CheckTarget](#bytebase-store-PlanCheckRunConfig-CheckTarget) | repeated | |
+
+
+
+
+
+
+<a name="bytebase-store-PlanCheckRunConfig-CheckTarget"></a>
+
+### PlanCheckRunConfig.CheckTarget
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| target | [string](#string) | | Format: instances/{instance}/databases/{database} |
+| sheet_sha256 | [string](#string) | | |
+| enable_prior_backup | [bool](#bool) | | |
+| enable_ghost | [bool](#bool) | | |
+| enable_sdl | [bool](#bool) | | |
+| ghost_flags | [PlanCheckRunConfig.CheckTarget.GhostFlagsEntry](#bytebase-store-PlanCheckRunConfig-CheckTarget-GhostFlagsEntry) | repeated | |
+| types | [PlanCheckType](#bytebase-store-PlanCheckType) | repeated | |
+
-<a name="bytebase-store-PlanCheckRunConfig-GhostFlagsEntry"></a>
-### PlanCheckRunConfig.GhostFlagsEntry
+<a name="bytebase-store-PlanCheckRunConfig-CheckTarget-GhostFlagsEntry"></a>
+
+### PlanCheckRunConfig.CheckTarget.GhostFlagsEntry
@@ -3039,6 +3057,8 @@ Type is the database change type.
| title | [string](#string) | | |
| content | [string](#string) | | |
| code | [int32](#int32) | | |
+| target | [string](#string) | | Target identification for consolidated results Format: instances/{instance}/databases/{database} |
+| type | [PlanCheckType](#bytebase-store-PlanCheckType) | | |
| sql_summary_report | [PlanCheckRunResult.Result.SqlSummaryReport](#bytebase-store-PlanCheckRunResult-Result-SqlSummaryReport) | | |
| sql_review_report | [PlanCheckRunResult.Result.SqlReviewReport](#bytebase-store-PlanCheckRunResult-Result-SqlReviewReport) | | |
@@ -3081,6 +3101,20 @@ Type is the database change type.
+
+<a name="bytebase-store-PlanCheckType"></a>
+
+### PlanCheckType
+
+
+| Name | Number | Description |
+| ---- | ------ | ----------- |
+| PLAN_CHECK_TYPE_UNSPECIFIED | 0 | |
+| PLAN_CHECK_TYPE_STATEMENT_ADVISE | 1 | |
+| PLAN_CHECK_TYPE_STATEMENT_SUMMARY_REPORT | 2 | |
+| PLAN_CHECK_TYPE_GHOST_SYNC | 3 | |
+
+
diff --git a/proto/gen/grpc-doc/store/index.html b/proto/gen/grpc-doc/store/index.html
index 38e4327dd3..7993fa817e 100644
--- a/proto/gen/grpc-doc/store/index.html
+++ b/proto/gen/grpc-doc/store/index.html
@@ -849,7 +849,11 @@
</li>
<li>
- <a href="#bytebase.store.PlanCheckRunConfig.GhostFlagsEntry"><span class="badge">M</span>PlanCheckRunConfig.GhostFlagsEntry</a>
+ <a href="#bytebase.store.PlanCheckRunConfig.CheckTarget"><span class="badge">M</span>PlanCheckRunConfig.CheckTarget</a>
+ </li>
+
+ <li>
+ <a href="#bytebase.store.PlanCheckRunConfig.CheckTarget.GhostFlagsEntry"><span class="badge">M</span>PlanCheckRunConfig.CheckTarget.GhostFlagsEntry</a>
</li>
<li>
@@ -869,6 +873,10 @@
</li>
+ <li>
+ <a href="#bytebase.store.PlanCheckType"><span class="badge">E</span>PlanCheckType</a>
+ </li>
+
</ul>
@@ -8596,52 +8604,76 @@ Leave it empty if there is no need to encrypt the zip file. </p></td>
<tbody>
<tr>
- <td>sheet_sha256</td>
- <td><a href="#string">string</a></td>
- <td></td>
- <td><p>The SHA256 hash of the sheet content (hex-encoded). </p></td>
+ <td>targets</td>
+ <td><a href="#bytebase.store.PlanCheckRunConfig.CheckTarget">PlanCheckRunConfig.CheckTarget</a></td>
+ <td>repeated</td>
+ <td><p> </p></td>
</tr>
+ </tbody>
+ </table>
+
+
+
+
+
+ <h3 id="bytebase.store.PlanCheckRunConfig.CheckTarget">PlanCheckRunConfig.CheckTarget</h3>
+ <p></p>
+
+
+ <table class="field-table">
+ <thead>
+ <tr><td>Field</td><td>Type</td><td>Label</td><td>Description</td></tr>
+ </thead>
+ <tbody>
+
<tr>
- <td>instance_id</td>
+ <td>target</td>
<td><a href="#string">string</a></td>
<td></td>
- <td><p> </p></td>
+ <td><p>Format: instances/{instance}/databases/{database} </p></td>
</tr>
<tr>
- <td>database_name</td>
+ <td>sheet_sha256</td>
<td><a href="#string">string</a></td>
<td></td>
<td><p> </p></td>
</tr>
- <tr>
- <td>ghost_flags</td>
- <td><a href="#bytebase.store.PlanCheckRunConfig.GhostFlagsEntry">PlanCheckRunConfig.GhostFlagsEntry</a></td>
- <td>repeated</td>
- <td><p> </p></td>
- </tr>
-
<tr>
<td>enable_prior_backup</td>
<td><a href="#bool">bool</a></td>
<td></td>
- <td><p>If set, a backup of the modified data will be created automatically before any changes are applied. </p></td>
+ <td><p> </p></td>
</tr>
<tr>
<td>enable_ghost</td>
<td><a href="#bool">bool</a></td>
<td></td>
- <td><p>Whether to use gh-ost for online schema migration. </p></td>
+ <td><p> </p></td>
</tr>
<tr>
<td>enable_sdl</td>
<td><a href="#bool">bool</a></td>
<td></td>
- <td><p>Whether this is a Schema Definition Language (SDL) change. </p></td>
+ <td><p> </p></td>
+ </tr>
+
+ <tr>
+ <td>ghost_flags</td>
+ <td><a href="#bytebase.store.PlanCheckRunConfig.CheckTarget.GhostFlagsEntry">PlanCheckRunConfig.CheckTarget.GhostFlagsEntry</a></td>
+ <td>repeated</td>
+ <td><p> </p></td>
+ </tr>
+
+ <tr>
+ <td>types</td>
+ <td><a href="#bytebase.store.PlanCheckType">PlanCheckType</a></td>
+ <td>repeated</td>
+ <td><p> </p></td>
</tr>
</tbody>
@@ -8651,7 +8683,7 @@ Leave it empty if there is no need to encrypt the zip file. </p></td>
- <h3 id="bytebase.store.PlanCheckRunConfig.GhostFlagsEntry">PlanCheckRunConfig.GhostFlagsEntry</h3>
+ <h3 id="bytebase.store.PlanCheckRunConfig.CheckTarget.GhostFlagsEntry">PlanCheckRunConfig.CheckTarget.GhostFlagsEntry</h3>
<p></p>
@@ -8751,6 +8783,21 @@ Leave it empty if there is no need to encrypt the zip file. </p></td>
<td><p> </p></td>
</tr>
+ <tr>
+ <td>target</td>
+ <td><a href="#string">string</a></td>
+ <td></td>
+ <td><p>Target identification for consolidated results
+Format: instances/{instance}/databases/{database} </p></td>
+ </tr>
+
+ <tr>
+ <td>type</td>
+ <td><a href="#bytebase.store.PlanCheckType">PlanCheckType</a></td>
+ <td></td>
+ <td><p> </p></td>
+ </tr>
+
<tr>
<td>sql_summary_report</td>
<td><a href="#bytebase.store.PlanCheckRunResult.Result.SqlSummaryReport">PlanCheckRunResult.Result.SqlSummaryReport</a></td>
@@ -8843,6 +8890,41 @@ Leave it empty if there is no need to encrypt the zip file. </p></td>
+ <h3 id="bytebase.store.PlanCheckType">PlanCheckType</h3>
+ <p></p>
+ <table class="enum-table">
+ <thead>
+ <tr><td>Name</td><td>Number</td><td>Description</td></tr>
+ </thead>
+ <tbody>
+
+ <tr>
+ <td>PLAN_CHECK_TYPE_UNSPECIFIED</td>
+ <td>0</td>
+ <td><p></p></td>
+ </tr>
+
+ <tr>
+ <td>PLAN_CHECK_TYPE_STATEMENT_ADVISE</td>
+ <td>1</td>
+ <td><p></p></td>
+ </tr>
+
+ <tr>
+ <td>PLAN_CHECK_TYPE_STATEMENT_SUMMARY_REPORT</td>
+ <td>2</td>
+ <td><p></p></td>
+ </tr>
+
+ <tr>
+ <td>PLAN_CHECK_TYPE_GHOST_SYNC</td>
+ <td>3</td>
+ <td><p></p></td>
+ </tr>
+
+ </tbody>
+ </table>
+
diff --git a/proto/store/store/plan_check_run.proto b/proto/store/store/plan_check_run.proto
index 50c6274387..6ad921d108 100644
--- a/proto/store/store/plan_check_run.proto
+++ b/proto/store/store/plan_check_run.proto
@@ -7,22 +7,26 @@ import "store/common.proto";
option go_package = "generated-go/store";
-message PlanCheckRunConfig {
- // The SHA256 hash of the sheet content (hex-encoded).
- string sheet_sha256 = 1;
- string instance_id = 2;
- string database_name = 3;
-
- map<string, string> ghost_flags = 4;
-
- // If set, a backup of the modified data will be created automatically before any changes are applied.
- bool enable_prior_backup = 5;
-
- // Whether to use gh-ost for online schema migration.
- bool enable_ghost = 6;
+enum PlanCheckType {
+ PLAN_CHECK_TYPE_UNSPECIFIED = 0;
+ PLAN_CHECK_TYPE_STATEMENT_ADVISE = 1;
+ PLAN_CHECK_TYPE_STATEMENT_SUMMARY_REPORT = 2;
+ PLAN_CHECK_TYPE_GHOST_SYNC = 3;
+}
- // Whether this is a Schema Definition Language (SDL) change.
- bool enable_sdl = 7;
+message PlanCheckRunConfig {
+ repeated CheckTarget targets = 1;
+
+ message CheckTarget {
+ // Format: instances/{instance}/databases/{database}
+ string target = 1;
+ string sheet_sha256 = 2;
+ bool enable_prior_backup = 3;
+ bool enable_ghost = 4;
+ bool enable_sdl = 5;
+ map<string, string> ghost_flags = 6;
+ repeated PlanCheckType types = 7;
+ }
}
message PlanCheckRunResult {
@@ -35,6 +39,11 @@ message PlanCheckRunResult {
string content = 3;
int32 code = 4;
+ // Target identification for consolidated results
+ // Format: instances/{instance}/databases/{database}
+ string target = 7;
+ PlanCheckType type = 8;
+
oneof report {
SqlSummaryReport sql_summary_report = 5;
SqlReviewReport sql_review_report = 6;