Skip to content

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

refactor: derive plan check run config at runtime (#18762)

p0ny6e9a0455f6cd
diff --git a/backend/api/v1/plan_service.go b/backend/api/v1/plan_service.go
index 0c8e25bf52..185b444886 100644
--- a/backend/api/v1/plan_service.go
+++ b/backend/api/v1/plan_service.go
@@ -13,6 +13,7 @@ import (
"github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/common/log"
"github.com/bytebase/bytebase/backend/runner/approval"
+ "github.com/bytebase/bytebase/backend/runner/plancheck"
"github.com/bytebase/bytebase/backend/component/bus"
"github.com/bytebase/bytebase/backend/component/iam"
@@ -727,61 +728,9 @@ func storePlanConfigHasCreateDatabase(plan *storepb.PlanConfig) bool {
// getPlanCheckRunFromPlan returns the 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 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]
- }
- }
-
- // Plan checks only run for sheet-based migrations (releases are skipped above).
- // Sheet-based migrations are always imperative (MIGRATE), never declarative (SDL).
- enableGhost := config.ChangeDatabaseConfig.EnableGhost
-
- for _, target := range databases {
- types := []storepb.PlanCheckType{
- storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_ADVISE,
- storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_SUMMARY_REPORT,
- }
- 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,
- GhostFlags: config.ChangeDatabaseConfig.GhostFlags,
- Types: types,
- })
- }
- default:
- return nil, errors.Errorf("unknown spec config type %T", config)
- }
+ targets, err := plancheck.DeriveCheckTargets(project, plan, databaseGroup)
+ if err != nil {
+ return nil, err
}
if len(targets) == 0 {
@@ -791,7 +740,6 @@ func getPlanCheckRunFromPlan(project *store.ProjectMessage, plan *store.PlanMess
return &store.PlanCheckRunMessage{
PlanUID: plan.UID,
Status: store.PlanCheckRunStatusRunning,
- Config: &storepb.PlanCheckRunConfig{Targets: targets},
}, nil
}
diff --git a/backend/generated-go/store/plan_check_run.pb.go b/backend/generated-go/store/plan_check_run.pb.go
index ba4c727f99..f2380ed9a7 100644
--- a/backend/generated-go/store/plan_check_run.pb.go
+++ b/backend/generated-go/store/plan_check_run.pb.go
@@ -73,50 +73,6 @@ func (PlanCheckType) EnumDescriptor() ([]byte, []int) {
return file_store_plan_check_run_proto_rawDescGZIP(), []int{0}
}
-type PlanCheckRunConfig struct {
- 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
-}
-
-func (x *PlanCheckRunConfig) Reset() {
- *x = PlanCheckRunConfig{}
- mi := &file_store_plan_check_run_proto_msgTypes[0]
- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
- ms.StoreMessageInfo(mi)
-}
-
-func (x *PlanCheckRunConfig) String() string {
- return protoimpl.X.MessageStringOf(x)
-}
-
-func (*PlanCheckRunConfig) ProtoMessage() {}
-
-func (x *PlanCheckRunConfig) ProtoReflect() protoreflect.Message {
- mi := &file_store_plan_check_run_proto_msgTypes[0]
- 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.ProtoReflect.Descriptor instead.
-func (*PlanCheckRunConfig) Descriptor() ([]byte, []int) {
- return file_store_plan_check_run_proto_rawDescGZIP(), []int{0}
-}
-
-func (x *PlanCheckRunConfig) GetTargets() []*PlanCheckRunConfig_CheckTarget {
- if x != nil {
- return x.Targets
- }
- return nil
-}
-
type PlanCheckRunResult struct {
state protoimpl.MessageState `protogen:"open.v1"`
Results []*PlanCheckRunResult_Result `protobuf:"bytes,1,rep,name=results,proto3" json:"results,omitempty"`
@@ -127,7 +83,7 @@ type PlanCheckRunResult struct {
func (x *PlanCheckRunResult) Reset() {
*x = PlanCheckRunResult{}
- mi := &file_store_plan_check_run_proto_msgTypes[1]
+ mi := &file_store_plan_check_run_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -139,7 +95,7 @@ func (x *PlanCheckRunResult) String() string {
func (*PlanCheckRunResult) ProtoMessage() {}
func (x *PlanCheckRunResult) ProtoReflect() protoreflect.Message {
- mi := &file_store_plan_check_run_proto_msgTypes[1]
+ mi := &file_store_plan_check_run_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -152,7 +108,7 @@ func (x *PlanCheckRunResult) ProtoReflect() protoreflect.Message {
// Deprecated: Use PlanCheckRunResult.ProtoReflect.Descriptor instead.
func (*PlanCheckRunResult) Descriptor() ([]byte, []int) {
- return file_store_plan_check_run_proto_rawDescGZIP(), []int{1}
+ return file_store_plan_check_run_proto_rawDescGZIP(), []int{0}
}
func (x *PlanCheckRunResult) GetResults() []*PlanCheckRunResult_Result {
@@ -178,7 +134,7 @@ type ChangedResources struct {
func (x *ChangedResources) Reset() {
*x = ChangedResources{}
- mi := &file_store_plan_check_run_proto_msgTypes[2]
+ mi := &file_store_plan_check_run_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -190,7 +146,7 @@ func (x *ChangedResources) String() string {
func (*ChangedResources) ProtoMessage() {}
func (x *ChangedResources) ProtoReflect() protoreflect.Message {
- mi := &file_store_plan_check_run_proto_msgTypes[2]
+ mi := &file_store_plan_check_run_proto_msgTypes[1]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -203,7 +159,7 @@ func (x *ChangedResources) ProtoReflect() protoreflect.Message {
// Deprecated: Use ChangedResources.ProtoReflect.Descriptor instead.
func (*ChangedResources) Descriptor() ([]byte, []int) {
- return file_store_plan_check_run_proto_rawDescGZIP(), []int{2}
+ return file_store_plan_check_run_proto_rawDescGZIP(), []int{1}
}
func (x *ChangedResources) GetDatabases() []*ChangedResourceDatabase {
@@ -223,7 +179,7 @@ type ChangedResourceDatabase struct {
func (x *ChangedResourceDatabase) Reset() {
*x = ChangedResourceDatabase{}
- mi := &file_store_plan_check_run_proto_msgTypes[3]
+ mi := &file_store_plan_check_run_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -235,7 +191,7 @@ func (x *ChangedResourceDatabase) String() string {
func (*ChangedResourceDatabase) ProtoMessage() {}
func (x *ChangedResourceDatabase) ProtoReflect() protoreflect.Message {
- mi := &file_store_plan_check_run_proto_msgTypes[3]
+ mi := &file_store_plan_check_run_proto_msgTypes[2]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -248,7 +204,7 @@ func (x *ChangedResourceDatabase) ProtoReflect() protoreflect.Message {
// Deprecated: Use ChangedResourceDatabase.ProtoReflect.Descriptor instead.
func (*ChangedResourceDatabase) Descriptor() ([]byte, []int) {
- return file_store_plan_check_run_proto_rawDescGZIP(), []int{3}
+ return file_store_plan_check_run_proto_rawDescGZIP(), []int{2}
}
func (x *ChangedResourceDatabase) GetName() string {
@@ -275,7 +231,7 @@ type ChangedResourceSchema struct {
func (x *ChangedResourceSchema) Reset() {
*x = ChangedResourceSchema{}
- mi := &file_store_plan_check_run_proto_msgTypes[4]
+ mi := &file_store_plan_check_run_proto_msgTypes[3]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -287,7 +243,7 @@ func (x *ChangedResourceSchema) String() string {
func (*ChangedResourceSchema) ProtoMessage() {}
func (x *ChangedResourceSchema) ProtoReflect() protoreflect.Message {
- mi := &file_store_plan_check_run_proto_msgTypes[4]
+ mi := &file_store_plan_check_run_proto_msgTypes[3]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -300,7 +256,7 @@ func (x *ChangedResourceSchema) ProtoReflect() protoreflect.Message {
// Deprecated: Use ChangedResourceSchema.ProtoReflect.Descriptor instead.
func (*ChangedResourceSchema) Descriptor() ([]byte, []int) {
- return file_store_plan_check_run_proto_rawDescGZIP(), []int{4}
+ return file_store_plan_check_run_proto_rawDescGZIP(), []int{3}
}
func (x *ChangedResourceSchema) GetName() string {
@@ -328,7 +284,7 @@ type ChangedResourceTable struct {
func (x *ChangedResourceTable) Reset() {
*x = ChangedResourceTable{}
- mi := &file_store_plan_check_run_proto_msgTypes[5]
+ mi := &file_store_plan_check_run_proto_msgTypes[4]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -340,7 +296,7 @@ func (x *ChangedResourceTable) String() string {
func (*ChangedResourceTable) ProtoMessage() {}
func (x *ChangedResourceTable) ProtoReflect() protoreflect.Message {
- mi := &file_store_plan_check_run_proto_msgTypes[5]
+ mi := &file_store_plan_check_run_proto_msgTypes[4]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -353,7 +309,7 @@ func (x *ChangedResourceTable) ProtoReflect() protoreflect.Message {
// Deprecated: Use ChangedResourceTable.ProtoReflect.Descriptor instead.
func (*ChangedResourceTable) Descriptor() ([]byte, []int) {
- return file_store_plan_check_run_proto_rawDescGZIP(), []int{5}
+ return file_store_plan_check_run_proto_rawDescGZIP(), []int{4}
}
func (x *ChangedResourceTable) GetName() string {
@@ -370,91 +326,6 @@ 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"`
- 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) 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"`
@@ -476,7 +347,7 @@ type PlanCheckRunResult_Result struct {
func (x *PlanCheckRunResult_Result) Reset() {
*x = PlanCheckRunResult_Result{}
- mi := &file_store_plan_check_run_proto_msgTypes[8]
+ mi := &file_store_plan_check_run_proto_msgTypes[5]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -488,7 +359,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[8]
+ mi := &file_store_plan_check_run_proto_msgTypes[5]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -501,7 +372,7 @@ func (x *PlanCheckRunResult_Result) ProtoReflect() protoreflect.Message {
// Deprecated: Use PlanCheckRunResult_Result.ProtoReflect.Descriptor instead.
func (*PlanCheckRunResult_Result) Descriptor() ([]byte, []int) {
- return file_store_plan_check_run_proto_rawDescGZIP(), []int{1, 0}
+ return file_store_plan_check_run_proto_rawDescGZIP(), []int{0, 0}
}
func (x *PlanCheckRunResult_Result) GetStatus() Advice_Status {
@@ -599,7 +470,7 @@ type PlanCheckRunResult_Result_SqlSummaryReport struct {
func (x *PlanCheckRunResult_Result_SqlSummaryReport) Reset() {
*x = PlanCheckRunResult_Result_SqlSummaryReport{}
- mi := &file_store_plan_check_run_proto_msgTypes[9]
+ mi := &file_store_plan_check_run_proto_msgTypes[6]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -611,7 +482,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[9]
+ mi := &file_store_plan_check_run_proto_msgTypes[6]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -624,7 +495,7 @@ func (x *PlanCheckRunResult_Result_SqlSummaryReport) ProtoReflect() protoreflect
// Deprecated: Use PlanCheckRunResult_Result_SqlSummaryReport.ProtoReflect.Descriptor instead.
func (*PlanCheckRunResult_Result_SqlSummaryReport) Descriptor() ([]byte, []int) {
- return file_store_plan_check_run_proto_rawDescGZIP(), []int{1, 0, 0}
+ return file_store_plan_check_run_proto_rawDescGZIP(), []int{0, 0, 0}
}
func (x *PlanCheckRunResult_Result_SqlSummaryReport) GetStatementTypes() []string {
@@ -659,7 +530,7 @@ type PlanCheckRunResult_Result_SqlReviewReport struct {
func (x *PlanCheckRunResult_Result_SqlReviewReport) Reset() {
*x = PlanCheckRunResult_Result_SqlReviewReport{}
- mi := &file_store_plan_check_run_proto_msgTypes[10]
+ mi := &file_store_plan_check_run_proto_msgTypes[7]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -671,7 +542,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[10]
+ mi := &file_store_plan_check_run_proto_msgTypes[7]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -684,7 +555,7 @@ func (x *PlanCheckRunResult_Result_SqlReviewReport) ProtoReflect() protoreflect.
// Deprecated: Use PlanCheckRunResult_Result_SqlReviewReport.ProtoReflect.Descriptor instead.
func (*PlanCheckRunResult_Result_SqlReviewReport) Descriptor() ([]byte, []int) {
- return file_store_plan_check_run_proto_rawDescGZIP(), []int{1, 0, 1}
+ return file_store_plan_check_run_proto_rawDescGZIP(), []int{0, 0, 1}
}
func (x *PlanCheckRunResult_Result_SqlReviewReport) GetStartPosition() *Position {
@@ -705,20 +576,7 @@ 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\"\xd1\x03\n" +
- "\x12PlanCheckRunConfig\x12H\n" +
- "\atargets\x18\x01 \x03(\v2..bytebase.store.PlanCheckRunConfig.CheckTargetR\atargets\x1a\xf0\x02\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_\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\"\xe3\x06\n" +
+ "\x1astore/plan_check_run.proto\x12\x0ebytebase.store\x1a\x12store/advice.proto\x1a\x12store/common.proto\"\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\xf1\x05\n" +
@@ -771,43 +629,37 @@ func file_store_plan_check_run_proto_rawDescGZIP() []byte {
}
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_msgTypes = make([]protoimpl.MessageInfo, 8)
var file_store_plan_check_run_proto_goTypes = []any{
(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
+ (*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
+ (*PlanCheckRunResult_Result)(nil), // 6: bytebase.store.PlanCheckRunResult.Result
+ (*PlanCheckRunResult_Result_SqlSummaryReport)(nil), // 7: bytebase.store.PlanCheckRunResult.Result.SqlSummaryReport
+ (*PlanCheckRunResult_Result_SqlReviewReport)(nil), // 8: bytebase.store.PlanCheckRunResult.Result.SqlReviewReport
+ (Advice_Status)(0), // 9: bytebase.store.Advice.Status
+ (*Position)(nil), // 10: bytebase.store.Position
}
var file_store_plan_check_run_proto_depIdxs = []int32{
- 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
+ 6, // 0: bytebase.store.PlanCheckRunResult.results:type_name -> bytebase.store.PlanCheckRunResult.Result
+ 3, // 1: bytebase.store.ChangedResources.databases:type_name -> bytebase.store.ChangedResourceDatabase
+ 4, // 2: bytebase.store.ChangedResourceDatabase.schemas:type_name -> bytebase.store.ChangedResourceSchema
+ 5, // 3: bytebase.store.ChangedResourceSchema.tables:type_name -> bytebase.store.ChangedResourceTable
+ 9, // 4: bytebase.store.PlanCheckRunResult.Result.status:type_name -> bytebase.store.Advice.Status
+ 0, // 5: bytebase.store.PlanCheckRunResult.Result.type:type_name -> bytebase.store.PlanCheckType
+ 7, // 6: bytebase.store.PlanCheckRunResult.Result.sql_summary_report:type_name -> bytebase.store.PlanCheckRunResult.Result.SqlSummaryReport
+ 8, // 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
+ 10, // 9: bytebase.store.PlanCheckRunResult.Result.SqlReviewReport.start_position:type_name -> bytebase.store.Position
+ 10, // 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
}
func init() { file_store_plan_check_run_proto_init() }
@@ -817,7 +669,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[8].OneofWrappers = []any{
+ file_store_plan_check_run_proto_msgTypes[5].OneofWrappers = []any{
(*PlanCheckRunResult_Result_SqlSummaryReport_)(nil),
(*PlanCheckRunResult_Result_SqlReviewReport_)(nil),
}
@@ -827,7 +679,7 @@ func file_store_plan_check_run_proto_init() {
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: 1,
- NumMessages: 11,
+ NumMessages: 8,
NumExtensions: 0,
NumServices: 0,
},
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 c34b1aa4a3..3309c588f9 100644
--- a/backend/generated-go/store/plan_check_run_equal.pb.go
+++ b/backend/generated-go/store/plan_check_run_equal.pb.go
@@ -3,66 +3,6 @@
package store
-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.EnablePriorBackup != y.EnablePriorBackup {
- return false
- }
- if x.EnableGhost != y.EnableGhost {
- return false
- }
- if len(x.GhostFlags) != len(y.GhostFlags) {
- return false
- }
- for k := range x.GhostFlags {
- _, ok := y.GhostFlags[k]
- if !ok {
- return false
- }
- if x.GhostFlags[k] != y.GhostFlags[k] {
- return false
- }
- }
- if len(x.Types) != len(y.Types) {
- return false
- }
- for i := 0; i < len(x.Types); i++ {
- if x.Types[i] != y.Types[i] {
- return false
- }
- }
- 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
-}
-
func (x *PlanCheckRunResult_Result_SqlSummaryReport) Equal(y *PlanCheckRunResult_Result_SqlSummaryReport) bool {
if x == y {
return true
diff --git a/backend/migrator/migration/3.14/0021##remove_plan_check_run_config_payload.sql b/backend/migrator/migration/3.14/0021##remove_plan_check_run_config_payload.sql
new file mode 100644
index 0000000000..adb856e103
--- /dev/null
+++ b/backend/migrator/migration/3.14/0021##remove_plan_check_run_config_payload.sql
@@ -0,0 +1,3 @@
+-- Drop config and payload columns from plan_check_run
+ALTER TABLE plan_check_run DROP COLUMN config;
+ALTER TABLE plan_check_run DROP COLUMN payload;
diff --git a/backend/migrator/migration/LATEST.sql b/backend/migrator/migration/LATEST.sql
index 1bd4f29461..3a8abdd9e4 100644
--- a/backend/migrator/migration/LATEST.sql
+++ b/backend/migrator/migration/LATEST.sql
@@ -216,11 +216,8 @@ 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')),
- -- 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 '{}'
+ result jsonb NOT NULL DEFAULT '{}'
);
CREATE UNIQUE INDEX idx_plan_check_run_unique_plan_id ON plan_check_run(plan_id);
diff --git a/backend/migrator/migrator_test.go b/backend/migrator/migrator_test.go
index 001b8abb11..636c0d226a 100644
--- a/backend/migrator/migrator_test.go
+++ b/backend/migrator/migrator_test.go
@@ -12,8 +12,8 @@ import (
func TestLatestVersion(t *testing.T) {
files, err := getSortedVersionedFiles()
require.NoError(t, err)
- require.Equal(t, semver.MustParse("3.14.20"), *files[len(files)-1].version)
- require.Equal(t, "migration/3.14/0020##remove_task_run_code_and_sheet_sha256.sql", files[len(files)-1].path)
+ require.Equal(t, semver.MustParse("3.14.21"), *files[len(files)-1].version)
+ require.Equal(t, "migration/3.14/0021##remove_plan_check_run_config_payload.sql", files[len(files)-1].path)
}
func TestVersionUnique(t *testing.T) {
diff --git a/backend/runner/plancheck/check_target.go b/backend/runner/plancheck/check_target.go
new file mode 100644
index 0000000000..354f79543a
--- /dev/null
+++ b/backend/runner/plancheck/check_target.go
@@ -0,0 +1,20 @@
+package plancheck
+
+import storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+
+// CheckTarget represents a derived check target from a plan.
+// This is computed at runtime from the plan's specs, not stored.
+type CheckTarget struct {
+ // Target is the database resource name: instances/{instance}/databases/{database}
+ Target string
+ // SheetSha256 is the content hash of the SQL sheet
+ SheetSha256 string
+ // EnablePriorBackup indicates if backup before migration is enabled
+ EnablePriorBackup bool
+ // EnableGhost indicates if gh-ost online migration is enabled
+ EnableGhost bool
+ // GhostFlags are configuration flags for gh-ost
+ GhostFlags map[string]string
+ // Types are the plan check types to run for this target
+ Types []storepb.PlanCheckType
+}
diff --git a/backend/runner/plancheck/derive.go b/backend/runner/plancheck/derive.go
new file mode 100644
index 0000000000..68cfb08bcf
--- /dev/null
+++ b/backend/runner/plancheck/derive.go
@@ -0,0 +1,70 @@
+package plancheck
+
+import (
+ "github.com/pkg/errors"
+
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
+ "github.com/bytebase/bytebase/backend/store"
+)
+
+// DeriveCheckTargets derives check targets from a plan and optional database group.
+// This replaces the stored config by computing targets at runtime.
+func DeriveCheckTargets(project *store.ProjectMessage, plan *store.PlanMessage, databaseGroup *v1pb.DatabaseGroup) ([]*CheckTarget, error) {
+ var targets []*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]
+ }
+ }
+
+ enableGhost := config.ChangeDatabaseConfig.EnableGhost
+
+ for _, target := range databases {
+ types := []storepb.PlanCheckType{
+ storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_ADVISE,
+ storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_SUMMARY_REPORT,
+ }
+ if enableGhost {
+ types = append(types, storepb.PlanCheckType_PLAN_CHECK_TYPE_GHOST_SYNC)
+ }
+
+ targets = append(targets, &CheckTarget{
+ Target: target,
+ SheetSha256: config.ChangeDatabaseConfig.SheetSha256,
+ EnablePriorBackup: config.ChangeDatabaseConfig.EnablePriorBackup,
+ EnableGhost: config.ChangeDatabaseConfig.EnableGhost,
+ GhostFlags: config.ChangeDatabaseConfig.GhostFlags,
+ Types: types,
+ })
+ }
+ default:
+ return nil, errors.Errorf("unknown spec config type %T", config)
+ }
+ }
+
+ return targets, nil
+}
diff --git a/backend/runner/plancheck/executor.go b/backend/runner/plancheck/executor.go
index c94ad1b831..641c9e1d5b 100644
--- a/backend/runner/plancheck/executor.go
+++ b/backend/runner/plancheck/executor.go
@@ -9,5 +9,5 @@ import (
// Executor is the plan check executor.
type Executor interface {
// RunForTarget will be called periodically by the plan check scheduler for each target
- RunForTarget(ctx context.Context, target *storepb.PlanCheckRunConfig_CheckTarget) (results []*storepb.PlanCheckRunResult_Result, err error)
+ RunForTarget(ctx context.Context, target *CheckTarget) (results []*storepb.PlanCheckRunResult_Result, err error)
}
diff --git a/backend/runner/plancheck/executor_combined.go b/backend/runner/plancheck/executor_combined.go
index 91c175061f..85fa09f553 100644
--- a/backend/runner/plancheck/executor_combined.go
+++ b/backend/runner/plancheck/executor_combined.go
@@ -31,7 +31,7 @@ func NewCombinedExecutor(
}
// RunForTarget runs all checks for the given target.
-func (e *CombinedExecutor) RunForTarget(ctx context.Context, target *storepb.PlanCheckRunConfig_CheckTarget) ([]*storepb.PlanCheckRunResult_Result, error) {
+func (e *CombinedExecutor) RunForTarget(ctx context.Context, target *CheckTarget) ([]*storepb.PlanCheckRunResult_Result, error) {
var allResults []*storepb.PlanCheckRunResult_Result
for _, checkType := range target.Types {
@@ -59,7 +59,7 @@ func (e *CombinedExecutor) RunForTarget(ctx context.Context, target *storepb.Pla
return allResults, nil
}
-func (e *CombinedExecutor) runCheck(ctx context.Context, target *storepb.PlanCheckRunConfig_CheckTarget, checkType storepb.PlanCheckType) ([]*storepb.PlanCheckRunResult_Result, error) {
+func (e *CombinedExecutor) runCheck(ctx context.Context, target *CheckTarget, checkType storepb.PlanCheckType) ([]*storepb.PlanCheckRunResult_Result, error) {
switch checkType {
case storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_ADVISE:
return e.runStatementAdvise(ctx, target)
@@ -72,7 +72,7 @@ func (e *CombinedExecutor) runCheck(ctx context.Context, target *storepb.PlanChe
}
}
-func (e *CombinedExecutor) runStatementAdvise(ctx context.Context, target *storepb.PlanCheckRunConfig_CheckTarget) ([]*storepb.PlanCheckRunResult_Result, error) {
+func (e *CombinedExecutor) runStatementAdvise(ctx context.Context, target *CheckTarget) ([]*storepb.PlanCheckRunResult_Result, error) {
executor := &StatementAdviseExecutor{
store: e.store,
sheetManager: e.sheetManager,
@@ -81,7 +81,7 @@ func (e *CombinedExecutor) runStatementAdvise(ctx context.Context, target *store
return executor.RunForTarget(ctx, target)
}
-func (e *CombinedExecutor) runStatementReport(ctx context.Context, target *storepb.PlanCheckRunConfig_CheckTarget) ([]*storepb.PlanCheckRunResult_Result, error) {
+func (e *CombinedExecutor) runStatementReport(ctx context.Context, target *CheckTarget) ([]*storepb.PlanCheckRunResult_Result, error) {
executor := &StatementReportExecutor{
store: e.store,
sheetManager: e.sheetManager,
@@ -90,7 +90,7 @@ func (e *CombinedExecutor) runStatementReport(ctx context.Context, target *store
return executor.RunForTarget(ctx, target)
}
-func (e *CombinedExecutor) runGhostSync(ctx context.Context, target *storepb.PlanCheckRunConfig_CheckTarget) ([]*storepb.PlanCheckRunResult_Result, error) {
+func (e *CombinedExecutor) runGhostSync(ctx context.Context, target *CheckTarget) ([]*storepb.PlanCheckRunResult_Result, error) {
executor := &GhostSyncExecutor{
store: e.store,
dbFactory: e.dbFactory,
diff --git a/backend/runner/plancheck/ghost_sync_executor.go b/backend/runner/plancheck/ghost_sync_executor.go
index 8c0636e9d8..121117d664 100644
--- a/backend/runner/plancheck/ghost_sync_executor.go
+++ b/backend/runner/plancheck/ghost_sync_executor.go
@@ -38,7 +38,7 @@ type GhostSyncExecutor struct {
}
// 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) {
+func (e *GhostSyncExecutor) RunForTarget(ctx context.Context, target *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.
diff --git a/backend/runner/plancheck/scheduler.go b/backend/runner/plancheck/scheduler.go
index 1eccc5b1da..7957dcf732 100644
--- a/backend/runner/plancheck/scheduler.go
+++ b/backend/runner/plancheck/scheduler.go
@@ -10,10 +10,13 @@ import (
"github.com/pkg/errors"
+ "github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/common/log"
"github.com/bytebase/bytebase/backend/component/bus"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
"github.com/bytebase/bytebase/backend/store"
+ "github.com/bytebase/bytebase/backend/utils"
)
const (
@@ -97,9 +100,43 @@ func (s *Scheduler) runPlanCheckRun(ctx context.Context, planCheckRun *store.Pla
defer cancel()
s.bus.RunningPlanCheckRunsCancelFunc.Store(planCheckRun.UID, cancel)
+ // Fetch plan to derive check targets at runtime
+ plan, err := s.store.GetPlan(ctxWithCancel, &store.FindPlanMessage{UID: &planCheckRun.PlanUID})
+ if err != nil {
+ s.markPlanCheckRunFailed(ctx, planCheckRun, err.Error())
+ return
+ }
+ if plan == nil {
+ s.markPlanCheckRunFailed(ctx, planCheckRun, "plan not found")
+ return
+ }
+
+ project, err := s.store.GetProject(ctxWithCancel, &store.FindProjectMessage{ResourceID: &plan.ProjectID})
+ if err != nil {
+ s.markPlanCheckRunFailed(ctx, planCheckRun, err.Error())
+ return
+ }
+ if project == nil {
+ s.markPlanCheckRunFailed(ctx, planCheckRun, "project not found")
+ return
+ }
+
+ // Get database group if needed (for spec expansion)
+ databaseGroup, err := s.getDatabaseGroupForPlan(ctxWithCancel, plan)
+ if err != nil {
+ s.markPlanCheckRunFailed(ctx, planCheckRun, err.Error())
+ return
+ }
+
+ // Derive check targets from plan
+ targets, err := DeriveCheckTargets(project, plan, databaseGroup)
+ if err != nil {
+ s.markPlanCheckRunFailed(ctx, planCheckRun, err.Error())
+ return
+ }
+
var results []*storepb.PlanCheckRunResult_Result
- var err error
- for _, target := range planCheckRun.Config.Targets {
+ for _, target := range targets {
targetResults, targetErr := s.executor.RunForTarget(ctxWithCancel, target)
if targetErr != nil {
err = targetErr
@@ -173,3 +210,60 @@ func (s *Scheduler) markPlanCheckRunCanceled(ctx context.Context, planCheckRun *
slog.Error("failed to mark plan check run canceled", log.BBError(err))
}
}
+
+// getDatabaseGroupForPlan checks if the plan targets a database group and returns it with matched databases.
+// Returns nil if the plan does not target a database group.
+func (s *Scheduler) getDatabaseGroupForPlan(ctx context.Context, plan *store.PlanMessage) (*v1pb.DatabaseGroup, error) {
+ for _, spec := range plan.Config.Specs {
+ cfg, ok := spec.Config.(*storepb.PlanConfig_Spec_ChangeDatabaseConfig)
+ if !ok {
+ continue
+ }
+ if len(cfg.ChangeDatabaseConfig.Targets) != 1 {
+ continue
+ }
+
+ target := cfg.ChangeDatabaseConfig.Targets[0]
+ _, databaseGroupID, err := common.GetProjectIDDatabaseGroupID(target)
+ if err != nil {
+ // Not a database group reference, skip
+ continue
+ }
+
+ // Found a database group reference - fetch and expand it
+ dbGroup, err := s.store.GetDatabaseGroup(ctx, &store.FindDatabaseGroupMessage{
+ ResourceID: &databaseGroupID,
+ ProjectID: &plan.ProjectID,
+ })
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to get database group %q", target)
+ }
+ if dbGroup == nil {
+ return nil, errors.Errorf("database group %q not found", target)
+ }
+
+ // Get all databases in the project to compute matches
+ allDatabases, err := s.store.ListDatabases(ctx, &store.FindDatabaseMessage{ProjectID: &plan.ProjectID})
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to list databases for project %q", plan.ProjectID)
+ }
+
+ // Compute matched databases using CEL expression
+ matchedDatabases, err := utils.GetMatchedDatabasesInDatabaseGroup(ctx, dbGroup, allDatabases)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to get matched databases for group %q", databaseGroupID)
+ }
+
+ // Convert to v1pb.DatabaseGroup format
+ result := &v1pb.DatabaseGroup{
+ Name: target,
+ }
+ for _, db := range matchedDatabases {
+ result.MatchedDatabases = append(result.MatchedDatabases, &v1pb.DatabaseGroup_Database{
+ Name: common.FormatDatabase(db.InstanceID, db.DatabaseName),
+ })
+ }
+ return result, nil
+ }
+ return nil, nil
+}
diff --git a/backend/runner/plancheck/statement_advise_executor.go b/backend/runner/plancheck/statement_advise_executor.go
index 9b2416a4cb..7a4dbdcf7d 100644
--- a/backend/runner/plancheck/statement_advise_executor.go
+++ b/backend/runner/plancheck/statement_advise_executor.go
@@ -40,7 +40,7 @@ type StatementAdviseExecutor struct {
}
// 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) {
+func (e *StatementAdviseExecutor) RunForTarget(ctx context.Context, target *CheckTarget) ([]*storepb.PlanCheckRunResult_Result, error) {
fullSheet, err := e.store.GetSheetFull(ctx, target.SheetSha256)
if err != nil {
return nil, err
diff --git a/backend/runner/plancheck/statement_report_executor.go b/backend/runner/plancheck/statement_report_executor.go
index 72385922d3..53a27f3d0c 100644
--- a/backend/runner/plancheck/statement_report_executor.go
+++ b/backend/runner/plancheck/statement_report_executor.go
@@ -47,7 +47,7 @@ type StatementReportExecutor struct {
}
// 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) {
+func (e *StatementReportExecutor) RunForTarget(ctx context.Context, target *CheckTarget) ([]*storepb.PlanCheckRunResult_Result, error) {
fullSheet, err := e.store.GetSheetFull(ctx, target.SheetSha256)
if err != nil {
return nil, err
diff --git a/backend/store/plan_check_run.go b/backend/store/plan_check_run.go
index 3d9ea30a13..c099e55e01 100644
--- a/backend/store/plan_check_run.go
+++ b/backend/store/plan_check_run.go
@@ -35,7 +35,6 @@ type PlanCheckRunMessage struct {
PlanUID int64
Status PlanCheckRunStatus
- Config *storepb.PlanCheckRunConfig
Result *storepb.PlanCheckRunResult
}
@@ -49,25 +48,20 @@ type FindPlanCheckRunMessage struct {
// CreatePlanCheckRun creates or replaces the plan check run for a plan.
func (s *Store) CreatePlanCheckRun(ctx context.Context, create *PlanCheckRunMessage) error {
- config, err := protojson.Marshal(create.Config)
- if err != nil {
- return errors.Wrapf(err, "failed to marshal config")
- }
result, err := protojson.Marshal(create.Result)
if err != nil {
return errors.Wrapf(err, "failed to marshal result")
}
query := `
- INSERT INTO plan_check_run (plan_id, status, config, result)
- VALUES ($1, $2, $3, $4)
+ INSERT INTO plan_check_run (plan_id, status, result)
+ VALUES ($1, $2, $3)
ON CONFLICT (plan_id) DO UPDATE SET
status = EXCLUDED.status,
- config = EXCLUDED.config,
result = EXCLUDED.result,
updated_at = now()
`
- if _, err := s.GetDB().ExecContext(ctx, query, create.PlanUID, create.Status, config, result); err != nil {
+ if _, err := s.GetDB().ExecContext(ctx, query, create.PlanUID, create.Status, result); err != nil {
return errors.Wrapf(err, "failed to upsert plan check run")
}
return nil
@@ -82,7 +76,6 @@ SELECT
plan_check_run.updated_at,
plan_check_run.plan_id,
plan_check_run.status,
- plan_check_run.config,
plan_check_run.result
FROM plan_check_run
WHERE TRUE`)
@@ -116,24 +109,19 @@ WHERE TRUE`)
var planCheckRuns []*PlanCheckRunMessage
for rows.Next() {
planCheckRun := PlanCheckRunMessage{
- Config: &storepb.PlanCheckRunConfig{},
Result: &storepb.PlanCheckRunResult{},
}
- var config, result string
+ var 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
}
diff --git a/docs/plans/2026-01-05-plan-check-run-runtime-derivation-impl.md b/docs/plans/2026-01-05-plan-check-run-runtime-derivation-impl.md
new file mode 100644
index 0000000000..b6dfc33ee0
--- /dev/null
+++ b/docs/plans/2026-01-05-plan-check-run-runtime-derivation-impl.md
@@ -0,0 +1,838 @@
+# Plan Check Run Runtime Derivation Implementation Plan
+
+> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
+
+**Goal:** Refactor plan check run to derive configuration from the plan at runtime instead of storing a self-contained copy.
+
+**Architecture:** Remove `config` and `payload` columns from `plan_check_run` table. The scheduler fetches the plan and calls a derivation function to get check targets at runtime. Executors receive derived config instead of stored config.
+
+**Tech Stack:** Go, PostgreSQL, Protocol Buffers
+
+---
+
+## Task 1: Create Database Migration
+
+**Files:**
+- Create: `backend/migrator/migration/3.14/0021##remove_plan_check_run_config_payload.sql`
+- Modify: `backend/migrator/migration/LATEST.sql:213-230`
+- Modify: `backend/migrator/migrator_test.go:15-16`
+
+**Step 1: Create migration file**
+
+```sql
+-- Drop config and payload columns from plan_check_run
+ALTER TABLE plan_check_run DROP COLUMN config;
+ALTER TABLE plan_check_run DROP COLUMN payload;
+```
+
+**Step 2: Update LATEST.sql**
+
+Change:
+```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')),
+ -- 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 '{}'
+);
+```
+
+To:
+```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')),
+ -- Stored as PlanCheckRunResult (proto/store/store/plan_check_run.proto)
+ result jsonb NOT NULL DEFAULT '{}'
+);
+```
+
+**Step 3: Update migrator_test.go**
+
+Change:
+```go
+require.Equal(t, semver.MustParse("3.14.20"), *files[len(files)-1].version)
+require.Equal(t, "migration/3.14/0020##remove_task_run_code_and_sheet_sha256.sql", files[len(files)-1].path)
+```
+
+To:
+```go
+require.Equal(t, semver.MustParse("3.14.21"), *files[len(files)-1].version)
+require.Equal(t, "migration/3.14/0021##remove_plan_check_run_config_payload.sql", files[len(files)-1].path)
+```
+
+**Step 4: Commit**
+
+```bash
+but commit plan-check-run-refactor -m "chore(migration): drop config and payload from plan_check_run"
+```
+
+---
+
+## Task 2: Update Proto - Remove PlanCheckRunConfig
+
+**Files:**
+- Modify: `proto/store/store/plan_check_run.proto:17-29`
+
+**Step 1: Remove PlanCheckRunConfig message**
+
+Delete the `PlanCheckRunConfig` message and `CheckTarget` nested message (lines 17-29):
+
+```protobuf
+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;
+ map<string, string> ghost_flags = 6;
+ repeated PlanCheckType types = 7;
+ }
+}
+```
+
+**Step 2: Run buf format and lint**
+
+```bash
+buf format -w proto && buf lint proto
+```
+
+**Step 3: Regenerate proto**
+
+```bash
+cd proto && buf generate
+```
+
+**Step 4: Commit**
+
+```bash
+but commit plan-check-run-refactor -m "proto: remove PlanCheckRunConfig message"
+```
+
+---
+
+## Task 3: Update Store Layer
+
+**Files:**
+- Modify: `backend/store/plan_check_run.go`
+
+**Step 1: Remove Config from PlanCheckRunMessage**
+
+Change struct (lines 29-40):
+```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
+ Result *storepb.PlanCheckRunResult
+}
+```
+
+To:
+```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
+ Result *storepb.PlanCheckRunResult
+}
+```
+
+**Step 2: Update CreatePlanCheckRun**
+
+Change (lines 51-74):
+```go
+// CreatePlanCheckRun creates or replaces the plan check run for a plan.
+func (s *Store) CreatePlanCheckRun(ctx context.Context, create *PlanCheckRunMessage) error {
+ config, err := protojson.Marshal(create.Config)
+ if err != nil {
+ return errors.Wrapf(err, "failed to marshal config")
+ }
+ result, err := protojson.Marshal(create.Result)
+ if err != nil {
+ return errors.Wrapf(err, "failed to marshal result")
+ }
+
+ query := `
+ INSERT INTO plan_check_run (plan_id, status, config, result)
+ VALUES ($1, $2, $3, $4)
+ ON CONFLICT (plan_id) DO UPDATE SET
+ status = EXCLUDED.status,
+ config = EXCLUDED.config,
+ result = EXCLUDED.result,
+ updated_at = now()
+ `
+ if _, err := s.GetDB().ExecContext(ctx, query, create.PlanUID, create.Status, config, result); err != nil {
+ return errors.Wrapf(err, "failed to upsert plan check run")
+ }
+ return nil
+}
+```
+
+To:
+```go
+// CreatePlanCheckRun creates or replaces the plan check run for a plan.
+func (s *Store) CreatePlanCheckRun(ctx context.Context, create *PlanCheckRunMessage) error {
+ result, err := protojson.Marshal(create.Result)
+ if err != nil {
+ return errors.Wrapf(err, "failed to marshal result")
+ }
+
+ query := `
+ INSERT INTO plan_check_run (plan_id, status, result)
+ VALUES ($1, $2, $3)
+ ON CONFLICT (plan_id) DO UPDATE SET
+ status = EXCLUDED.status,
+ result = EXCLUDED.result,
+ updated_at = now()
+ `
+ if _, err := s.GetDB().ExecContext(ctx, query, create.PlanUID, create.Status, result); err != nil {
+ return errors.Wrapf(err, "failed to upsert plan check run")
+ }
+ return nil
+}
+```
+
+**Step 3: Update ListPlanCheckRuns**
+
+Change query and scan (lines 77-148):
+```go
+// ListPlanCheckRuns returns a list of plan check runs based on find.
+func (s *Store) ListPlanCheckRuns(ctx context.Context, find *FindPlanCheckRunMessage) ([]*PlanCheckRunMessage, error) {
+ q := qb.Q().Space(`
+SELECT
+ plan_check_run.id,
+ plan_check_run.created_at,
+ plan_check_run.updated_at,
+ plan_check_run.plan_id,
+ plan_check_run.status,
+ plan_check_run.result
+FROM plan_check_run
+WHERE TRUE`)
+ if v := find.PlanUID; v != nil {
+ q.Space("AND plan_check_run.plan_id = ?", *v)
+ }
+ if v := find.UIDs; v != nil {
+ q.Space("AND plan_check_run.id = ANY(?)", *v)
+ }
+ if v := find.Status; v != nil {
+ q.Space("AND plan_check_run.status = ANY(?)", *v)
+ }
+ if v := find.ResultStatus; v != nil {
+ statusStrings := make([]string, len(*v))
+ for i, status := range *v {
+ statusStrings[i] = status.String()
+ }
+ q.Space("AND EXISTS (SELECT 1 FROM jsonb_array_elements(plan_check_run.result->'results') AS elem WHERE elem->>'status' = ANY(?))", statusStrings)
+ }
+ q.Space("ORDER BY plan_check_run.id ASC")
+ query, args, err := q.ToSQL()
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to build sql")
+ }
+ rows, err := s.GetDB().QueryContext(ctx, query, args...)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ var planCheckRuns []*PlanCheckRunMessage
+ for rows.Next() {
+ planCheckRun := PlanCheckRunMessage{
+ Result: &storepb.PlanCheckRunResult{},
+ }
+ var result string
+ if err := rows.Scan(
+ &planCheckRun.UID,
+ &planCheckRun.CreatedAt,
+ &planCheckRun.UpdatedAt,
+ &planCheckRun.PlanUID,
+ &planCheckRun.Status,
+ &result,
+ ); err != nil {
+ return nil, err
+ }
+ if err := common.ProtojsonUnmarshaler.Unmarshal([]byte(result), planCheckRun.Result); err != nil {
+ return nil, err
+ }
+ planCheckRuns = append(planCheckRuns, &planCheckRun)
+ }
+
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+
+ return planCheckRuns, nil
+}
+```
+
+**Step 4: Run lint**
+
+```bash
+golangci-lint run --allow-parallel-runners ./backend/store/...
+```
+
+**Step 5: Commit**
+
+```bash
+but commit plan-check-run-refactor -m "store: remove config from plan_check_run"
+```
+
+---
+
+## Task 4: Add Check Target Derivation Types
+
+**Files:**
+- Create: `backend/runner/plancheck/check_target.go`
+
+**Step 1: Create new file with CheckTarget struct**
+
+```go
+package plancheck
+
+import storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+
+// CheckTarget represents a derived check target from a plan.
+// This is computed at runtime from the plan's specs, not stored.
+type CheckTarget struct {
+ // Target is the database resource name: instances/{instance}/databases/{database}
+ Target string
+ // SheetSHA256 is the content hash of the SQL sheet
+ SheetSHA256 string
+ // EnablePriorBackup indicates if backup before migration is enabled
+ EnablePriorBackup bool
+ // EnableGhost indicates if gh-ost online migration is enabled
+ EnableGhost bool
+ // GhostFlags are configuration flags for gh-ost
+ GhostFlags map[string]string
+ // Types are the plan check types to run for this target
+ Types []storepb.PlanCheckType
+}
+```
+
+**Step 2: Commit**
+
+```bash
+but commit plan-check-run-refactor -m "plancheck: add CheckTarget type for runtime derivation"
+```
+
+---
+
+## Task 5: Extract Derivation Logic to Plancheck Package
+
+**Files:**
+- Create: `backend/runner/plancheck/derive.go`
+- Modify: `backend/api/v1/plan_service.go`
+
+**Step 1: Create derive.go with derivation function**
+
+```go
+package plancheck
+
+import (
+ "github.com/pkg/errors"
+
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
+ "github.com/bytebase/bytebase/backend/store"
+)
+
+// DeriveCheckTargets derives check targets from a plan and optional database group.
+// This replaces the stored config by computing targets at runtime.
+func DeriveCheckTargets(project *store.ProjectMessage, plan *store.PlanMessage, databaseGroup *v1pb.DatabaseGroup) ([]*CheckTarget, error) {
+ var targets []*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]
+ }
+ }
+
+ enableGhost := config.ChangeDatabaseConfig.EnableGhost
+
+ for _, target := range databases {
+ types := []storepb.PlanCheckType{
+ storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_ADVISE,
+ storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_SUMMARY_REPORT,
+ }
+ if enableGhost {
+ types = append(types, storepb.PlanCheckType_PLAN_CHECK_TYPE_GHOST_SYNC)
+ }
+
+ targets = append(targets, &CheckTarget{
+ Target: target,
+ SheetSHA256: config.ChangeDatabaseConfig.SheetSha256,
+ EnablePriorBackup: config.ChangeDatabaseConfig.EnablePriorBackup,
+ EnableGhost: config.ChangeDatabaseConfig.EnableGhost,
+ GhostFlags: config.ChangeDatabaseConfig.GhostFlags,
+ Types: types,
+ })
+ }
+ default:
+ return nil, errors.Errorf("unknown spec config type %T", config)
+ }
+ }
+
+ return targets, nil
+}
+```
+
+**Step 2: Update plan_service.go - simplify getPlanCheckRunFromPlan**
+
+Change function (lines 729-796):
+```go
+func getPlanCheckRunFromPlan(project *store.ProjectMessage, plan *store.PlanMessage, databaseGroup *v1pb.DatabaseGroup) (*store.PlanCheckRunMessage, error) {
+ targets, err := plancheck.DeriveCheckTargets(project, plan, databaseGroup)
+ if err != nil {
+ return nil, err
+ }
+
+ if len(targets) == 0 {
+ return nil, nil
+ }
+
+ return &store.PlanCheckRunMessage{
+ PlanUID: plan.UID,
+ Status: store.PlanCheckRunStatusRunning,
+ }, nil
+}
+```
+
+**Step 3: Add import for plancheck package in plan_service.go**
+
+Add to imports:
+```go
+"github.com/bytebase/bytebase/backend/runner/plancheck"
+```
+
+**Step 4: Run lint**
+
+```bash
+golangci-lint run --allow-parallel-runners ./backend/api/v1/... ./backend/runner/plancheck/...
+```
+
+**Step 5: Commit**
+
+```bash
+but commit plan-check-run-refactor -m "plancheck: extract DeriveCheckTargets function"
+```
+
+---
+
+## Task 6: Update Executors to Use CheckTarget
+
+**Files:**
+- Modify: `backend/runner/plancheck/executor.go`
+- Modify: `backend/runner/plancheck/executor_combined.go`
+- Modify: `backend/runner/plancheck/statement_advise_executor.go`
+- Modify: `backend/runner/plancheck/statement_report_executor.go`
+- Modify: `backend/runner/plancheck/ghost_sync_executor.go`
+
+**Step 1: Update Executor interface**
+
+Change `backend/runner/plancheck/executor.go`:
+```go
+package plancheck
+
+import (
+ "context"
+
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+)
+
+// Executor is the plan check executor.
+type Executor interface {
+ // RunForTarget will be called periodically by the plan check scheduler for each target
+ RunForTarget(ctx context.Context, target *CheckTarget) (results []*storepb.PlanCheckRunResult_Result, err error)
+}
+```
+
+**Step 2: Update CombinedExecutor**
+
+Change `backend/runner/plancheck/executor_combined.go`:
+```go
+package plancheck
+
+import (
+ "context"
+
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/component/dbfactory"
+ "github.com/bytebase/bytebase/backend/component/sheet"
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ "github.com/bytebase/bytebase/backend/store"
+)
+
+// CombinedExecutor processes all plan check types.
+type CombinedExecutor struct {
+ store *store.Store
+ sheetManager *sheet.Manager
+ dbFactory *dbfactory.DBFactory
+}
+
+// NewCombinedExecutor creates a combined executor.
+func NewCombinedExecutor(
+ store *store.Store,
+ sheetManager *sheet.Manager,
+ dbFactory *dbfactory.DBFactory,
+) *CombinedExecutor {
+ return &CombinedExecutor{
+ store: store,
+ sheetManager: sheetManager,
+ dbFactory: dbFactory,
+ }
+}
+
+// RunForTarget runs all checks for the given target.
+func (e *CombinedExecutor) RunForTarget(ctx context.Context, target *CheckTarget) ([]*storepb.PlanCheckRunResult_Result, error) {
+ var allResults []*storepb.PlanCheckRunResult_Result
+
+ 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 *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 *CheckTarget) ([]*storepb.PlanCheckRunResult_Result, error) {
+ executor := &StatementAdviseExecutor{
+ store: e.store,
+ sheetManager: e.sheetManager,
+ dbFactory: e.dbFactory,
+ }
+ return executor.RunForTarget(ctx, target)
+}
+
+func (e *CombinedExecutor) runStatementReport(ctx context.Context, target *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 *CheckTarget) ([]*storepb.PlanCheckRunResult_Result, error) {
+ executor := &GhostSyncExecutor{
+ store: e.store,
+ dbFactory: e.dbFactory,
+ }
+ return executor.RunForTarget(ctx, target)
+}
+```
+
+**Step 3: Update StatementAdviseExecutor**
+
+Change function signature and field access in `backend/runner/plancheck/statement_advise_executor.go`:
+```go
+// RunForTarget runs the statement advise check for a single target.
+func (e *StatementAdviseExecutor) RunForTarget(ctx context.Context, target *CheckTarget) ([]*storepb.PlanCheckRunResult_Result, error) {
+ fullSheet, err := e.store.GetSheetFull(ctx, target.SheetSHA256)
+ // ... rest uses target.Target, target.EnablePriorBackup, target.EnableGhost
+```
+
+**Step 4: Update StatementReportExecutor**
+
+Change function signature in `backend/runner/plancheck/statement_report_executor.go`:
+```go
+// RunForTarget runs the statement report check for a single target.
+func (e *StatementReportExecutor) RunForTarget(ctx context.Context, target *CheckTarget) ([]*storepb.PlanCheckRunResult_Result, error) {
+ fullSheet, err := e.store.GetSheetFull(ctx, target.SheetSHA256)
+ // ... rest uses target.Target
+```
+
+**Step 5: Update GhostSyncExecutor**
+
+Change function signature in `backend/runner/plancheck/ghost_sync_executor.go`:
+```go
+// RunForTarget runs the gh-ost sync check for a single target.
+func (e *GhostSyncExecutor) RunForTarget(ctx context.Context, target *CheckTarget) (results []*storepb.PlanCheckRunResult_Result, err error) {
+ // ... uses target.Target, target.SheetSHA256, target.GhostFlags
+```
+
+**Step 6: Run lint**
+
+```bash
+golangci-lint run --allow-parallel-runners ./backend/runner/plancheck/...
+```
+
+**Step 7: Commit**
+
+```bash
+but commit plan-check-run-refactor -m "plancheck: update executors to use CheckTarget"
+```
+
+---
+
+## Task 7: Update Scheduler for Runtime Derivation
+
+**Files:**
+- Modify: `backend/runner/plancheck/scheduler.go`
+
+**Step 1: Update Scheduler struct to include store for plan fetching**
+
+The scheduler already has `store *store.Store`, so it can fetch plans.
+
+**Step 2: Update runPlanCheckRun to fetch plan and derive targets**
+
+Change the `runPlanCheckRun` function (lines 83-120):
+```go
+func (s *Scheduler) runPlanCheckRun(ctx context.Context, planCheckRun *store.PlanCheckRunMessage) {
+ // Skip the plan check run if it is already running.
+ if _, ok := s.bus.RunningPlanChecks.Load(planCheckRun.UID); ok {
+ return
+ }
+
+ s.bus.RunningPlanChecks.Store(planCheckRun.UID, true)
+ go func() {
+ defer func() {
+ s.bus.RunningPlanChecks.Delete(planCheckRun.UID)
+ s.bus.RunningPlanCheckRunsCancelFunc.Delete(planCheckRun.UID)
+ }()
+
+ ctxWithCancel, cancel := context.WithCancel(ctx)
+ defer cancel()
+ s.bus.RunningPlanCheckRunsCancelFunc.Store(planCheckRun.UID, cancel)
+
+ // Fetch plan to derive check targets at runtime
+ plan, err := s.store.GetPlan(ctxWithCancel, planCheckRun.PlanUID)
+ if err != nil {
+ s.markPlanCheckRunFailed(ctx, planCheckRun, err.Error())
+ return
+ }
+ if plan == nil {
+ s.markPlanCheckRunFailed(ctx, planCheckRun, "plan not found")
+ return
+ }
+
+ project, err := s.store.GetProject(ctxWithCancel, &store.FindProjectMessage{ResourceID: &plan.ProjectID})
+ if err != nil {
+ s.markPlanCheckRunFailed(ctx, planCheckRun, err.Error())
+ return
+ }
+ if project == nil {
+ s.markPlanCheckRunFailed(ctx, planCheckRun, "project not found")
+ return
+ }
+
+ // Get database group if needed (for spec expansion)
+ var databaseGroup *v1pb.DatabaseGroup
+ for _, spec := range plan.Config.Specs {
+ if cfg, ok := spec.Config.(*storepb.PlanConfig_Spec_ChangeDatabaseConfig); ok {
+ if len(cfg.ChangeDatabaseConfig.Targets) == 1 {
+ target := cfg.ChangeDatabaseConfig.Targets[0]
+ if dbg, err := s.store.GetDatabaseGroup(ctxWithCancel, &store.FindDatabaseGroupMessage{ResourceID: &target}); err == nil && dbg != nil {
+ databaseGroup = convertToDatabaseGroup(dbg)
+ break
+ }
+ }
+ }
+ }
+
+ // Derive check targets from plan
+ targets, err := DeriveCheckTargets(project, plan, databaseGroup)
+ if err != nil {
+ s.markPlanCheckRunFailed(ctx, planCheckRun, err.Error())
+ return
+ }
+
+ var results []*storepb.PlanCheckRunResult_Result
+ for _, target := range targets {
+ targetResults, targetErr := s.executor.RunForTarget(ctxWithCancel, target)
+ if targetErr != nil {
+ err = targetErr
+ break
+ }
+ results = append(results, targetResults...)
+ }
+ 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 3: Add helper function for database group conversion**
+
+Add at end of file:
+```go
+func convertToDatabaseGroup(dbg *store.DatabaseGroupMessage) *v1pb.DatabaseGroup {
+ if dbg == nil {
+ return nil
+ }
+ result := &v1pb.DatabaseGroup{
+ Name: dbg.ResourceID,
+ }
+ for _, db := range dbg.MatchedDatabases {
+ result.MatchedDatabases = append(result.MatchedDatabases, &v1pb.DatabaseGroup_Database{
+ Name: db,
+ })
+ }
+ return result
+}
+```
+
+**Step 4: Add imports**
+
+Add to imports:
+```go
+v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
+```
+
+**Step 5: Run lint**
+
+```bash
+golangci-lint run --allow-parallel-runners ./backend/runner/plancheck/...
+```
+
+**Step 6: Commit**
+
+```bash
+but commit plan-check-run-refactor -m "plancheck: scheduler derives targets at runtime"
+```
+
+---
+
+## Task 8: Build and Test
+
+**Step 1: Build backend**
+
+```bash
+go build -ldflags "-w -s" -p=16 -o ./bytebase-build/bytebase ./backend/bin/server/main.go
+```
+
+**Step 2: Run lint on all changed packages**
+
+```bash
+golangci-lint run --allow-parallel-runners ./backend/store/... ./backend/api/v1/... ./backend/runner/plancheck/...
+```
+
+**Step 3: Commit any fixes**
+
+```bash
+but commit plan-check-run-refactor -m "fix: lint issues"
+```
+
+---
+
+## Task 9: Final Cleanup
+
+**Step 1: Remove unused imports in plan_service.go**
+
+If `storepb.PlanCheckRunConfig` is no longer referenced, the import may need cleanup.
+
+**Step 2: Run full lint**
+
+```bash
+golangci-lint run --allow-parallel-runners
+```
+
+**Step 3: Final commit**
+
+```bash
+but commit plan-check-run-refactor -m "refactor: plan check run derives config at runtime
+
+- Remove config and payload columns from plan_check_run table
+- Remove PlanCheckRunConfig proto message
+- Add CheckTarget struct for runtime derivation
+- Scheduler fetches plan and derives targets before execution
+- Executors receive CheckTarget instead of stored proto"
+```
+
+---
+
+## Summary
+
+| Task | Description |
+|------|-------------|
+| 1 | Database migration to drop columns |
+| 2 | Proto changes to remove PlanCheckRunConfig |
+| 3 | Store layer updates |
+| 4 | New CheckTarget type |
+| 5 | Extract DeriveCheckTargets function |
+| 6 | Update all executors |
+| 7 | Update scheduler for runtime derivation |
+| 8 | Build and test |
+| 9 | Final cleanup |
diff --git a/docs/plans/2026-01-05-plan-check-run-runtime-derivation.md b/docs/plans/2026-01-05-plan-check-run-runtime-derivation.md
new file mode 100644
index 0000000000..2fc10ab996
--- /dev/null
+++ b/docs/plans/2026-01-05-plan-check-run-runtime-derivation.md
@@ -0,0 +1,106 @@
+# Plan Check Run Runtime Derivation
+
+## Overview
+
+Refactor plan check run to derive configuration from the associated plan at runtime, rather than storing a self-contained copy of the configuration.
+
+## Motivation
+
+1. **Simplify code** — Remove the config copying logic in `getPlanCheckRunFromPlan()`
+2. **Reduce storage** — Avoid storing redundant data that duplicates the plan
+3. **Prevent staleness** — Plan check run config can't get out of sync with plan
+
+## Current State
+
+Plan check run stores duplicated fields from the plan:
+
+| Field | In Plan | In Plan Check Run |
+|-------|---------|-------------------|
+| `sheet_sha256` | `ChangeDatabaseConfig` | `CheckTarget` |
+| `enable_prior_backup` | `ChangeDatabaseConfig` | `CheckTarget` |
+| `enable_ghost` | `ChangeDatabaseConfig` | `CheckTarget` |
+| `ghost_flags` | `ChangeDatabaseConfig` | `CheckTarget` |
+| `targets` | Spec level | Expanded per `CheckTarget` |
+
+The `config` column stores `PlanCheckRunConfig` which contains these duplicated fields. The `payload` column is unused.
+
+## Design
+
+### Key Insight
+
+There is only one plan check run per plan (unique constraint on `plan_id`). When plan checks are rerun, the old run is replaced. This means:
+- No need to preserve historical config
+- Results are self-documenting (contain target info)
+- Config can be derived from current plan state
+
+### Data Model Changes
+
+**Remove from `plan_check_run` table:**
+- `config` column (JSONB storing `PlanCheckRunConfig`)
+- `payload` column (unused, reserved)
+
+**Keep in `plan_check_run` table:**
+- `id` (primary key)
+- `created_at`, `updated_at`
+- `plan_id` (foreign key to plan)
+- `status` (RUNNING/DONE/FAILED/CANCELED)
+- `result` (JSONB storing `PlanCheckRunResult`)
+
+**Proto changes:**
+- Remove `PlanCheckRunConfig` message from `proto/store/store/plan_check_run.proto`
+- Remove `CheckTarget` message (only used in config)
+- Update API proto if config is exposed to clients
+
+**Store layer:**
+- Remove `Config` field from `PlanCheckRunMessage`
+- Update CRUD operations to exclude config/payload columns
+
+### Runtime Derivation
+
+**`getPlanCheckRunFromPlan()` becomes a pure derivation function:**
+
+Instead of creating a persisted config, it returns an in-memory struct:
+
+```go
+type DerivedCheckTarget struct {
+ Target string // database resource name
+ SheetSHA256 string // from plan spec
+ EnablePriorBackup bool
+ EnableGhost bool
+ GhostFlags map[string]string
+ Types []storepb.PlanCheckType
+}
+```
+
+**Executor flow:**
+1. Fetch plan check run (has `plan_id`, `status`)
+2. Fetch plan by `plan_id`
+3. Call derivation function to get targets and config
+4. Run checks against each target using derived config
+5. Store results in `result` field
+
+### Migration
+
+```sql
+ALTER TABLE plan_check_run DROP COLUMN config;
+ALTER TABLE plan_check_run DROP COLUMN payload;
+```
+
+## Files to Change
+
+| Layer | File(s) | Change |
+|-------|---------|--------|
+| Proto (store) | `proto/store/store/plan_check_run.proto` | Remove `PlanCheckRunConfig`, `CheckTarget` |
+| Proto (API) | `proto/v1/plan_service.proto` | Remove config from `PlanCheckRun` if exposed |
+| Migration | `backend/migrator/migration/LATEST.sql` + new | Drop columns |
+| Store | `backend/store/plan_check_run.go` | Remove `Config` field, update CRUD |
+| API | `backend/api/v1/plan_service.go` | Simplify creation, extract derivation |
+| Runner | `backend/runner/plancheck/runner.go` | Fetch plan, derive targets at runtime |
+| Executors | `backend/runner/plancheck/*.go` | Receive derived config |
+
+## What Stays the Same
+
+- `PlanCheckRunResult` proto (stores actual results per target)
+- Plan check run status lifecycle (RUNNING -> DONE/FAILED/CANCELED)
+- The derivation logic itself (database group expansion, CI sampling)
+- One plan check run per plan constraint
diff --git a/proto/gen/grpc-doc/store/README.md b/proto/gen/grpc-doc/store/README.md
index 9cbe87a32f..be4ff2b8e5 100644
--- a/proto/gen/grpc-doc/store/README.md
+++ b/proto/gen/grpc-doc/store/README.md
@@ -169,9 +169,6 @@
- [ChangedResourceSchema](#bytebase-store-ChangedResourceSchema)
- [ChangedResourceTable](#bytebase-store-ChangedResourceTable)
- [ChangedResources](#bytebase-store-ChangedResources)
- - [PlanCheckRunConfig](#bytebase-store-PlanCheckRunConfig)
- - [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)
@@ -2961,57 +2958,6 @@ Plan spec update event (tracks sheet changes to plan specs)
-<a name="bytebase-store-PlanCheckRunConfig"></a>
-
-### PlanCheckRunConfig
-
-
-
-| Field | Type | Label | Description |
-| ----- | ---- | ----- | ----------- |
-| 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) | | |
-| ghost_flags | [PlanCheckRunConfig.CheckTarget.GhostFlagsEntry](#bytebase-store-PlanCheckRunConfig-CheckTarget-GhostFlagsEntry) | repeated | |
-| types | [PlanCheckType](#bytebase-store-PlanCheckType) | repeated | |
-
-
-
-
-
-
-<a name="bytebase-store-PlanCheckRunConfig-CheckTarget-GhostFlagsEntry"></a>
-
-### PlanCheckRunConfig.CheckTarget.GhostFlagsEntry
-
-
-
-| Field | Type | Label | Description |
-| ----- | ---- | ----- | ----------- |
-| key | [string](#string) | | |
-| value | [string](#string) | | |
-
-
-
-
-
-
<a name="bytebase-store-PlanCheckRunResult"></a>
### PlanCheckRunResult
diff --git a/proto/gen/grpc-doc/store/index.html b/proto/gen/grpc-doc/store/index.html
index 87495ac29d..6e10b38c7d 100644
--- a/proto/gen/grpc-doc/store/index.html
+++ b/proto/gen/grpc-doc/store/index.html
@@ -840,18 +840,6 @@
<a href="#bytebase.store.ChangedResources"><span class="badge">M</span>ChangedResources</a>
</li>
- <li>
- <a href="#bytebase.store.PlanCheckRunConfig"><span class="badge">M</span>PlanCheckRunConfig</a>
- </li>
-
- <li>
- <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>
<a href="#bytebase.store.PlanCheckRunResult"><span class="badge">M</span>PlanCheckRunResult</a>
</li>
@@ -8553,120 +8541,6 @@ Leave it empty if there is no need to encrypt the zip file. </p></td>
- <h3 id="bytebase.store.PlanCheckRunConfig">PlanCheckRunConfig</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>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>target</td>
- <td><a href="#string">string</a></td>
- <td></td>
- <td><p>Format: instances/{instance}/databases/{database} </p></td>
- </tr>
-
- <tr>
- <td>sheet_sha256</td>
- <td><a href="#string">string</a></td>
- <td></td>
- <td><p> </p></td>
- </tr>
-
- <tr>
- <td>enable_prior_backup</td>
- <td><a href="#bool">bool</a></td>
- <td></td>
- <td><p> </p></td>
- </tr>
-
- <tr>
- <td>enable_ghost</td>
- <td><a href="#bool">bool</a></td>
- <td></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>
- </table>
-
-
-
-
-
- <h3 id="bytebase.store.PlanCheckRunConfig.CheckTarget.GhostFlagsEntry">PlanCheckRunConfig.CheckTarget.GhostFlagsEntry</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>key</td>
- <td><a href="#string">string</a></td>
- <td></td>
- <td><p> </p></td>
- </tr>
-
- <tr>
- <td>value</td>
- <td><a href="#string">string</a></td>
- <td></td>
- <td><p> </p></td>
- </tr>
-
- </tbody>
- </table>
-
-
-
-
-
<h3 id="bytebase.store.PlanCheckRunResult">PlanCheckRunResult</h3>
<p></p>
diff --git a/proto/store/store/plan_check_run.proto b/proto/store/store/plan_check_run.proto
index 294bce4c81..d4b3423fd6 100644
--- a/proto/store/store/plan_check_run.proto
+++ b/proto/store/store/plan_check_run.proto
@@ -14,20 +14,6 @@ enum PlanCheckType {
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;
- map<string, string> ghost_flags = 6;
- repeated PlanCheckType types = 7;
- }
-}
-
message PlanCheckRunResult {
repeated Result results = 1;
string error = 2;