Skip to content

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

4.6 KB
Raw Blame
package plancheck

import (
	"context"

	"github.com/pkg/errors"

	"github.com/bytebase/bytebase/backend/component/ghost"
	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, applying the project's CI sampling limit: plan checks are CI
// validation, and sampling bounds their cost. The AI review uses the same
// sample to bound its model calls.
// This replaces the stored config by computing targets at runtime.
func DeriveCheckTargets(ctx context.Context, s *store.Store, project *store.ProjectMessage, plan *store.PlanMessage, databaseGroup *v1pb.DatabaseGroup) ([]*CheckTarget, error) {
	return deriveTargets(ctx, s, project, plan, databaseGroup, true)
}

// DeriveReviewTargets derives the same targets without CI sampling: a rule
// review run's DONE means every (spec, target) unit was evaluated, so the
// rule review must see the full target set.
func DeriveReviewTargets(ctx context.Context, s *store.Store, project *store.ProjectMessage, plan *store.PlanMessage, databaseGroup *v1pb.DatabaseGroup) ([]*CheckTarget, error) {
	return deriveTargets(ctx, s, project, plan, databaseGroup, false)
}

// HasReviewTargets reports whether the rule review has SQL to read in the
// plan: whether DeriveReviewTargets finds any target.
func HasReviewTargets(ctx context.Context, s *store.Store, project *store.ProjectMessage, plan *store.PlanMessage) (bool, error) {
	databaseGroup, err := GetDatabaseGroupForPlan(ctx, s, plan, nil)
	if err != nil {
		return false, errors.Wrap(err, "failed to get database group for plan")
	}
	targets, err := DeriveReviewTargets(ctx, s, project, plan, databaseGroup)
	if err != nil {
		return false, errors.Wrap(err, "failed to derive review targets")
	}
	return len(targets) > 0, nil
}

func deriveTargets(ctx context.Context, s *store.Store, project *store.ProjectMessage, plan *store.PlanMessage, databaseGroup *v1pb.DatabaseGroup, applySampling bool) ([]*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_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 applySampling {
				if samplingSize := project.Setting.GetCiSamplingSize(); samplingSize > 0 && len(databases) > int(samplingSize) {
					databases = databases[:samplingSize]
				}
			}

			// Parse ghost config from sheet content
			var enableGhost bool
			var ghostFlags map[string]string

			sheetContent, err := getSheetContent(ctx, s, config.ChangeDatabaseConfig.SheetSha256)
			if err != nil {
				return nil, errors.Wrapf(err, "failed to get sheet content")
			}
			if sheetContent != "" {
				enableGhost = ghost.IsGhostEnabled(sheetContent)
				if enableGhost {
					ghostFlags, err = ghost.ParseGhostDirective(sheetContent)
					if err != nil {
						return nil, errors.Wrapf(err, "failed to parse ghost directive")
					}
				}
			}

			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{
					SpecID:            spec.Id,
					Target:            target,
					SheetSha256:       config.ChangeDatabaseConfig.SheetSha256,
					EnablePriorBackup: config.ChangeDatabaseConfig.EnablePriorBackup,
					EnableGhost:       enableGhost,
					GhostFlags:        ghostFlags,
					Types:             types,
				})
			}
		default:
			return nil, errors.Errorf("unknown spec config type %T", config)
		}
	}

	return targets, nil
}

func getSheetContent(ctx context.Context, s *store.Store, sheetSha256 string) (string, error) {
	if sheetSha256 == "" {
		return "", nil
	}
	sheet, err := s.GetSheetFull(ctx, sheetSha256)
	if err != nil {
		return "", err
	}
	if sheet == nil {
		return "", nil
	}
	return sheet.Statement, nil
}