Skip to content

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

feat: configure a Sample SQL Review Policy (#4708)

Tianzhou (天舟)a51f3c7e1611
diff --git a/backend/component/config/profile.go b/backend/component/config/profile.go
index 74e85aea5a..113a9c17a0 100644
--- a/backend/component/config/profile.go
+++ b/backend/component/config/profile.go
@@ -65,6 +65,9 @@ type Profile struct {
MetricConnectionKey string
// DisableMetric will disable the metric collector.
DisableMetric bool
+
+ // Test only flag to skip generating onboarding data.
+ TestOnlySkipOnboardingData bool
}
// UseEmbedDB returns whether to use embedDB.
diff --git a/backend/legacyapi/project.go b/backend/legacyapi/project.go
index 87eb90c14c..36e43965c4 100644
--- a/backend/legacyapi/project.go
+++ b/backend/legacyapi/project.go
@@ -22,6 +22,8 @@ const (
// This can be mutated by the user. But for now this is only used by onboarding flow to create
// a prod instance after first signup, so it's safe to refer it.
DefaultProdEnvironmentID = "prod"
+ // DefaultProdEnvironmentUID is the initial resource UID for the prod environment.
+ DefaultProdEnvironmentUID = 102
)
// ProjectWorkflowType is the workflow type for projects.
diff --git a/backend/server/server.go b/backend/server/server.go
index 1897e07810..4a8193aaab 100644
--- a/backend/server/server.go
+++ b/backend/server/server.go
@@ -51,6 +51,8 @@ import (
api "github.com/bytebase/bytebase/backend/legacyapi"
"github.com/bytebase/bytebase/backend/metric"
metricCollector "github.com/bytebase/bytebase/backend/metric/collector"
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ advisorDb "github.com/bytebase/bytebase/backend/plugin/advisor/db"
"github.com/bytebase/bytebase/backend/plugin/app/feishu"
"github.com/bytebase/bytebase/backend/plugin/db"
bbs3 "github.com/bytebase/bytebase/backend/plugin/storage/s3"
@@ -458,6 +460,9 @@ func NewServer(ctx context.Context, profile config.Profile) (*Server, error) {
)
v1pb.RegisterAuthServiceServer(s.grpcServer, v1.NewAuthService(s.store, s.secret, s.MetricReporter, &profile,
func(ctx context.Context, user *store.UserMessage, firstEndUser bool) error {
+ if s.profile.TestOnlySkipOnboardingData {
+ return nil
+ }
// Only generate onboarding data after the first enduser signup.
if firstEndUser {
if err := s.generateOnboardingData(ctx, user.ID); err != nil {
@@ -752,6 +757,48 @@ func (s *Server) GetWorkspaceID() string {
return s.workspaceID
}
+// getSampleSQLReviewPolicy returns a sample SQL review policy for preparing onboardign data.
+func getSampleSQLReviewPolicy() *advisor.SQLReviewPolicy {
+ policy := &advisor.SQLReviewPolicy{
+ Name: "SQL Review Sample Policy",
+ }
+
+ ruleList := []*advisor.SQLReviewRule{}
+
+ // Add DropEmptyDatabase rule for MySQL and TiDB.
+ for _, e := range []advisorDb.Type{advisorDb.MySQL, advisorDb.TiDB} {
+ ruleList = append(ruleList, &advisor.SQLReviewRule{
+ Type: advisor.SchemaRuleDropEmptyDatabase,
+ Level: advisor.SchemaRuleLevelError,
+ Engine: e,
+ Payload: "{}",
+ })
+ }
+
+ // Add ColumnNotNull rule for MySQL, TiDB and Postgres.
+ for _, e := range []advisorDb.Type{advisorDb.MySQL, advisorDb.TiDB, advisorDb.Postgres} {
+ ruleList = append(ruleList, &advisor.SQLReviewRule{
+ Type: advisor.SchemaRuleColumnNotNull,
+ Level: advisor.SchemaRuleLevelWarning,
+ Engine: e,
+ Payload: "{}",
+ })
+ }
+
+ // Add TableDropNamingConvention rule for MySQL, TiDB and Postgres.
+ for _, e := range []advisorDb.Type{advisorDb.MySQL, advisorDb.TiDB, advisorDb.Postgres} {
+ ruleList = append(ruleList, &advisor.SQLReviewRule{
+ Type: advisor.SchemaRuleTableDropNamingConvention,
+ Level: advisor.SchemaRuleLevelError,
+ Engine: e,
+ Payload: "{\"format\":\"_del$\"}",
+ })
+ }
+
+ policy.RuleList = ruleList
+ return policy
+}
+
// generateOnboardingData generates onboarding data after the first signup.
func (s *Server) generateOnboardingData(ctx context.Context, userID int) error {
project, err := s.store.CreateProjectV2(ctx, &store.ProjectMessage{
@@ -828,6 +875,26 @@ func (s *Server) generateOnboardingData(ctx context.Context, userID int) error {
return errors.Wrapf(err, "failed to sync sample database schema")
}
+ // Add a sample SQL Review policy to the prod environment. This pairs with the following schema
+ // change issue to demonstrate the SQL Review feature.
+ policyPayload, err := json.Marshal(*getSampleSQLReviewPolicy())
+ if err != nil {
+ return errors.Wrapf(err, "failed to marshal onboarding SQL Review policy")
+ }
+
+ _, err = s.store.CreatePolicyV2(ctx, &store.PolicyMessage{
+ ResourceUID: api.DefaultProdEnvironmentUID,
+ ResourceType: api.PolicyResourceTypeEnvironment,
+ Payload: string(policyPayload),
+ Type: api.PolicyTypeSQLReview,
+ InheritFromParent: true,
+ // Enforce cannot be false while creating a policy.
+ Enforce: true,
+ }, userID)
+ if err != nil {
+ return errors.Wrapf(err, "failed to create onboarding SQL Review policy")
+ }
+
// Create a schema update issue.
createContext, err := json.Marshal(
&api.MigrationContext{
@@ -835,7 +902,9 @@ func (s *Server) generateOnboardingData(ctx context.Context, userID int) error {
{
MigrationType: db.Migrate,
DatabaseID: database.UID,
- Statement: "ALTER TABLE employee ADD COLUMN IF NOT EXISTS email TEXT NOT NULL DEFAULT '';",
+ // This will violate the NOT NULL SQL Review policy configured above and emit a
+ // warning. Thus to demonstrate the SQL Review capability.
+ Statement: "ALTER TABLE employee ADD COLUMN IF NOT EXISTS email TEXT DEFAULT '';",
},
},
})
diff --git a/backend/tests/schema_update_test.go b/backend/tests/schema_update_test.go
index 20e29b0569..c766b90fdd 100644
--- a/backend/tests/schema_update_test.go
+++ b/backend/tests/schema_update_test.go
@@ -1467,6 +1467,9 @@ func TestVCS_SQL_Review(t *testing.T) {
err := ctl.StartServerWithExternalPg(ctx, &config{
dataDir: t.TempDir(),
vcsProviderCreator: test.vcsProviderCreator,
+ // We check against empty SQL Review policy, while our onboarding data generation
+ // will create a SQL Review policy. Thus we need to skip onboarding data generation.
+ skipOnboardingData: true,
})
a.NoError(err)
defer func() {
diff --git a/backend/tests/tests.go b/backend/tests/tests.go
index d873295031..c8888cf278 100644
--- a/backend/tests/tests.go
+++ b/backend/tests/tests.go
@@ -171,6 +171,7 @@ type config struct {
vcsProviderCreator fake.VCSProviderCreator
feishuProverdierCreator fake.FeishuProviderCreator
readOnly bool
+ skipOnboardingData bool
}
var (
@@ -235,7 +236,7 @@ func (ctl *controller) StartServerWithExternalPg(ctx context.Context, config *co
pgURL := fmt.Sprintf("postgresql://%s@:%d/%s?host=%s", externalPgUser, externalPgPort, databaseName, common.GetPostgresSocketDir())
serverPort := getTestPort()
- profile := getTestProfileWithExternalPg(config.dataDir, resourceDir, serverPort, externalPgUser, pgURL, ctl.feishuProvider.APIURL(ctl.feishuURL))
+ profile := getTestProfileWithExternalPg(config.dataDir, resourceDir, serverPort, externalPgUser, pgURL, ctl.feishuProvider.APIURL(ctl.feishuURL), config.skipOnboardingData)
server, err := server.NewServer(ctx, profile)
if err != nil {
return err
@@ -293,20 +294,21 @@ func getTestProfile(dataDir, resourceDir string, port int, readOnly bool, feishu
// GetTestProfileWithExternalPg will return a profile for testing with external Postgres.
// We require port as an argument of GetTestProfile so that test can run in parallel in different ports,
// pgURL for connect to Postgres.
-func getTestProfileWithExternalPg(dataDir, resourceDir string, port int, pgUser string, pgURL string, feishuAPIURL string) componentConfig.Profile {
+func getTestProfileWithExternalPg(dataDir, resourceDir string, port int, pgUser string, pgURL string, feishuAPIURL string, skipOnboardingData bool) componentConfig.Profile {
return componentConfig.Profile{
- Mode: testReleaseMode,
- ExternalURL: fmt.Sprintf("http://localhost:%d", port),
- GrpcPort: port + 1,
- SampleDatabasePort: port + 2,
- PgUser: pgUser,
- DataDir: dataDir,
- ResourceDir: resourceDir,
- AppRunnerInterval: 1 * time.Second,
- BackupRunnerInterval: 10 * time.Second,
- BackupStorageBackend: api.BackupStorageBackendLocal,
- FeishuAPIURL: feishuAPIURL,
- PgURL: pgURL,
+ Mode: testReleaseMode,
+ ExternalURL: fmt.Sprintf("http://localhost:%d", port),
+ GrpcPort: port + 1,
+ SampleDatabasePort: port + 2,
+ PgUser: pgUser,
+ DataDir: dataDir,
+ ResourceDir: resourceDir,
+ AppRunnerInterval: 1 * time.Second,
+ BackupRunnerInterval: 10 * time.Second,
+ BackupStorageBackend: api.BackupStorageBackendLocal,
+ FeishuAPIURL: feishuAPIURL,
+ PgURL: pgURL,
+ TestOnlySkipOnboardingData: skipOnboardingData,
}
}
diff --git a/frontend/src/components/Issue/TaskCheckRunPanel.vue b/frontend/src/components/Issue/TaskCheckRunPanel.vue
index 647519502a..f634aff72a 100644
--- a/frontend/src/components/Issue/TaskCheckRunPanel.vue
+++ b/frontend/src/components/Issue/TaskCheckRunPanel.vue
@@ -170,7 +170,7 @@ const errorCodeLink = (
default: {
const url = `https://www.bytebase.com/docs/reference/error-code/${
checkResult.namespace === "bb.advisor" ? "advisor" : "core"
- }?source=console`;
+ }?source=console#${checkResult.code}`;
return {
title: t("common.view-doc"),
target: "__blank",