Skip to content

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

feat(review): switch the standard review rules on and off

rebelicec5e3c534a030
diff --git a/backend/api/mcp/gen/openapi.yaml b/backend/api/mcp/gen/openapi.yaml
index 21772eecbb..ea90fe66bd 100644
--- a/backend/api/mcp/gen/openapi.yaml
+++ b/backend/api/mcp/gen/openapi.yaml
@@ -19170,7 +19170,12 @@ components:
description: |-
Standard review rule policy: the rules switched on. The nearest policy
wins: a project's own policy applies as is; a project without one uses
- the workspace policy; with neither, every rule is on.
+ the workspace policy; with neither, every rule is on. Getting the policy
+ of a project without its own is NOT_FOUND; getting the workspace's when it
+ has none returns every rule on.
+
+ SYNTAX gates the rest: the other rules judge only SQL that parses, so a
+ list without SYNTAX switches every rule off.
A saved list is explicit, so a rule added to the standard set in a later
release is appended to every saved policy by a data migration in that
diff --git a/backend/api/v1/issue_service_review_run.go b/backend/api/v1/issue_service_review_run.go
index 29497e5025..f12aafa8ab 100644
--- a/backend/api/v1/issue_service_review_run.go
+++ b/backend/api/v1/issue_service_review_run.go
@@ -82,6 +82,15 @@ func (s *IssueService) RunReview(ctx context.Context, req *connect.Request[v1pb.
if len(targets) == 0 {
return nil, connect.NewError(connect.CodeFailedPrecondition, errors.Errorf("the plan has no reviewable SQL"))
}
+ if reviewType == store.ReviewRunTypeRule {
+ policy, err := s.store.GetEffectiveReviewRulePolicy(ctx, project.Workspace, projectID)
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to get review rule policy"))
+ }
+ if len(policy.GetRules()) == 0 {
+ return nil, connect.NewError(connect.CodeFailedPrecondition, errors.Errorf("rule review requires the SYNTAX rule to be on"))
+ }
+ }
if reviewType == store.ReviewRunTypeAI {
aiSetting, err := s.store.GetAISetting(ctx, common.GetWorkspaceIDFromContext(ctx))
if err != nil {
diff --git a/backend/api/v1/issue_service_review_run_test.go b/backend/api/v1/issue_service_review_run_test.go
new file mode 100644
index 0000000000..4e38c80d50
--- /dev/null
+++ b/backend/api/v1/issue_service_review_run_test.go
@@ -0,0 +1,57 @@
+package v1
+
+import (
+ "fmt"
+ "testing"
+
+ "connectrpc.com/connect"
+ "github.com/stretchr/testify/require"
+ "google.golang.org/protobuf/encoding/protojson"
+
+ "github.com/bytebase/bytebase/backend/common"
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
+ "github.com/bytebase/bytebase/backend/store"
+)
+
+func TestRunReviewRefusesRuleReviewWithoutSyntax(t *testing.T) {
+ t.Parallel()
+ ctx := issueServiceTestContext()
+ stores := setupIssueServiceTestStore(ctx, t)
+ _, issue := createIssueServiceApprovalIssue(ctx, t, stores)
+ service := newIssueServiceForTest(t, stores)
+
+ setProjectRules := func(rules ...storepb.ReviewRuleType) {
+ t.Helper()
+ payload, err := protojson.Marshal(&storepb.ReviewRulePolicy{Rules: rules})
+ require.NoError(t, err)
+ _, err = stores.CreatePolicy(ctx, &store.PolicyMessage{
+ Workspace: "default",
+ ResourceType: storepb.Policy_PROJECT,
+ Resource: common.FormatProject("project-a"),
+ Type: storepb.Policy_REVIEW_RULE,
+ Payload: string(payload),
+ Enforce: true,
+ })
+ require.NoError(t, err)
+ }
+ runRuleReview := func() (*v1pb.ReviewRun, error) {
+ resp, err := service.RunReview(ctx, connect.NewRequest(&v1pb.RunReviewRequest{
+ Name: fmt.Sprintf("projects/project-a/issues/%d/reviewRuns/rule", issue.UID),
+ }))
+ if err != nil {
+ return nil, err
+ }
+ return resp.Msg, nil
+ }
+
+ setProjectRules(storepb.ReviewRuleType_REQUIRE_WHERE)
+ _, err := runRuleReview()
+ require.Equal(t, connect.CodeFailedPrecondition, connect.CodeOf(err))
+
+ setProjectRules(storepb.ReviewRuleType_SYNTAX, storepb.ReviewRuleType_REQUIRE_WHERE)
+ run, err := runRuleReview()
+ require.NoError(t, err)
+ require.Equal(t, v1pb.ReviewRun_RULE, run.Type)
+ require.Equal(t, v1pb.ReviewRun_AVAILABLE, run.Status)
+}
diff --git a/backend/api/v1/org_policy_service.go b/backend/api/v1/org_policy_service.go
index 0c1d762917..6cb42e2e89 100644
--- a/backend/api/v1/org_policy_service.go
+++ b/backend/api/v1/org_policy_service.go
@@ -370,13 +370,17 @@ func (*OrgPolicyService) getDefaultRolloutPolicy(parent string) (*store.PolicyMe
}
// getDefaultReviewRulePolicy returns the review rule policy that stands in for
-// a missing row: every rule on. It is the same default the store applies when
-// neither the project nor the workspace has a policy.
+// a missing workspace row: every rule on, the default the store applies when
+// neither the project nor the workspace has a policy. A project without its
+// own policy follows the workspace's, so it has no stand-in and gets nil.
func getDefaultReviewRulePolicy(parent string) (*store.PolicyMessage, error) {
resourceType, resource, err := common.GetPolicyResourceTypeAndResource(parent)
if err != nil {
return nil, connect.NewError(connect.CodeInvalidArgument, err)
}
+ if resourceType != storepb.Policy_WORKSPACE {
+ return nil, nil
+ }
payloadBytes, err := protojson.Marshal(store.GetDefaultReviewRulePolicy())
if err != nil {
diff --git a/backend/api/v1/org_policy_service_review_rule_test.go b/backend/api/v1/org_policy_service_review_rule_test.go
index 6982bbf9ac..409ff187ec 100644
--- a/backend/api/v1/org_policy_service_review_rule_test.go
+++ b/backend/api/v1/org_policy_service_review_rule_test.go
@@ -146,31 +146,36 @@ func TestValidateReviewRulePolicyPayload(t *testing.T) {
}
}
-// TestDefaultReviewRulePolicy pins that the stand-in for a missing row is
-// every rule, and that it survives the store-to-v1 conversion.
+// TestDefaultReviewRulePolicy pins that the stand-in for a missing workspace
+// row is every rule and survives the store-to-v1 conversion, and that a
+// project has no stand-in.
func TestDefaultReviewRulePolicy(t *testing.T) {
t.Parallel()
- message, err := getDefaultReviewRulePolicy("projects/p1")
+ message, err := getDefaultReviewRulePolicy("workspaces/w1")
require.NoError(t, err)
- require.Equal(t, storepb.Policy_PROJECT, message.ResourceType)
- require.Equal(t, "projects/p1", message.Resource)
+ require.Equal(t, storepb.Policy_WORKSPACE, message.ResourceType)
+ require.Equal(t, "workspaces/w1", message.Resource)
require.Equal(t, storepb.Policy_REVIEW_RULE, message.Type)
require.True(t, message.Enforce)
policy, err := convertToPolicy(message)
require.NoError(t, err)
- require.Equal(t, "projects/p1/policies/review_rule", policy.Name)
+ require.Equal(t, "workspaces/w1/policies/review_rule", policy.Name)
require.Equal(t, v1pb.PolicyType_REVIEW_RULE, policy.Type)
got := policy.GetReviewRulePolicy().Rules
require.Len(t, got, len(v1pb.ReviewRuleType_name)-1)
require.NotContains(t, got, v1pb.ReviewRuleType_REVIEW_RULE_TYPE_UNSPECIFIED)
require.Equal(t, len(store.GetDefaultReviewRulePolicy().Rules), len(got))
+
+ message, err = getDefaultReviewRulePolicy("projects/p1")
+ require.NoError(t, err)
+ require.Nil(t, message)
}
// TestReviewRulePolicyService walks the REVIEW_RULE policy through
-// OrgPolicyService at both levels against PostgreSQL: the all-rules default
-// on a missing row, create, get, list, update, validation, delete, and the
-// nearest-wins resolution the store exposes to the executor.
+// OrgPolicyService at both levels against PostgreSQL: a missing row, create,
+// get, list, update, validation, delete, and the nearest-wins resolution the
+// store exposes to the executor.
func TestReviewRulePolicyService(t *testing.T) {
t.Parallel()
ctx := issueServiceTestContext()
@@ -202,6 +207,10 @@ func TestReviewRulePolicyService(t *testing.T) {
require.NoError(t, err)
return resp.Msg
}
+ getCode := func(name string) connect.Code {
+ _, err := service.GetPolicy(ctx, connect.NewRequest(&v1pb.GetPolicyRequest{Name: name}))
+ return connect.CodeOf(err)
+ }
create := func(parent string, policy *v1pb.Policy) (*v1pb.Policy, error) {
resp, err := service.CreatePolicy(ctx, connect.NewRequest(&v1pb.CreatePolicyRequest{Parent: parent, Policy: policy}))
if err != nil {
@@ -231,13 +240,12 @@ func TestReviewRulePolicyService(t *testing.T) {
return names
}
- // No row at either level: every rule, not NotFound.
- got := get(projectPolicyName)
- require.Equal(t, projectPolicyName, got.Name)
+ // No row at either level: the project has no policy of its own, and the
+ // workspace stands in with every rule.
+ require.Equal(t, connect.CodeNotFound, getCode(projectPolicyName))
+ got := get(workspacePolicyName)
+ require.Equal(t, workspacePolicyName, got.Name)
require.Equal(t, v1pb.PolicyType_REVIEW_RULE, got.Type)
- require.Equal(t, v1pb.PolicyResourceType_PROJECT, got.ResourceType)
- require.Len(t, rules(got), everyRule)
- got = get(workspacePolicyName)
require.Equal(t, v1pb.PolicyResourceType_WORKSPACE, got.ResourceType)
require.Len(t, rules(got), everyRule)
require.Len(t, effective(), everyRule)
@@ -260,10 +268,10 @@ func TestReviewRulePolicyService(t *testing.T) {
require.Equal(t, projectPolicyName, listed.Msg.Policies[0].Name)
// Update through the review_rule_policy mask path.
- updated, err := update(projectPolicyName, reviewRule(v1pb.ReviewRuleType_REQUIRE_WHERE))
+ updated, err := update(projectPolicyName, reviewRule(v1pb.ReviewRuleType_SYNTAX, v1pb.ReviewRuleType_REQUIRE_WHERE))
require.NoError(t, err)
- require.Equal(t, []v1pb.ReviewRuleType{v1pb.ReviewRuleType_REQUIRE_WHERE}, rules(updated))
- require.Equal(t, []string{"REQUIRE_WHERE"}, effective())
+ require.Equal(t, []v1pb.ReviewRuleType{v1pb.ReviewRuleType_SYNTAX, v1pb.ReviewRuleType_REQUIRE_WHERE}, rules(updated))
+ require.Equal(t, []string{"SYNTAX", "REQUIRE_WHERE"}, effective())
// Unspecified and repeated rules are refused.
for _, bad := range [][]v1pb.ReviewRuleType{
@@ -280,13 +288,14 @@ func TestReviewRulePolicyService(t *testing.T) {
// Workspace level, and nearest wins: the project's policy while it has
// one, the workspace's after the project's is deleted.
- created, err = create(common.FormatWorkspace(workspaceID), reviewRule(v1pb.ReviewRuleType_DISALLOW_TRUNCATE))
+ created, err = create(common.FormatWorkspace(workspaceID), reviewRule(v1pb.ReviewRuleType_SYNTAX, v1pb.ReviewRuleType_DISALLOW_TRUNCATE))
require.NoError(t, err)
require.Equal(t, workspacePolicyName, created.Name)
- require.Equal(t, []string{"REQUIRE_WHERE"}, effective())
+ require.Equal(t, []string{"SYNTAX", "REQUIRE_WHERE"}, effective())
_, err = service.DeletePolicy(ctx, connect.NewRequest(&v1pb.DeletePolicyRequest{Name: projectPolicyName}))
require.NoError(t, err)
- require.Equal(t, []string{"DISALLOW_TRUNCATE"}, effective())
- require.Len(t, rules(get(projectPolicyName)), everyRule)
+ require.Equal(t, []string{"SYNTAX", "DISALLOW_TRUNCATE"}, effective())
+ require.Equal(t, connect.CodeNotFound, getCode(projectPolicyName))
+ require.Equal(t, rules(created), rules(get(workspacePolicyName)))
}
diff --git a/backend/generated-go/v1/org_policy_service.pb.go b/backend/generated-go/v1/org_policy_service.pb.go
index a513fcdfec..a66b230981 100644
--- a/backend/generated-go/v1/org_policy_service.pb.go
+++ b/backend/generated-go/v1/org_policy_service.pb.go
@@ -706,7 +706,12 @@ func (*Policy_ReviewAiPolicy) isPolicy_Policy() {}
// Standard review rule policy: the rules switched on. The nearest policy
// wins: a project's own policy applies as is; a project without one uses
-// the workspace policy; with neither, every rule is on.
+// the workspace policy; with neither, every rule is on. Getting the policy
+// of a project without its own is NOT_FOUND; getting the workspace's when it
+// has none returns every rule on.
+//
+// SYNTAX gates the rest: the other rules judge only SQL that parses, so a
+// list without SYNTAX switches every rule off.
//
// A saved list is explicit, so a rule added to the standard set in a later
// release is appended to every saved policy by a data migration in that
diff --git a/backend/generated-go/v1/review_rule.pb.go b/backend/generated-go/v1/review_rule.pb.go
index 051ebde72f..cd5b1c6b03 100644
--- a/backend/generated-go/v1/review_rule.pb.go
+++ b/backend/generated-go/v1/review_rule.pb.go
@@ -33,7 +33,8 @@ type ReviewRuleType int32
const (
ReviewRuleType_REVIEW_RULE_TYPE_UNSPECIFIED ReviewRuleType = 0
- // P0: the statements do not parse for the target engine.
+ // P0: the statements do not parse for the target engine. It gates the
+ // other rules (see ReviewRulePolicy).
ReviewRuleType_SYNTAX ReviewRuleType = 1
// P0: applying the statements to the synced schema fails: a missing
// table or column, a duplicate object, or an invalid reference.
diff --git a/backend/runner/reviewrun/main_test.go b/backend/runner/reviewrun/main_test.go
new file mode 100644
index 0000000000..dd2708afec
--- /dev/null
+++ b/backend/runner/reviewrun/main_test.go
@@ -0,0 +1,9 @@
+package reviewrun
+
+import (
+ "testing"
+
+ "github.com/bytebase/bytebase/backend/common/testcontainer"
+)
+
+func TestMain(m *testing.M) { testcontainer.Main(m) }
diff --git a/backend/runner/reviewrun/rule_executor.go b/backend/runner/reviewrun/rule_executor.go
index ee352067b4..8b1f9e03ab 100644
--- a/backend/runner/reviewrun/rule_executor.go
+++ b/backend/runner/reviewrun/rule_executor.go
@@ -66,6 +66,11 @@ func (e *RuleExecutor) RunOnce(ctx context.Context, projectID string, issueUID i
if err != nil {
return nil, errors.Wrapf(err, "failed to get review rule policy")
}
+ // An empty policy is review switched off. omni evaluates SYNTAX whether or
+ // not it is listed, so it is not asked at all.
+ if len(policy.GetRules()) == 0 {
+ return nil, nil
+ }
databaseGroup, err := plancheck.GetDatabaseGroupForPlan(ctx, e.store, plan, nil)
if err != nil {
diff --git a/backend/runner/reviewrun/rule_executor_test.go b/backend/runner/reviewrun/rule_executor_test.go
new file mode 100644
index 0000000000..36c928b4cf
--- /dev/null
+++ b/backend/runner/reviewrun/rule_executor_test.go
@@ -0,0 +1,81 @@
+package reviewrun
+
+import (
+ "context"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+ "google.golang.org/protobuf/encoding/protojson"
+
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/common/testcontainer"
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ "github.com/bytebase/bytebase/backend/store"
+
+ _ "github.com/bytebase/bytebase/backend/plugin/db/pg"
+)
+
+// TestRuleExecutorSkipsAnEmptyPolicy pins that review switched off is no
+// review: the executor returns no findings without resolving a target, where
+// the same issue fails once a rule is on because its target does not exist.
+func TestRuleExecutorSkipsAnEmptyPolicy(t *testing.T) {
+ t.Parallel()
+ ctx := context.Background()
+ db, stores, _ := testcontainer.NewMetadataDB(t)
+ _, err := db.ExecContext(ctx, `
+ INSERT INTO workspace (resource_id) VALUES ('ws');
+ INSERT INTO principal (name, email, password_hash) VALUES ('creator', '[email protected]', 'unused');
+ INSERT INTO project (resource_id, workspace, name) VALUES ('p', 'ws', 'P');
+ `)
+ require.NoError(t, err)
+
+ plan, err := stores.CreatePlan(ctx, &store.PlanMessage{
+ ProjectID: "p",
+ Name: "plan",
+ Config: &storepb.PlanConfig{
+ Specs: []*storepb.PlanConfig_Spec{{
+ Id: "spec-1",
+ Config: &storepb.PlanConfig_Spec_ChangeDatabaseConfig{
+ ChangeDatabaseConfig: &storepb.PlanConfig_ChangeDatabaseConfig{
+ Targets: []string{"instances/missing/databases/app"},
+ },
+ },
+ }},
+ },
+ require.NoError(t, err)
+ issue, err := stores.CreateIssue(ctx, &store.IssueMessage{
+ ProjectID: "p",
+ CreatorEmail: "[email protected]",
+ Title: "issue",
+ Type: storepb.Issue_DATABASE_CHANGE,
+ Payload: &storepb.Issue{},
+ PlanUID: &plan.UID,
+ })
+ require.NoError(t, err)
+
+ setRules := func(rules ...storepb.ReviewRuleType) {
+ t.Helper()
+ payload, err := protojson.Marshal(&storepb.ReviewRulePolicy{Rules: rules})
+ require.NoError(t, err)
+ _, err = stores.CreatePolicy(ctx, &store.PolicyMessage{
+ Workspace: "ws",
+ ResourceType: storepb.Policy_PROJECT,
+ Resource: common.FormatProject("p"),
+ Type: storepb.Policy_REVIEW_RULE,
+ Payload: string(payload),
+ Enforce: true,
+ })
+ require.NoError(t, err)
+ }
+ executor := NewRuleExecutor(stores)
+
+ setRules()
+ comments, err := executor.RunOnce(ctx, "p", issue.UID)
+ require.NoError(t, err)
+ require.Empty(t, comments)
+
+ setRules(storepb.ReviewRuleType_SYNTAX)
+ _, err = executor.RunOnce(ctx, "p", issue.UID)
+ require.Error(t, err)
+}
diff --git a/backend/store/policy.go b/backend/store/policy.go
index f70d8e1c8f..2aff186dc2 100644
--- a/backend/store/policy.go
+++ b/backend/store/policy.go
@@ -484,7 +484,8 @@ func GetDefaultReviewRulePolicy() *storepb.ReviewRulePolicy {
// GetEffectiveReviewRulePolicy returns the standard review rules on for a
// project. The nearest policy wins: the project's own policy applies as is, a
// project without one uses the workspace policy, and with neither every rule
-// is on. A policy that is not enforced counts as absent.
+// is on. A policy that is not enforced counts as absent. SYNTAX gates the
+// rest, so a policy without it leaves no rule on.
func (s *Store) GetEffectiveReviewRulePolicy(ctx context.Context, workspaceID string, projectID string) (*storepb.ReviewRulePolicy, error) {
for _, level := range []struct {
resourceType storepb.Policy_Resource
@@ -498,6 +499,9 @@ func (s *Store) GetEffectiveReviewRulePolicy(ctx context.Context, workspaceID st
return nil, err
}
if policy != nil {
+ if !slices.Contains(policy.Rules, storepb.ReviewRuleType_SYNTAX) {
+ return &storepb.ReviewRulePolicy{}, nil
+ }
return policy, nil
}
}
diff --git a/backend/store/policy_review_rule_test.go b/backend/store/policy_review_rule_test.go
index 441b0b919e..10d52f9b57 100644
--- a/backend/store/policy_review_rule_test.go
+++ b/backend/store/policy_review_rule_test.go
@@ -18,7 +18,7 @@ import (
// TestGetEffectiveReviewRulePolicy pins the nearest-wins resolution: the
// project's own policy applies as is, a project without one uses the
// workspace's, and with neither every rule is on. A policy that is not
-// enforced counts as absent.
+// enforced counts as absent, and one without SYNTAX leaves no rule on.
func TestGetEffectiveReviewRulePolicy(t *testing.T) {
t.Parallel()
ctx := context.Background()
@@ -61,8 +61,12 @@ func TestGetEffectiveReviewRulePolicy(t *testing.T) {
require.Equal(t, []storepb.ReviewRuleType{storepb.ReviewRuleType_SYNTAX, storepb.ReviewRuleType_REQUIRE_WHERE}, effective())
// The project's own policy replaces the workspace's, no union.
+ upsert(storepb.Policy_PROJECT, common.FormatProject("p"), true, storepb.ReviewRuleType_SYNTAX, storepb.ReviewRuleType_DISALLOW_TRUNCATE)
+ require.Equal(t, []storepb.ReviewRuleType{storepb.ReviewRuleType_SYNTAX, storepb.ReviewRuleType_DISALLOW_TRUNCATE}, effective())
+
+ // Without SYNTAX no rule is on, whatever else the list names.
upsert(storepb.Policy_PROJECT, common.FormatProject("p"), true, storepb.ReviewRuleType_DISALLOW_TRUNCATE)
- require.Equal(t, []storepb.ReviewRuleType{storepb.ReviewRuleType_DISALLOW_TRUNCATE}, effective())
+ require.Empty(t, effective())
// An empty project list is a policy too: everything off.
upsert(storepb.Policy_PROJECT, common.FormatProject("p"), true)
@@ -72,6 +76,11 @@ func TestGetEffectiveReviewRulePolicy(t *testing.T) {
upsert(storepb.Policy_PROJECT, common.FormatProject("p"), false, storepb.ReviewRuleType_DISALLOW_TRUNCATE)
require.Equal(t, []storepb.ReviewRuleType{storepb.ReviewRuleType_SYNTAX, storepb.ReviewRuleType_REQUIRE_WHERE}, effective())
+ // A workspace policy without SYNTAX leaves no rule on for the projects
+ // that follow it.
+ upsert(storepb.Policy_WORKSPACE, common.FormatWorkspace("ws"), true, storepb.ReviewRuleType_REQUIRE_WHERE)
+ require.Empty(t, effective())
+
// Same for the workspace: back to every rule.
upsert(storepb.Policy_WORKSPACE, common.FormatWorkspace("ws"), false, storepb.ReviewRuleType_SYNTAX)
require.Equal(t, every, effective())
@@ -86,18 +95,18 @@ func TestGetEffectiveReviewRulePolicy(t *testing.T) {
ResourceType: storepb.Policy_PROJECT,
Resource: common.FormatProject("p"),
Type: storepb.Policy_REVIEW_RULE,
- Payload: payload(storepb.ReviewRuleType_REQUIRE_IS_NULL),
+ Payload: payload(storepb.ReviewRuleType_SYNTAX, storepb.ReviewRuleType_REQUIRE_IS_NULL),
Enforce: true,
})
require.NoError(t, err)
otherEffective, err := stores.GetEffectiveReviewRulePolicy(ctx, "other", "p")
require.NoError(t, err)
- require.Equal(t, []storepb.ReviewRuleType{storepb.ReviewRuleType_REQUIRE_IS_NULL}, otherEffective.Rules)
+ require.Equal(t, []storepb.ReviewRuleType{storepb.ReviewRuleType_SYNTAX, storepb.ReviewRuleType_REQUIRE_IS_NULL}, otherEffective.Rules)
require.Equal(t, every, effective())
- upsert(storepb.Policy_PROJECT, common.FormatProject("p"), true, storepb.ReviewRuleType_DISALLOW_RENAME)
- require.Equal(t, []storepb.ReviewRuleType{storepb.ReviewRuleType_DISALLOW_RENAME}, effective())
+ upsert(storepb.Policy_PROJECT, common.FormatProject("p"), true, storepb.ReviewRuleType_SYNTAX, storepb.ReviewRuleType_DISALLOW_RENAME)
+ require.Equal(t, []storepb.ReviewRuleType{storepb.ReviewRuleType_SYNTAX, storepb.ReviewRuleType_DISALLOW_RENAME}, effective())
otherEffective, err = stores.GetEffectiveReviewRulePolicy(ctx, "other", "p")
require.NoError(t, err)
- require.Equal(t, []storepb.ReviewRuleType{storepb.ReviewRuleType_REQUIRE_IS_NULL}, otherEffective.Rules)
+ require.Equal(t, []storepb.ReviewRuleType{storepb.ReviewRuleType_SYNTAX, storepb.ReviewRuleType_REQUIRE_IS_NULL}, otherEffective.Rules)
}
diff --git a/frontend/src/app/router/handles.ts b/frontend/src/app/router/handles.ts
index 888fd0ea9d..9a4591145c 100644
--- a/frontend/src/app/router/handles.ts
+++ b/frontend/src/app/router/handles.ts
@@ -106,6 +106,7 @@ export const PROJECT_V1_ROUTE_PLAN_ROLLOUT = `${PROJECT_V1_ROUTE_PLAN_DETAIL}.ro
export const PROJECT_V1_ROUTE_PLAN_ROLLOUT_STAGE = `${PROJECT_V1_ROUTE_PLAN_ROLLOUT}.stage`;
export const PROJECT_V1_ROUTE_PLAN_ROLLOUT_TASK = `${PROJECT_V1_ROUTE_PLAN_ROLLOUT_STAGE}.task`;
export const PROJECT_V1_ROUTE_GITOPS = `${PROJECT_V1_ROUTE_DASHBOARD}.gitops`;
+export const PROJECT_V1_ROUTE_SQL_REVIEW = `${PROJECT_V1_ROUTE_DASHBOARD}.sql-review`;
// --- Project route helpers ---
export const PLAN_DETAIL_PHASE_CHANGES = "changes";
diff --git a/frontend/src/app/router/routes/dashboard.tsx b/frontend/src/app/router/routes/dashboard.tsx
index 091ce51e4c..e4ad70c0e4 100644
--- a/frontend/src/app/router/routes/dashboard.tsx
+++ b/frontend/src/app/router/routes/dashboard.tsx
@@ -43,6 +43,7 @@ import {
PROJECT_V1_ROUTE_RELEASES,
PROJECT_V1_ROUTE_SERVICE_ACCOUNTS,
PROJECT_V1_ROUTE_SETTINGS,
+ PROJECT_V1_ROUTE_SQL_REVIEW,
PROJECT_V1_ROUTE_SYNC_SCHEMA,
PROJECT_V1_ROUTE_WEBHOOK_CREATE,
PROJECT_V1_ROUTE_WEBHOOK_DETAIL,
@@ -81,6 +82,7 @@ import { lazyPage } from "@/app/router/lazyPage";
import { ProjectRouteGate } from "@/app/router/ProjectRouteGate";
import { RouteGroupOutlet } from "@/app/router/RouteGroupOutlet";
import type { Permission } from "@/types";
+import { sqlReviewV2Enabled } from "@/utils/featureGates";
// Workspace and project routes nested under the dashboard layouts. Leaf route
// modules are lazy-loaded from their owner under src/routes.
@@ -192,33 +194,38 @@ const workspaceLevelRoutes: RouteObject[] = [
(m) => m.SQLReviewPage
),
},
- {
- path: "new",
- handle: {
- name: WORKSPACE_ROUTE_SQL_REVIEW_CREATE,
- requiredPermissionList: (): Permission[] => [
- "bb.reviewConfigs.create",
- ],
- },
- lazy: lazyPage(
- () => import("@/routes/workspace/SQLReviewCreatePage"),
- (m) => m.SQLReviewCreatePage
- ),
- },
- {
- path: ":sqlReviewPolicySlug",
- handle: {
- name: WORKSPACE_ROUTE_SQL_REVIEW_DETAIL,
- requiredPermissionList: (): Permission[] => [
- "bb.reviewConfigs.get",
- "bb.policies.get",
- ],
- },
- lazy: lazyPage(
- () => import("@/routes/workspace/SQLReviewDetailPage"),
- (m) => m.SQLReviewDetailPage
- ),
- },
+ // The v1 review policy pages go away with SQL Review V2.
+ ...(sqlReviewV2Enabled()
+ ? []
+ : [
+ {
+ path: "new",
+ handle: {
+ name: WORKSPACE_ROUTE_SQL_REVIEW_CREATE,
+ requiredPermissionList: (): Permission[] => [
+ "bb.reviewConfigs.create",
+ ],
+ },
+ lazy: lazyPage(
+ () => import("@/routes/workspace/SQLReviewCreatePage"),
+ (m) => m.SQLReviewCreatePage
+ ),
+ },
+ {
+ path: ":sqlReviewPolicySlug",
+ handle: {
+ name: WORKSPACE_ROUTE_SQL_REVIEW_DETAIL,
+ requiredPermissionList: (): Permission[] => [
+ "bb.reviewConfigs.get",
+ "bb.policies.get",
+ ],
+ },
+ lazy: lazyPage(
+ () => import("@/routes/workspace/SQLReviewDetailPage"),
+ (m) => m.SQLReviewDetailPage
+ ),
+ },
+ ]),
],
},
// /idps — SettingRouteShell layout. The parent carries the route permission
@@ -829,6 +836,23 @@ const projectV1Routes: RouteObject[] = [
(m) => m.WorkloadIdentitiesPage
),
},
+ // Dark-launched with SQL Review V2: the route exists only where the
+ // sidebar entry that leads to it does.
+ ...(sqlReviewV2Enabled()
+ ? [
+ {
+ path: "sql-review",
+ handle: {
+ name: PROJECT_V1_ROUTE_SQL_REVIEW,
+ requiredPermissionList: (): Permission[] => ["bb.policies.get"],
+ },
+ lazy: lazyPage(
+ () => import("@/routes/project/ProjectSQLReviewPage"),
+ (m) => m.ProjectSQLReviewPage
+ ),
+ },
+ ]
+ : []),
{
path: "settings",
handle: { name: PROJECT_V1_ROUTE_SETTINGS },
diff --git a/frontend/src/components/ProjectSidebar.tsx b/frontend/src/components/ProjectSidebar.tsx
index 296ab16f9b..77125cbfc6 100644
--- a/frontend/src/components/ProjectSidebar.tsx
+++ b/frontend/src/components/ProjectSidebar.tsx
@@ -26,6 +26,7 @@ import {
PROJECT_V1_ROUTE_RELEASES,
PROJECT_V1_ROUTE_SERVICE_ACCOUNTS,
PROJECT_V1_ROUTE_SETTINGS,
+ PROJECT_V1_ROUTE_SQL_REVIEW,
PROJECT_V1_ROUTE_SYNC_SCHEMA,
PROJECT_V1_ROUTE_WEBHOOKS,
PROJECT_V1_ROUTE_WORKLOAD_IDENTITIES,
@@ -34,6 +35,7 @@ import { RouterLink } from "@/components/RouterLink";
import { useRecentVisit } from "@/hooks/useRecentVisit";
import { useAppStore } from "@/stores/app";
import { projectNamePrefix } from "@/stores/modules/v1/common";
+import { sqlReviewV2Enabled } from "@/utils/featureGates";
// ---------------------------------------------------------------------------
// Types
@@ -110,6 +112,12 @@ function useSidebarItems(): SidebarItem[] {
path: PROJECT_V1_ROUTE_GITOPS,
type: "div",
},
+ {
+ title: t("sql-review.title"),
+ path: PROJECT_V1_ROUTE_SQL_REVIEW,
+ type: "div",
+ hide: !sqlReviewV2Enabled(),
+ },
],
},
{
diff --git a/frontend/src/components/sql-review/StandardRuleSwitches.test.tsx b/frontend/src/components/sql-review/StandardRuleSwitches.test.tsx
new file mode 100644
index 0000000000..34826ef86b
--- /dev/null
+++ b/frontend/src/components/sql-review/StandardRuleSwitches.test.tsx
@@ -0,0 +1,152 @@
+import { fireEvent, render, screen } from "@testing-library/react";
+import { useState } from "react";
+import { describe, expect, test, vi } from "vitest";
+import { ReviewRuleType } from "@/types/proto-es/v1/review_rule_pb";
+import { StandardRuleSwitches } from "./StandardRuleSwitches";
+import { STANDARD_RULE_TYPES } from "./standardRules";
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+const ruleSwitch = (rule: string) =>
+ screen.getByRole("switch", {
+ name: `sql-review.standard-rules.rule.${rule}.title`,
+ });
+
+// Holds the rules the way a page does, so a sequence of clicks can be tested.
+function Stateful({
+ initial,
+ onChange,
+}: {
+ initial: readonly ReviewRuleType[];
+ onChange: (rules: ReviewRuleType[]) => void;
+}) {
+ const [rules, setRules] = useState<readonly ReviewRuleType[]>(initial);
+ return (
+ <StandardRuleSwitches
+ rules={rules}
+ onChange={(next) => {
+ setRules(next);
+ onChange(next);
+ }}
+ />
+ );
+}
+
+describe("StandardRuleSwitches", () => {
+ test("switches one rule and reports the list in display order", () => {
+ const onChange = vi.fn();
+ render(
+ <StandardRuleSwitches
+ rules={[ReviewRuleType.DISALLOW_RENAME, ReviewRuleType.SYNTAX]}
+ onChange={onChange}
+ />
+ );
+
+ expect(screen.getAllByRole("switch")).toHaveLength(
+ STANDARD_RULE_TYPES.length
+ );
+ expect(
+ screen.getByText("sql-review.standard-rules.running")
+ ).toBeInTheDocument();
+ expect(ruleSwitch("require-where")).toHaveAttribute(
+ "aria-checked",
+ "false"
+ );
+ fireEvent.click(ruleSwitch("require-where"));
+ expect(onChange).toHaveBeenLastCalledWith([
+ ReviewRuleType.SYNTAX,
+ ReviewRuleType.REQUIRE_WHERE,
+ ReviewRuleType.DISALLOW_RENAME,
+ ]);
+
+ fireEvent.click(ruleSwitch("disallow-rename"));
+ expect(onChange).toHaveBeenLastCalledWith([ReviewRuleType.SYNTAX]);
+ });
+
+ test("turning SYNTAX off switches every rule off", () => {
+ const onChange = vi.fn();
+ render(
+ <StandardRuleSwitches rules={STANDARD_RULE_TYPES} onChange={onChange} />
+ );
+
+ expect(
+ screen.queryByText("sql-review.standard-rules.syntax-off")
+ ).not.toBeInTheDocument();
+ fireEvent.click(ruleSwitch("syntax"));
+ expect(onChange).toHaveBeenLastCalledWith([]);
+ });
+
+ test("with nothing on, the status line explains it and the rest are locked", () => {
+ const onChange = vi.fn();
+ render(<StandardRuleSwitches rules={[]} onChange={onChange} />);
+
+ expect(
+ screen.getByText("sql-review.standard-rules.syntax-off")
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByText("sql-review.standard-rules.running")
+ ).not.toBeInTheDocument();
+ expect(ruleSwitch("syntax")).not.toHaveAttribute("data-disabled");
+ expect(ruleSwitch("require-where")).toHaveAttribute("data-disabled");
+ expect(ruleSwitch("require-where")).toHaveAttribute(
+ "aria-checked",
+ "false"
+ );
+
+ // Nothing to restore, so SYNTAX brings every rule back.
+ fireEvent.click(ruleSwitch("syntax"));
+ expect(onChange).toHaveBeenLastCalledWith([...STANDARD_RULE_TYPES]);
+ });
+
+ test("turning SYNTAX back on restores the rules from before", () => {
+ const onChange = vi.fn();
+ render(<Stateful initial={STANDARD_RULE_TYPES} onChange={onChange} />);
+
+ fireEvent.click(ruleSwitch("disallow-truncate"));
+ fireEvent.click(ruleSwitch("syntax"));
+ expect(onChange).toHaveBeenLastCalledWith([]);
+ expect(ruleSwitch("disallow-rename")).toHaveAttribute(
+ "aria-checked",
+ "false"
+ );
+
+ fireEvent.click(ruleSwitch("syntax"));
+ expect(onChange).toHaveBeenLastCalledWith(
+ STANDARD_RULE_TYPES.filter(
+ (rule) => rule !== ReviewRuleType.DISALLOW_TRUNCATE
+ )
+ );
+ });
+
+ test("disabled locks every switch", () => {
+ render(
+ <StandardRuleSwitches
+ rules={STANDARD_RULE_TYPES}
+ onChange={vi.fn()}
+ disabled
+ />
+ );
+
+ for (const control of screen.getAllByRole("switch")) {
+ expect(control).toHaveAttribute("data-disabled");
+ }
+ });
+
+ test("read-only shows each rule's state as text", () => {
+ render(
+ <StandardRuleSwitches
+ rules={[ReviewRuleType.SYNTAX, ReviewRuleType.REQUIRE_WHERE]}
+ onChange={vi.fn()}
+ readOnly
+ />
+ );
+
+ expect(screen.queryAllByRole("switch")).toHaveLength(0);
+ expect(screen.getAllByText("sql-review.standard-rules.on")).toHaveLength(2);
+ expect(screen.getAllByText("sql-review.standard-rules.off")).toHaveLength(
+ STANDARD_RULE_TYPES.length - 2
+ );
+ });
+});
diff --git a/frontend/src/components/sql-review/StandardRuleSwitches.tsx b/frontend/src/components/sql-review/StandardRuleSwitches.tsx
new file mode 100644
index 0000000000..25f97b040c
--- /dev/null
+++ b/frontend/src/components/sql-review/StandardRuleSwitches.tsx
@@ -0,0 +1,99 @@
+import { useRef } from "react";
+import { useTranslation } from "react-i18next";
+import { cn } from "@/lib/utils";
+import { ReviewRuleType } from "@/types/proto-es/v1/review_rule_pb";
+import { SwitchRow } from "./SwitchRow";
+import {
+ isStandardReviewOn,
+ STANDARD_RULE_TYPES,
+ standardRuleText,
+} from "./standardRules";
+
+interface StandardRuleSwitchesProps {
+ // The rules switched on.
+ rules: readonly ReviewRuleType[];
+ onChange: (rules: ReviewRuleType[]) => void;
+ disabled?: boolean;
+ // Shows each rule's state as text instead of a switch, for rules that are
+ // set elsewhere.
+ readOnly?: boolean;
+}
+
+export function StandardRuleSwitches({
+ rules,
+ onChange,
+ disabled = false,
+ readOnly = false,
+}: StandardRuleSwitchesProps) {
+ const { t } = useTranslation();
+ const reviewOn = isStandardReviewOn(rules);
+
+ // SYNTAX gates the rest, and the backend reads a list without it as empty,
+ // so switching it off saves an empty list. Switching it back on restores
+ // the rules from before it went off in this session, else every rule.
+ const rulesWithSyntax = useRef<readonly ReviewRuleType[] | undefined>(
+ undefined
+ );
+ if (reviewOn) {
+ rulesWithSyntax.current = rules;
+ }
+ const toggle = (rule: ReviewRuleType, on: boolean) => {
+ if (rule === ReviewRuleType.SYNTAX) {
+ onChange(on ? [...(rulesWithSyntax.current ?? STANDARD_RULE_TYPES)] : []);
+ return;
+ }
+ onChange(
+ STANDARD_RULE_TYPES.filter((type) =>
+ type === rule ? on : rules.includes(type)
+ )
+ );
+ };
+
+ return (
+ <div className="rounded-sm border border-block-border">
+ {/* The status line keeps its place whether or not SYNTAX is on, so
+ switching it does not move the rules below. */}
+ <div
+ role="status"
+ className={cn(
+ "flex items-center gap-x-2 border-b px-4 py-2 text-sm",
+ reviewOn
+ ? "border-block-border bg-control-bg text-control-light"
+ : "border-warning/40 bg-warning/10 text-warning"
+ )}
+ >
+ <span
+ className={cn(
+ "size-1.5 shrink-0 rounded-full",
+ reviewOn ? "bg-accent" : "bg-warning"
+ )}
+ />
+ {reviewOn
+ ? t("sql-review.standard-rules.running", {
+ on: rules.length,
+ total: STANDARD_RULE_TYPES.length,
+ })
+ : t("sql-review.standard-rules.syntax-off")}
+ </div>
+ <div className="divide-y divide-block-border">
+ {STANDARD_RULE_TYPES.map((rule) => {
+ const text = standardRuleText(t, rule);
+ return (
+ <SwitchRow
+ key={rule}
+ className="px-4 py-3"
+ title={text.title}
+ description={text.description}
+ checked={rules.includes(rule)}
+ onCheckedChange={(on) => toggle(rule, on)}
+ disabled={
+ disabled || (rule !== ReviewRuleType.SYNTAX && !reviewOn)
+ }
+ readOnly={readOnly}
+ />
+ );
+ })}
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/src/components/sql-review/SwitchRow.tsx b/frontend/src/components/sql-review/SwitchRow.tsx
new file mode 100644
index 0000000000..62769eb8e7
--- /dev/null
+++ b/frontend/src/components/sql-review/SwitchRow.tsx
@@ -0,0 +1,64 @@
+import type { ReactNode } from "react";
+import { useTranslation } from "react-i18next";
+import { Switch } from "@/components/ui/switch";
+import { cn } from "@/lib/utils";
+
+interface SwitchRowProps {
+ title: string;
+ description?: ReactNode;
+ checked: boolean;
+ onCheckedChange: (checked: boolean) => void;
+ disabled?: boolean;
+ // Shows the state as text instead of a switch, for a setting made elsewhere.
+ readOnly?: boolean;
+ className?: string;
+}
+
+// A setting whose text takes the row and whose control trails it.
+export function SwitchRow({
+ title,
+ description,
+ checked,
+ onCheckedChange,
+ disabled = false,
+ readOnly = false,
+ className,
+}: SwitchRowProps) {
+ const { t } = useTranslation();
+ return (
+ <div className={cn("flex items-center justify-between gap-x-4", className)}>
+ <div className="flex min-w-0 flex-col">
+ <div className="text-sm font-medium text-main">{title}</div>
+ {description !== undefined && (
+ <div className="text-sm text-control-light">{description}</div>
+ )}
+ </div>
+ {readOnly ? (
+ <span
+ className={cn(
+ "inline-flex shrink-0 items-center gap-x-1.5 text-xs",
+ checked ? "text-main" : "text-control-light"
+ )}
+ >
+ <span
+ className={cn(
+ "size-1.5 rounded-full",
+ checked ? "bg-accent" : "bg-control-placeholder"
+ )}
+ />
+ {checked
+ ? t("sql-review.standard-rules.on")
+ : t("sql-review.standard-rules.off")}
+ </span>
+ ) : (
+ <Switch
+ className="shrink-0"
+ checked={checked}
+ onCheckedChange={onCheckedChange}
+ disabled={disabled}
+ aria-label={title}
+ />
+ )}
+ </div>
+ );
+}
diff --git a/frontend/src/components/sql-review/standardRules.test.ts b/frontend/src/components/sql-review/standardRules.test.ts
new file mode 100644
index 0000000000..cbbee799de
--- /dev/null
+++ b/frontend/src/components/sql-review/standardRules.test.ts
@@ -0,0 +1,96 @@
+import { create } from "@bufbuild/protobuf";
+import type { TFunction } from "i18next";
+import { describe, expect, test } from "vitest";
+import {
+ PolicySchema,
+ PolicyType,
+ ReviewRulePolicySchema,
+} from "@/types/proto-es/v1/org_policy_service_pb";
+import { ReviewRuleType } from "@/types/proto-es/v1/review_rule_pb";
+import {
+ isStandardReviewOn,
+ reviewRulesOfPolicy,
+ STANDARD_RULE_TYPES,
+ sameStandardRules,
+ sortStandardRules,
+ standardRuleText,
+} from "./standardRules";
+
+const t = ((key: string) => key) as unknown as TFunction;
+
+const everyRuleType = Object.values(ReviewRuleType).filter(
+ (value): value is ReviewRuleType =>
+ typeof value === "number" &&
+ value !== ReviewRuleType.REVIEW_RULE_TYPE_UNSPECIFIED
+);
+
+describe("standard rules", () => {
+ test("list every review rule type once", () => {
+ expect([...STANDARD_RULE_TYPES].sort((a, b) => a - b)).toEqual(
+ everyRuleType.sort((a, b) => a - b)
+ );
+ });
+
+ test("give every rule its own title and description", () => {
+ const keys = STANDARD_RULE_TYPES.flatMap((rule) => {
+ const { title, description } = standardRuleText(t, rule);
+ return [title, description];
+ });
+ for (const key of keys) {
+ expect(key).toMatch(/^sql-review\.standard-rules\.rule\./);
+ }
+ expect(new Set(keys).size).toBe(keys.length);
+ });
+
+ test("compare lists regardless of order", () => {
+ expect(
+ sortStandardRules([
+ ReviewRuleType.REQUIRE_WHERE,
+ ReviewRuleType.SYNTAX,
+ ReviewRuleType.REVIEW_RULE_TYPE_UNSPECIFIED,
+ ])
+ ).toEqual([ReviewRuleType.SYNTAX, ReviewRuleType.REQUIRE_WHERE]);
+ expect(
+ sameStandardRules(
+ [ReviewRuleType.REQUIRE_WHERE, ReviewRuleType.SYNTAX],
+ [ReviewRuleType.SYNTAX, ReviewRuleType.REQUIRE_WHERE]
+ )
+ ).toBe(true);
+ expect(
+ sameStandardRules([ReviewRuleType.SYNTAX], [ReviewRuleType.WALK_THROUGH])
+ ).toBe(false);
+ });
+
+ test("read the rules of a policy, and nothing from a policy without one", () => {
+ expect(reviewRulesOfPolicy(undefined)).toBeUndefined();
+ // What the store caches when a project has no policy of its own.
+ expect(
+ reviewRulesOfPolicy(
+ create(PolicySchema, { name: "projects/p/policies/review_rule" })
+ )
+ ).toBeUndefined();
+ expect(
+ reviewRulesOfPolicy(
+ create(PolicySchema, {
+ type: PolicyType.REVIEW_RULE,
+ policy: {
+ case: "reviewRulePolicy",
+ value: create(ReviewRulePolicySchema, {
+ rules: [ReviewRuleType.DISALLOW_RENAME, ReviewRuleType.SYNTAX],
+ }),
+ },
+ })
+ )
+ ).toEqual([ReviewRuleType.SYNTAX, ReviewRuleType.DISALLOW_RENAME]);
+ });
+
+ test("need SYNTAX for standard review to run", () => {
+ expect(isStandardReviewOn(STANDARD_RULE_TYPES)).toBe(true);
+ expect(
+ isStandardReviewOn(
+ STANDARD_RULE_TYPES.filter((rule) => rule !== ReviewRuleType.SYNTAX)
+ )
+ ).toBe(false);
+ expect(isStandardReviewOn([])).toBe(false);
+ });
+});
diff --git a/frontend/src/components/sql-review/standardRules.ts b/frontend/src/components/sql-review/standardRules.ts
new file mode 100644
index 0000000000..9a62816333
--- /dev/null
+++ b/frontend/src/components/sql-review/standardRules.ts
@@ -0,0 +1,136 @@
+import type { TFunction } from "i18next";
+import type { Policy } from "@/types/proto-es/v1/org_policy_service_pb";
+import { ReviewRuleType } from "@/types/proto-es/v1/review_rule_pb";
+
+// The standard rules in display order.
+export const STANDARD_RULE_TYPES: readonly ReviewRuleType[] = [
+ ReviewRuleType.SYNTAX,
+ ReviewRuleType.WALK_THROUGH,
+ ReviewRuleType.ONLINE_MIGRATION,
+ ReviewRuleType.PRIOR_BACKUP,
+ ReviewRuleType.REQUIRE_IS_NULL,
+ ReviewRuleType.REQUIRE_WHERE,
+ ReviewRuleType.DISALLOW_DROP_OBJECT,
+ ReviewRuleType.DISALLOW_TRUNCATE,
+ ReviewRuleType.DISALLOW_DROP_CONSTRAINT,
+ ReviewRuleType.DISALLOW_RENAME,
+ ReviewRuleType.REQUIRE_PRIMARY_KEY,
+];
+
+// Puts rules in display order, which makes two lists comparable.
+export const sortStandardRules = (
+ rules: readonly ReviewRuleType[]
+): ReviewRuleType[] =>
+ STANDARD_RULE_TYPES.filter((rule) => rules.includes(rule));
+
+export const sameStandardRules = (
+ a: readonly ReviewRuleType[],
+ b: readonly ReviewRuleType[]
+): boolean => {
+ const left = sortStandardRules(a);
+ const right = sortStandardRules(b);
+ return (
+ left.length === right.length &&
+ left.every((rule, index) => rule === right[index])
+ );
+};
+
+// The rules a cached review rule policy switches on, or undefined when the
+// resource has none of its own.
+export const reviewRulesOfPolicy = (
+ policy: Policy | undefined
+): ReviewRuleType[] | undefined =>
+ policy?.policy.case === "reviewRulePolicy"
+ ? sortStandardRules(policy.policy.value.rules)
+ : undefined;
+
+// SYNTAX gates the rest: without it no standard rule runs.
+export const isStandardReviewOn = (rules: readonly ReviewRuleType[]): boolean =>
+ rules.includes(ReviewRuleType.SYNTAX);
+
+export const standardRuleText = (
+ t: TFunction,
+ rule: ReviewRuleType
+): { title: string; description: string } => {
+ switch (rule) {
+ case ReviewRuleType.SYNTAX:
+ return {
+ title: t("sql-review.standard-rules.rule.syntax.title"),
+ description: t("sql-review.standard-rules.rule.syntax.description"),
+ };
+ case ReviewRuleType.WALK_THROUGH:
+ return {
+ title: t("sql-review.standard-rules.rule.walk-through.title"),
+ description: t(
+ "sql-review.standard-rules.rule.walk-through.description"
+ ),
+ };
+ case ReviewRuleType.ONLINE_MIGRATION:
+ return {
+ title: t("sql-review.standard-rules.rule.online-migration.title"),
+ description: t(
+ "sql-review.standard-rules.rule.online-migration.description"
+ ),
+ };
+ case ReviewRuleType.PRIOR_BACKUP:
+ return {
+ title: t("sql-review.standard-rules.rule.prior-backup.title"),
+ description: t(
+ "sql-review.standard-rules.rule.prior-backup.description"
+ ),
+ };
+ case ReviewRuleType.REQUIRE_IS_NULL:
+ return {
+ title: t("sql-review.standard-rules.rule.require-is-null.title"),
+ description: t(
+ "sql-review.standard-rules.rule.require-is-null.description"
+ ),
+ };
+ case ReviewRuleType.REQUIRE_WHERE:
+ return {
+ title: t("sql-review.standard-rules.rule.require-where.title"),
+ description: t(
+ "sql-review.standard-rules.rule.require-where.description"
+ ),
+ };
+ case ReviewRuleType.DISALLOW_DROP_OBJECT:
+ return {
+ title: t("sql-review.standard-rules.rule.disallow-drop-object.title"),
+ description: t(
+ "sql-review.standard-rules.rule.disallow-drop-object.description"
+ ),
+ };
+ case ReviewRuleType.DISALLOW_TRUNCATE:
+ return {
+ title: t("sql-review.standard-rules.rule.disallow-truncate.title"),
+ description: t(
+ "sql-review.standard-rules.rule.disallow-truncate.description"
+ ),
+ };
+ case ReviewRuleType.DISALLOW_DROP_CONSTRAINT:
+ return {
+ title: t(
+ "sql-review.standard-rules.rule.disallow-drop-constraint.title"
+ ),
+ description: t(
+ "sql-review.standard-rules.rule.disallow-drop-constraint.description"
+ ),
+ };
+ case ReviewRuleType.DISALLOW_RENAME:
+ return {
+ title: t("sql-review.standard-rules.rule.disallow-rename.title"),
+ description: t(
+ "sql-review.standard-rules.rule.disallow-rename.description"
+ ),
+ };
+ case ReviewRuleType.REQUIRE_PRIMARY_KEY:
+ return {
+ title: t("sql-review.standard-rules.rule.require-primary-key.title"),
+ description: t(
+ "sql-review.standard-rules.rule.require-primary-key.description"
+ ),
+ };
+ default:
+ return { title: ReviewRuleType[rule] ?? String(rule), description: "" };
+ }
+};
diff --git a/frontend/src/locales/sql-review/en-US.json b/frontend/src/locales/sql-review/en-US.json
index 0f5eb3ea30..dcfade31e0 100644
--- a/frontend/src/locales/sql-review/en-US.json
+++ b/frontend/src/locales/sql-review/en-US.json
@@ -729,6 +729,66 @@
},
"select-all": "Select all",
"select-review-rules": "Select SQL review rules",
+ "standard-rules": {
+ "customize": {
+ "description": "When off, this project follows the workspace standard rules.",
+ "self": "Customize for this project",
+ "view-workspace-rules": "View workspace rules"
+ },
+ "description": "Built-in rules that review the SQL of every issue. Projects that do not customize their rules follow these.",
+ "off": "Off",
+ "on": "On",
+ "project-description": "Built-in rules that review the SQL of every issue in this project.",
+ "rule": {
+ "disallow-drop-constraint": {
+ "description": "Flags dropping a PRIMARY KEY, FOREIGN KEY, UNIQUE, or CHECK constraint.",
+ "title": "Dropping constraints"
+ },
+ "disallow-drop-object": {
+ "description": "Flags DROP TABLE, COLUMN, SCHEMA, or DATABASE.",
+ "title": "Dropping objects"
+ },
+ "disallow-rename": {
+ "description": "Flags renaming a table or column.",
+ "title": "Renaming"
+ },
+ "disallow-truncate": {
+ "description": "Flags TRUNCATE.",
+ "title": "Truncating tables"
+ },
+ "online-migration": {
+ "description": "Flags a change that requests online migration but is not eligible for it.",
+ "title": "Online migration eligibility"
+ },
+ "prior-backup": {
+ "description": "Flags a change that enables prior backup when the backup cannot be taken.",
+ "title": "Prior backup feasibility"
+ },
+ "require-is-null": {
+ "description": "Flags = NULL or <> NULL in a predicate, which is never true. Use IS NULL or IS NOT NULL instead.",
+ "title": "NULL comparison"
+ },
+ "require-primary-key": {
+ "description": "Flags a table the change creates without a primary key, or a primary key it drops without adding one back.",
+ "title": "Primary key"
+ },
+ "require-where": {
+ "description": "Flags UPDATE or DELETE without a WHERE clause.",
+ "title": "WHERE clause"
+ },
+ "syntax": {
+ "description": "Flags statements that do not parse for the database engine. The other rules only check SQL that parses, so turning this off turns off every standard rule.",
+ "title": "Syntax"
+ },
+ "walk-through": {
+ "description": "Flags statements that fail against the synced schema, such as a missing table or column, a duplicate object, or an invalid reference.",
+ "title": "Schema walk-through"
+ }
+ },
+ "running": "{{on}} of {{total}} rules running",
+ "self": "Standard rules",
+ "syntax-off": "Syntax is off, so none of the standard rules run. Turn Syntax on to review changes."
+ },
"template": {
"bb-sql-review-dev": "Basic Template",
"bb-sql-review-dev-desc": "Basic coverage to defend your databases from common misusage.",
diff --git a/frontend/src/locales/sql-review/es-ES.json b/frontend/src/locales/sql-review/es-ES.json
index 4589038b39..5cad0aa4f6 100644
--- a/frontend/src/locales/sql-review/es-ES.json
+++ b/frontend/src/locales/sql-review/es-ES.json
@@ -729,6 +729,66 @@
},
"select-all": "Seleccionar todo",
"select-review-rules": "Seleccionar reglas de revisión de SQL",
+ "standard-rules": {
+ "customize": {
+ "description": "Si está desactivado, este proyecto sigue las reglas estándar del espacio de trabajo.",
+ "self": "Personalizar para este proyecto",
+ "view-workspace-rules": "Ver las reglas del espacio de trabajo"
+ },
+ "description": "Reglas integradas que revisan el SQL de cada issue. Los proyectos que no personalizan sus reglas siguen estas.",
+ "off": "Desactivada",
+ "on": "Activada",
+ "project-description": "Reglas integradas que revisan el SQL de cada issue de este proyecto.",
+ "rule": {
+ "disallow-drop-constraint": {
+ "description": "Señala la eliminación de una restricción PRIMARY KEY, FOREIGN KEY, UNIQUE o CHECK.",
+ "title": "Eliminación de restricciones"
+ },
+ "disallow-drop-object": {
+ "description": "Señala DROP TABLE, COLUMN, SCHEMA o DATABASE.",
+ "title": "Eliminación de objetos"
+ },
+ "disallow-rename": {
+ "description": "Señala el cambio de nombre de una tabla o columna.",
+ "title": "Cambio de nombre"
+ },
+ "disallow-truncate": {
+ "description": "Señala TRUNCATE.",
+ "title": "Vaciado de tablas"
+ },
+ "online-migration": {
+ "description": "Señala un cambio que solicita migración en línea pero no es apto para ella.",
+ "title": "Idoneidad para la migración en línea"
+ },
+ "prior-backup": {
+ "description": "Señala un cambio que activa la copia de seguridad previa cuando no se puede realizar.",
+ "title": "Viabilidad de la copia de seguridad previa"
+ },
+ "require-is-null": {
+ "description": "Señala = NULL o <> NULL en un predicado, que nunca es verdadero. Use IS NULL o IS NOT NULL en su lugar.",
+ "title": "Comparación con NULL"
+ },
+ "require-primary-key": {
+ "description": "Señala una tabla que el cambio crea sin clave primaria, o una clave primaria que elimina sin volver a añadirla.",
+ "title": "Clave primaria"
+ },
+ "require-where": {
+ "description": "Señala UPDATE o DELETE sin cláusula WHERE.",
+ "title": "Cláusula WHERE"
+ },
+ "syntax": {
+ "description": "Señala las sentencias que el motor de base de datos no puede analizar. Las demás reglas solo comprueban SQL que se puede analizar, por lo que desactivar esta regla desactiva todas las reglas estándar.",
+ "title": "Sintaxis"
+ },
+ "walk-through": {
+ "description": "Señala las sentencias que fallan contra el esquema sincronizado, como una tabla o columna inexistente, un objeto duplicado o una referencia no válida.",
+ "title": "Recorrido del esquema"
+ }
+ },
+ "running": "{{on}} de {{total}} reglas activas",
+ "self": "Reglas estándar",
+ "syntax-off": "La sintaxis está desactivada, por lo que no se ejecuta ninguna regla estándar. Active la sintaxis para revisar los cambios."
+ },
"template": {
"bb-sql-review-dev": "Plantilla Básica",
"bb-sql-review-dev-desc": "Cobertura básica para defender sus bases de datos de uso indebido común.",
diff --git a/frontend/src/locales/sql-review/ja-JP.json b/frontend/src/locales/sql-review/ja-JP.json
index be0d6d2471..584c328126 100644
--- a/frontend/src/locales/sql-review/ja-JP.json
+++ b/frontend/src/locales/sql-review/ja-JP.json
@@ -729,6 +729,66 @@
},
"select-all": "すべて選択",
"select-review-rules": "SQL レビュールールを選択",
+ "standard-rules": {
+ "customize": {
+ "description": "オフの場合、このプロジェクトはワークスペースの標準ルールに従います。",
+ "self": "このプロジェクト用にカスタマイズ",
+ "view-workspace-rules": "ワークスペースのルールを表示"
+ },
+ "description": "すべての Issue の SQL をレビューする組み込みルールです。ルールをカスタマイズしていないプロジェクトはこの設定に従います。",
+ "off": "オフ",
+ "on": "オン",
+ "project-description": "このプロジェクトのすべての Issue の SQL をレビューする組み込みルールです。",
+ "rule": {
+ "disallow-drop-constraint": {
+ "description": "PRIMARY KEY、FOREIGN KEY、UNIQUE、CHECK 制約の削除を検出します。",
+ "title": "制約の削除"
+ },
+ "disallow-drop-object": {
+ "description": "DROP TABLE、COLUMN、SCHEMA、DATABASE を検出します。",
+ "title": "オブジェクトの削除"
+ },
+ "disallow-rename": {
+ "description": "テーブルまたは列の名前変更を検出します。",
+ "title": "名前の変更"
+ },
+ "disallow-truncate": {
+ "description": "TRUNCATE を検出します。",
+ "title": "テーブルの切り捨て"
+ },
+ "online-migration": {
+ "description": "オンライン移行を要求しているが、その条件を満たさない変更を検出します。",
+ "title": "オンライン移行の適格性"
+ },
+ "prior-backup": {
+ "description": "事前バックアップが有効だが、バックアップを取得できない変更を検出します。",
+ "title": "事前バックアップの実行可能性"
+ },
+ "require-is-null": {
+ "description": "述語内の = NULL または <> NULL を検出します。これらが真になることはありません。代わりに IS NULL または IS NOT NULL を使用してください。",
+ "title": "NULL の比較"
+ },
+ "require-primary-key": {
+ "description": "変更で作成されるテーブルに主キーがない場合や、削除した主キーを再追加しない場合を検出します。",
+ "title": "主キー"
+ },
+ "require-where": {
+ "description": "WHERE 句のない UPDATE または DELETE を検出します。",
+ "title": "WHERE 句"
+ },
+ "syntax": {
+ "description": "データベースエンジンで解析できないステートメントを検出します。他のルールは解析できる SQL のみをチェックするため、これをオフにするとすべての標準ルールがオフになります。",
+ "title": "構文"
+ },
+ "walk-through": {
+ "description": "同期済みのスキーマに対して失敗するステートメントを検出します。例: 存在しないテーブルや列、重複したオブジェクト、無効な参照。",
+ "title": "スキーマウォークスルー"
+ }
+ },
+ "running": "{{total}} 件中 {{on}} 件のルールが有効",
+ "self": "標準ルール",
+ "syntax-off": "構文チェックがオフのため、標準ルールはいずれも実行されません。変更をレビューするには構文チェックをオンにしてください。"
+ },
"template": {
"bb-sql-review-dev": "基本的なテンプレート",
"bb-sql-review-dev-desc": "一般的な誤用からデータベースを守るための基本的なカバレッジ。",
diff --git a/frontend/src/locales/sql-review/vi-VN.json b/frontend/src/locales/sql-review/vi-VN.json
index a8cfdd4eb2..26abd987b8 100644
--- a/frontend/src/locales/sql-review/vi-VN.json
+++ b/frontend/src/locales/sql-review/vi-VN.json
@@ -729,6 +729,66 @@
},
"select-all": "Chọn tất cả",
"select-review-rules": "Chọn quy tắc đánh giá SQL",
+ "standard-rules": {
+ "customize": {
+ "description": "Khi tắt, dự án này tuân theo các quy tắc tiêu chuẩn của không gian làm việc.",
+ "self": "Tùy chỉnh cho dự án này",
+ "view-workspace-rules": "Xem quy tắc của không gian làm việc"
+ },
+ "description": "Các quy tắc tích hợp sẵn dùng để đánh giá SQL của mọi issue. Các dự án không tùy chỉnh quy tắc sẽ tuân theo các quy tắc này.",
+ "off": "Tắt",
+ "on": "Bật",
+ "project-description": "Các quy tắc tích hợp sẵn dùng để đánh giá SQL của mọi issue trong dự án này.",
+ "rule": {
+ "disallow-drop-constraint": {
+ "description": "Đánh dấu việc xóa ràng buộc PRIMARY KEY, FOREIGN KEY, UNIQUE hoặc CHECK.",
+ "title": "Xóa ràng buộc"
+ },
+ "disallow-drop-object": {
+ "description": "Đánh dấu DROP TABLE, COLUMN, SCHEMA hoặc DATABASE.",
+ "title": "Xóa đối tượng"
+ },
+ "disallow-rename": {
+ "description": "Đánh dấu việc đổi tên bảng hoặc cột.",
+ "title": "Đổi tên"
+ },
+ "disallow-truncate": {
+ "description": "Đánh dấu TRUNCATE.",
+ "title": "Làm trống bảng"
+ },
+ "online-migration": {
+ "description": "Đánh dấu thay đổi yêu cầu di chuyển trực tuyến nhưng không đủ điều kiện.",
+ "title": "Điều kiện di chuyển trực tuyến"
+ },
+ "prior-backup": {
+ "description": "Đánh dấu thay đổi bật sao lưu trước khi không thể thực hiện sao lưu.",
+ "title": "Khả năng sao lưu trước"
+ },
+ "require-is-null": {
+ "description": "Đánh dấu = NULL hoặc <> NULL trong vị từ, vốn không bao giờ đúng. Hãy dùng IS NULL hoặc IS NOT NULL.",
+ "title": "So sánh NULL"
+ },
+ "require-primary-key": {
+ "description": "Đánh dấu bảng được thay đổi tạo ra mà không có khóa chính, hoặc khóa chính bị xóa mà không được thêm lại.",
+ "title": "Khóa chính"
+ },
+ "require-where": {
+ "description": "Đánh dấu UPDATE hoặc DELETE không có mệnh đề WHERE.",
+ "title": "Mệnh đề WHERE"
+ },
+ "syntax": {
+ "description": "Đánh dấu các câu lệnh mà công cụ cơ sở dữ liệu không phân tích được. Các quy tắc khác chỉ kiểm tra SQL phân tích được, vì vậy tắt quy tắc này sẽ tắt mọi quy tắc tiêu chuẩn.",
+ "title": "Cú pháp"
+ },
+ "walk-through": {
+ "description": "Đánh dấu các câu lệnh thất bại trên schema đã đồng bộ, chẳng hạn bảng hoặc cột không tồn tại, đối tượng trùng lặp hoặc tham chiếu không hợp lệ.",
+ "title": "Mô phỏng schema"
+ }
+ },
+ "running": "{{on}} trên {{total}} quy tắc đang chạy",
+ "self": "Quy tắc tiêu chuẩn",
+ "syntax-off": "Cú pháp đang tắt nên không quy tắc tiêu chuẩn nào được chạy. Hãy bật Cú pháp để đánh giá các thay đổi."
+ },
"template": {
"bb-sql-review-dev": "Mẫu Cơ bản",
"bb-sql-review-dev-desc": "Bảo vệ cơ bản để bảo vệ cơ sở dữ liệu khỏi những sai sót thường gặp.",
diff --git a/frontend/src/locales/sql-review/zh-CN.json b/frontend/src/locales/sql-review/zh-CN.json
index af41561746..80f96bb449 100644
--- a/frontend/src/locales/sql-review/zh-CN.json
+++ b/frontend/src/locales/sql-review/zh-CN.json
@@ -729,6 +729,66 @@
},
"select-all": "选择全部",
"select-review-rules": "选择 SQL 审核规则",
+ "standard-rules": {
+ "customize": {
+ "description": "关闭时,此项目遵循工作空间的标准规则。",
+ "self": "为此项目自定义",
+ "view-workspace-rules": "查看工作空间规则"
+ },
+ "description": "内置规则,审核每个工单中的 SQL。未自定义规则的项目遵循这里的设置。",
+ "off": "关",
+ "on": "开",
+ "project-description": "内置规则,审核此项目每个工单中的 SQL。",
+ "rule": {
+ "disallow-drop-constraint": {
+ "description": "标记删除 PRIMARY KEY、FOREIGN KEY、UNIQUE 或 CHECK 约束的操作。",
+ "title": "删除约束"
+ },
+ "disallow-drop-object": {
+ "description": "标记 DROP TABLE、COLUMN、SCHEMA 或 DATABASE。",
+ "title": "删除对象"
+ },
+ "disallow-rename": {
+ "description": "标记重命名表或列的操作。",
+ "title": "重命名"
+ },
+ "disallow-truncate": {
+ "description": "标记 TRUNCATE。",
+ "title": "清空表"
+ },
+ "online-migration": {
+ "description": "标记请求在线大表变更但不满足条件的变更。",
+ "title": "在线大表变更可行性"
+ },
+ "prior-backup": {
+ "description": "标记开启了事先备份但无法完成备份的变更。",
+ "title": "事先备份可行性"
+ },
+ "require-is-null": {
+ "description": "标记谓词中的 = NULL 或 <> NULL,它们永远不为真。请改用 IS NULL 或 IS NOT NULL。",
+ "title": "NULL 比较"
+ },
+ "require-primary-key": {
+ "description": "标记变更新建的表没有主键,或删除主键后没有重新添加。",
+ "title": "主键"
+ },
+ "require-where": {
+ "description": "标记没有 WHERE 子句的 UPDATE 或 DELETE。",
+ "title": "WHERE 子句"
+ },
+ "syntax": {
+ "description": "标记数据库引擎无法解析的语句。其他规则只检查能解析的 SQL,因此关闭此项会关闭所有标准规则。",
+ "title": "语法"
+ },
+ "walk-through": {
+ "description": "标记在已同步的 Schema 上执行失败的语句,例如表或列不存在、对象重复或引用无效。",
+ "title": "Schema 模拟执行"
+ }
+ },
+ "running": "{{total}} 条规则中 {{on}} 条生效",
+ "self": "标准规则",
+ "syntax-off": "语法检查已关闭,所有标准规则都不会运行。开启语法检查后才会审核变更。"
+ },
"template": {
"bb-sql-review-dev": "基础模板",
"bb-sql-review-dev-desc": "保证变更可正确地应用到数据库。",
diff --git a/frontend/src/routes/project/ProjectSQLReviewPage.test.tsx b/frontend/src/routes/project/ProjectSQLReviewPage.test.tsx
new file mode 100644
index 0000000000..d2953b2bc7
--- /dev/null
+++ b/frontend/src/routes/project/ProjectSQLReviewPage.test.tsx
@@ -0,0 +1,283 @@
+import { create } from "@bufbuild/protobuf";
+import { act, fireEvent, render, screen } from "@testing-library/react";
+import type { ReactNode } from "react";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import {
+ type Policy,
+ PolicyResourceType,
+ PolicySchema,
+ PolicyType,
+ ReviewRulePolicySchema,
+} from "@/types/proto-es/v1/org_policy_service_pb";
+import { ReviewRuleType } from "@/types/proto-es/v1/review_rule_pb";
+
+const WORKSPACE = "workspaces/ws";
+const PROJECT = "projects/p";
+
+const mocks = vi.hoisted(() => ({
+ canUpdate: { value: true },
+ upsertPolicy: vi.fn(),
+ deletePolicy: vi.fn(),
+ fetchPolicy: vi.fn(),
+ pushNotification: vi.fn(),
+}));
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock("@/hooks/useAppState", () => ({
+ useWorkspaceResourceName: () => "workspaces/ws",
+}));
+
+vi.mock("@/hooks/useProjectByName", () => ({
+ useProjectByName: (name: string) => ({ name }),
+}));
+
+vi.mock("@/hooks/useUnsavedChangesGuard", () => ({
+ useUnsavedChangesGuard: vi.fn(),
+}));
+
+vi.mock("@/utils", () => ({
+ hasProjectPermissionV2: () => mocks.canUpdate.value,
+ hasWorkspacePermissionV2: () => true,
+}));
+
+vi.mock("@/stores", () => ({ pushNotification: mocks.pushNotification }));
+vi.mock("@/stores/modules/v1/common", () => ({ projectNamePrefix: "projects/" }));
+
+vi.mock("@/components/RouterLink", () => ({
+ RouterLink: ({ children }: { children: ReactNode }) => <a href="/">{children}</a>,
+}));
+
+// Mirrors the real store: a fetch of a missing policy caches one with no
+// payload, and a delete drops the cached entry.
+vi.mock("@/stores/app", async () => {
+ const { create: createStore } = await import("zustand");
+ const { create: createMessage } = await import("@bufbuild/protobuf");
+ const { PolicySchema: Schema } = await import(
+ "@/types/proto-es/v1/org_policy_service_pb"
+ );
+ type StorePolicy = import("@/types/proto-es/v1/org_policy_service_pb").Policy;
+ const useAppStore = createStore<{
+ policies: Record<string, StorePolicy>;
+ getPolicyByParentAndType: (params: {
+ parentPath: string;
+ }) => StorePolicy | undefined;
+ getOrFetchPolicyByParentAndType: (params: {
+ parentPath: string;
+ refresh?: boolean;
+ }) => Promise<StorePolicy | undefined>;
+ upsertPolicy: (params: {
+ parentPath: string;
+ policy: Partial<StorePolicy>;
+ }) => Promise<StorePolicy>;
+ deletePolicy: (name: string) => Promise<void>;
+ }>()((set, get) => ({
+ policies: {},
+ getPolicyByParentAndType: ({ parentPath }) => get().policies[parentPath],
+ getOrFetchPolicyByParentAndType: async (params) => {
+ mocks.fetchPolicy(params);
+ if (!get().policies[params.parentPath]) {
+ set((state) => ({
+ policies: {
+ ...state.policies,
+ [params.parentPath]: createMessage(Schema, {
+ name: `${params.parentPath}/policies/review_rule`,
+ }),
+ },
+ }));
+ }
+ return get().policies[params.parentPath];
+ },
+ upsertPolicy: async (params) => {
+ await mocks.upsertPolicy(params);
+ const saved = {
+ ...params.policy,
+ name: `${params.parentPath}/policies/review_rule`,
+ } as StorePolicy;
+ set((state) => ({
+ policies: { ...state.policies, [params.parentPath]: saved },
+ }));
+ return saved;
+ },
+ deletePolicy: async (name) => {
+ await mocks.deletePolicy(name);
+ set((state) => ({
+ policies: Object.fromEntries(
+ Object.entries(state.policies).filter(
+ ([, policy]) => policy.name !== name
+ )
+ ),
+ }));
+ },
+ }));
+ return { useAppStore };
+});
+
+const { useAppStore } = await import("@/stores/app");
+// The mocked store holds only the policy cache.
+const seedPolicies = (policies: Record<string, Policy>) =>
+ (
+ useAppStore as unknown as {
+ setState: (state: { policies: Record<string, Policy> }) => void;
+ }
+ ).setState({ policies });
+const { ProjectSQLReviewPage } = await import("./ProjectSQLReviewPage");
+
+const reviewRulePolicy = (parent: string, rules: ReviewRuleType[]): Policy =>
+ create(PolicySchema, {
+ name: `${parent}/policies/review_rule`,
+ type: PolicyType.REVIEW_RULE,
+ policy: {
+ case: "reviewRulePolicy",
+ value: create(ReviewRulePolicySchema, { rules }),
+ },
+ });
+
+const workspacePolicy = () =>
+ reviewRulePolicy(WORKSPACE, [
+ ReviewRuleType.SYNTAX,
+ ReviewRuleType.REQUIRE_WHERE,
+ ]);
+
+const renderLoaded = async () => {
+ render(<ProjectSQLReviewPage projectId="p" />);
+ return screen.findByRole("switch", {
+ name: "sql-review.standard-rules.customize.self",
+ });
+};
+
+const ruleSwitch = (rule: string) =>
+ screen.getByRole("switch", {
+ name: `sql-review.standard-rules.rule.${rule}.title`,
+ });
+
+const update = () =>
+ act(async () => {
+ fireEvent.click(screen.getByRole("button", { name: "common.update" }));
+ });
+
+describe("ProjectSQLReviewPage", () => {
+ beforeEach(() => {
+ mocks.canUpdate.value = true;
+ mocks.upsertPolicy.mockReset();
+ mocks.deletePolicy.mockReset();
+ mocks.fetchPolicy.mockReset();
+ mocks.pushNotification.mockReset();
+ seedPolicies({ [WORKSPACE]: workspacePolicy() });
+ });
+
+ test("a project without its own policy shows the workspace rules as text", async () => {
+ const customize = await renderLoaded();
+
+ expect(customize).toHaveAttribute("aria-checked", "false");
+ // Only the customize control is a switch; the rules are read-only.
+ expect(screen.getAllByRole("switch")).toHaveLength(1);
+ expect(screen.getAllByText("sql-review.standard-rules.on")).toHaveLength(2);
+ expect(screen.getAllByText("sql-review.standard-rules.off")).toHaveLength(
+ 9
+ );
+ expect(
+ screen.getByText("sql-review.standard-rules.running")
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "common.update" })
+ ).not.toBeInTheDocument();
+ });
+
+ test("customizing starts from the workspace rules and saves a project policy", async () => {
+ const customize = await renderLoaded();
+
+ fireEvent.click(customize);
+ expect(ruleSwitch("require-where")).toHaveAttribute("aria-checked", "true");
+ expect(ruleSwitch("disallow-truncate")).toHaveAttribute(
+ "aria-checked",
+ "false"
+ );
+ fireEvent.click(ruleSwitch("disallow-truncate"));
+ await update();
+
+ expect(mocks.upsertPolicy).toHaveBeenCalledTimes(1);
+ const { parentPath, policy } = mocks.upsertPolicy.mock.calls[0][0];
+ expect(parentPath).toBe(PROJECT);
+ expect(policy.type).toBe(PolicyType.REVIEW_RULE);
+ expect(policy.resourceType).toBe(PolicyResourceType.PROJECT);
+ expect(policy.policy.value.rules).toEqual([
+ ReviewRuleType.SYNTAX,
+ ReviewRuleType.REQUIRE_WHERE,
+ ReviewRuleType.DISALLOW_TRUNCATE,
+ ]);
+ expect(
+ screen.queryByRole("button", { name: "common.update" })
+ ).not.toBeInTheDocument();
+ expect(customize).toHaveAttribute("aria-checked", "true");
+ expect(mocks.pushNotification).toHaveBeenCalledTimes(1);
+ });
+
+ test("turning customization off deletes the project policy", async () => {
+ seedPolicies({
+ [WORKSPACE]: workspacePolicy(),
+ [PROJECT]: reviewRulePolicy(PROJECT, [ReviewRuleType.SYNTAX]),
+ });
+ const customize = await renderLoaded();
+ expect(customize).toHaveAttribute("aria-checked", "true");
+ expect(ruleSwitch("require-where")).toHaveAttribute(
+ "aria-checked",
+ "false"
+ );
+
+ fireEvent.click(customize);
+ // Back to the workspace rules, shown as text again.
+ expect(screen.getAllByRole("switch")).toHaveLength(1);
+ await update();
+
+ expect(mocks.upsertPolicy).not.toHaveBeenCalled();
+ expect(mocks.deletePolicy).toHaveBeenCalledWith(
+ `${PROJECT}/policies/review_rule`
+ );
+ expect(mocks.fetchPolicy).toHaveBeenLastCalledWith({
+ parentPath: PROJECT,
+ policyType: PolicyType.REVIEW_RULE,
+ refresh: true,
+ });
+ expect(customize).toHaveAttribute("aria-checked", "false");
+ });
+
+ test("switching customization on and back off is not a change", async () => {
+ const customize = await renderLoaded();
+
+ fireEvent.click(customize);
+ fireEvent.click(customize);
+ expect(
+ screen.queryByRole("button", { name: "common.update" })
+ ).not.toBeInTheDocument();
+ });
+
+ test("a failed save keeps the draft", async () => {
+ mocks.upsertPolicy.mockRejectedValue(new Error("denied"));
+ const customize = await renderLoaded();
+
+ fireEvent.click(customize);
+ await update();
+
+ expect(
+ screen.getByRole("button", { name: "common.update" })
+ ).toBeInTheDocument();
+ expect(customize).toHaveAttribute("aria-checked", "true");
+ expect(mocks.pushNotification).not.toHaveBeenCalled();
+ });
+
+ test("without bb.policies.update nothing can be switched", async () => {
+ mocks.canUpdate.value = false;
+ seedPolicies({
+ [WORKSPACE]: workspacePolicy(),
+ [PROJECT]: reviewRulePolicy(PROJECT, [ReviewRuleType.SYNTAX]),
+ });
+ await renderLoaded();
+
+ for (const control of screen.getAllByRole("switch")) {
+ expect(control).toHaveAttribute("data-disabled");
+ }
+ });
+});
diff --git a/frontend/src/routes/project/ProjectSQLReviewPage.tsx b/frontend/src/routes/project/ProjectSQLReviewPage.tsx
new file mode 100644
index 0000000000..22dc39f02e
--- /dev/null
+++ b/frontend/src/routes/project/ProjectSQLReviewPage.tsx
@@ -0,0 +1,255 @@
+import { create } from "@bufbuild/protobuf";
+import { useCallback, useEffect, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { WORKSPACE_ROUTE_SQL_REVIEW } from "@/app/router/handles";
+import { ProjectPageLayout } from "@/components/ProjectPageLayout";
+import { RouterLink } from "@/components/RouterLink";
+import { StandardRuleSwitches } from "@/components/sql-review/StandardRuleSwitches";
+import { SwitchRow } from "@/components/sql-review/SwitchRow";
+import {
+ reviewRulesOfPolicy,
+ STANDARD_RULE_TYPES,
+ sameStandardRules,
+} from "@/components/sql-review/standardRules";
+import { Button } from "@/components/ui/button";
+import { StickyActionFooter } from "@/components/ui/sticky-action-footer";
+import { useWorkspaceResourceName } from "@/hooks/useAppState";
+import { useProjectByName } from "@/hooks/useProjectByName";
+import { useUnsavedChangesGuard } from "@/hooks/useUnsavedChangesGuard";
+import { cn } from "@/lib/utils";
+import { pushNotification } from "@/stores";
+import { useAppStore } from "@/stores/app";
+import { projectNamePrefix } from "@/stores/modules/v1/common";
+import {
+ PolicyResourceType,
+ PolicyType,
+ ReviewRulePolicySchema,
+} from "@/types/proto-es/v1/org_policy_service_pb";
+import type { ReviewRuleType } from "@/types/proto-es/v1/review_rule_pb";
+import { hasProjectPermissionV2, hasWorkspacePermissionV2 } from "@/utils";
+
+interface ProjectStandardRules {
+ // False until both the project and the workspace policy have been read.
+ loaded: boolean;
+ // Whether the project has rules of its own; otherwise it follows the
+ // workspace.
+ customized: boolean;
+ setCustomized: (customized: boolean) => void;
+ // The rules in force: the project's own while customized, else the
+ // workspace's. Undefined when the workspace policy could not be read.
+ rules: ReviewRuleType[] | undefined;
+ setRules: (rules: ReviewRuleType[]) => void;
+ isDirty: boolean;
+ saving: boolean;
+ revert: () => void;
+ save: () => Promise<void>;
+}
+
+interface Draft {
+ customized: boolean;
+ rules: ReviewRuleType[];
+}
+
+export function useProjectStandardRules(
+ projectName: string
+): ProjectStandardRules {
+ const { t } = useTranslation();
+ const workspace = useWorkspaceResourceName();
+ const projectPolicy = useAppStore((state) =>
+ state.getPolicyByParentAndType({
+ parentPath: projectName,
+ policyType: PolicyType.REVIEW_RULE,
+ })
+ );
+ const workspacePolicy = useAppStore((state) =>
+ state.getPolicyByParentAndType({
+ parentPath: workspace,
+ policyType: PolicyType.REVIEW_RULE,
+ })
+ );
+ const [loaded, setLoaded] = useState(false);
+ useEffect(() => {
+ if (!workspace) return;
+ setLoaded(false);
+ const store = useAppStore.getState();
+ void Promise.all([
+ store.getOrFetchPolicyByParentAndType({
+ parentPath: projectName,
+ policyType: PolicyType.REVIEW_RULE,
+ }),
+ store.getOrFetchPolicyByParentAndType({
+ parentPath: workspace,
+ policyType: PolicyType.REVIEW_RULE,
+ }),
+ ]).then(() => setLoaded(true));
+ }, [projectName, workspace]);
+
+ // A project without its own policy reads as NotFound, which the store
+ // caches as a policy with no payload.
+ const storedRules = reviewRulesOfPolicy(projectPolicy);
+ const workspaceRules = reviewRulesOfPolicy(workspacePolicy);
+ const storedCustomized = storedRules !== undefined;
+
+ const [draft, setDraft] = useState<Draft>();
+ const [saving, setSaving] = useState(false);
+ const revert = useCallback(() => setDraft(undefined), []);
+ const customized = draft?.customized ?? storedCustomized;
+ const ownRules = draft?.rules ?? storedRules;
+ const isDirty =
+ draft !== undefined &&
+ (draft.customized !== storedCustomized ||
+ (draft.customized && !sameStandardRules(draft.rules, storedRules ?? [])));
+
+ const setCustomized = (next: boolean) => {
+ setDraft({
+ customized: next,
+ rules: ownRules ?? workspaceRules ?? [...STANDARD_RULE_TYPES],
+ });
+ };
+
+ const save = async () => {
+ if (!draft || !isDirty) return;
+ setSaving(true);
+ try {
+ const store = useAppStore.getState();
+ if (draft.customized) {
+ await store.upsertPolicy({
+ parentPath: projectName,
+ policy: {
+ type: PolicyType.REVIEW_RULE,
+ resourceType: PolicyResourceType.PROJECT,
+ policy: {
+ case: "reviewRulePolicy",
+ value: create(ReviewRulePolicySchema, { rules: draft.rules }),
+ },
+ },
+ });
+ } else if (projectPolicy) {
+ await store.deletePolicy(projectPolicy.name);
+ await store.getOrFetchPolicyByParentAndType({
+ parentPath: projectName,
+ policyType: PolicyType.REVIEW_RULE,
+ refresh: true,
+ });
+ }
+ setDraft(undefined);
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.updated"),
+ });
+ } catch {
+ // The response middleware reports the failure; the draft stays for a
+ // retry.
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ return {
+ loaded,
+ customized,
+ setCustomized,
+ rules: customized ? ownRules : workspaceRules,
+ setRules: (rules) => setDraft({ customized: true, rules }),
+ isDirty,
+ saving,
+ revert,
+ save,
+ };
+}
+
+// The rules read as one centered column, and the footer lines its actions up
+// with it.
+const STANDARD_RULES_COLUMN = "mx-auto w-full max-w-3xl";
+
+export function ProjectSQLReviewPage({ projectId }: { projectId: string }) {
+ const { t } = useTranslation();
+ const projectName = `${projectNamePrefix}${projectId}`;
+ const project = useProjectByName(projectName);
+ const standardRules = useProjectStandardRules(projectName);
+ useUnsavedChangesGuard(standardRules.isDirty);
+
+ const allowEdit =
+ hasProjectPermissionV2(project, "bb.policies.update") &&
+ !standardRules.saving;
+ const canViewWorkspaceRules =
+ hasWorkspacePermissionV2("bb.reviewConfigs.list") &&
+ hasWorkspacePermissionV2("bb.policies.get");
+
+ return (
+ <ProjectPageLayout>
+ <div className={cn(STANDARD_RULES_COLUMN, "flex flex-col gap-y-6 pt-4")}>
+ <div className="flex flex-col gap-y-2">
+ <h1 className="text-2xl font-bold text-main">
+ {t("sql-review.standard-rules.self")}
+ </h1>
+ <p className="text-sm text-control-light">
+ {t("sql-review.standard-rules.project-description")}
+ </p>
+ </div>
+ {standardRules.loaded && (
+ <>
+ <SwitchRow
+ className="rounded-sm border border-block-border px-4 py-3"
+ title={t("sql-review.standard-rules.customize.self")}
+ description={
+ <>
+ {t("sql-review.standard-rules.customize.description")}
+ {canViewWorkspaceRules && (
+ <>
+ {" "}
+ <RouterLink
+ to={{ name: WORKSPACE_ROUTE_SQL_REVIEW }}
+ className="text-accent hover:underline"
+ >
+ {t(
+ "sql-review.standard-rules.customize.view-workspace-rules"
+ )}
+ </RouterLink>
+ </>
+ )}
+ </>
+ }
+ checked={standardRules.customized}
+ onCheckedChange={standardRules.setCustomized}
+ disabled={!allowEdit}
+ />
+ {standardRules.rules && (
+ <StandardRuleSwitches
+ rules={standardRules.rules}
+ onChange={standardRules.setRules}
+ disabled={!allowEdit}
+ readOnly={!standardRules.customized}
+ />
+ )}
+ </>
+ )}
+ </div>
+
+ {standardRules.isDirty && (
+ <StickyActionFooter
+ contentPadding={false}
+ contentClassName={STANDARD_RULES_COLUMN}
+ left={
+ <Button
+ appearance="outline"
+ disabled={standardRules.saving}
+ onClick={standardRules.revert}
+ >
+ {t("common.cancel")}
+ </Button>
+ }
+ right={
+ <Button
+ disabled={standardRules.saving}
+ onClick={() => void standardRules.save()}
+ >
+ {t("common.update")}
+ </Button>
+ }
+ />
+ )}
+ </ProjectPageLayout>
+ );
+}
diff --git a/frontend/src/routes/project/ProjectSettingsPage.tsx b/frontend/src/routes/project/ProjectSettingsPage.tsx
index a2d52a8e03..64c8643056 100644
--- a/frontend/src/routes/project/ProjectSettingsPage.tsx
+++ b/frontend/src/routes/project/ProjectSettingsPage.tsx
@@ -67,6 +67,7 @@ import {
hexToColor,
sqlReviewPolicySlug,
} from "@/utils";
+import { sqlReviewV2Enabled } from "@/utils/featureGates";
// ---------------------------------------------------------------------------
// ApprovalFlowIndicator
@@ -147,6 +148,8 @@ export function ProjectSettingsPage() {
void projectsByName;
const project = useProjectByName(projectName);
const isDefault = isDefaultProject(projectName);
+ // The v1 review policy settings go away with SQL Review V2.
+ const sqlReviewV2 = sqlReviewV2Enabled();
const hasPermission = useCallback(
(permission: Permission) =>
@@ -266,7 +269,9 @@ export function ProjectSettingsPage() {
useEffect(() => {
if (lastFetchedProject.current === projectName) return;
lastFetchedProject.current = projectName;
- useSQLReviewStore.getState().fetchReviewPolicyList();
+ if (!sqlReviewV2Enabled()) {
+ useSQLReviewStore.getState().fetchReviewPolicyList();
+ }
useAppStore.getState().getOrFetchPolicyByParentAndType({
parentPath: projectName,
policyType: PolicyType.DATA_QUERY,
@@ -737,62 +742,63 @@ export function ProjectSettingsPage() {
{canGetPolicies && (
<>
{/* SQL Review */}
- {hasWorkspacePermissionV2("bb.reviewConfigs.get") && (
- <FormField title={t("sql-review.title")}>
- <div>
- {pendingReviewPolicy ? (
- <FormControlRow>
- <Switch
- checked={enforceReview}
- onCheckedChange={setEnforceReview}
+ {!sqlReviewV2 &&
+ hasWorkspacePermissionV2("bb.reviewConfigs.get") && (
+ <FormField title={t("sql-review.title")}>
+ <div>
+ {pendingReviewPolicy ? (
+ <FormControlRow>
+ <Switch
+ checked={enforceReview}
+ onCheckedChange={setEnforceReview}
+ disabled={
+ !hasWorkspacePermissionV2(
+ "bb.reviewConfigs.update"
+ )
+ }
+ />
+ <span
+ className="text-sm font-medium text-accent cursor-pointer hover:underline"
+ onClick={() =>
+ router.push({
+ name: WORKSPACE_ROUTE_SQL_REVIEW_DETAIL,
+ params: {
+ sqlReviewPolicySlug:
+ sqlReviewPolicySlug(pendingReviewPolicy),
+ },
+ })
+ }
+ >
+ {pendingReviewPolicy.name}
+ </span>
+ {canUpdatePolicies && (
+ <Button
+ appearance="secondary"
+ size="sm"
+ onClick={() => {
+ setPendingReviewPolicy(undefined);
+ setEnforceReview(false);
+ }}
+ >
+ <X className="size-4" />
+ </Button>
+ )}
+ </FormControlRow>
+ ) : (
+ <Button
+ appearance="outline"
disabled={
- !hasWorkspacePermissionV2(
- "bb.reviewConfigs.update"
- )
- }
- />
- <span
- className="text-sm font-medium text-accent cursor-pointer hover:underline"
- onClick={() =>
- router.push({
- name: WORKSPACE_ROUTE_SQL_REVIEW_DETAIL,
- params: {
- sqlReviewPolicySlug:
- sqlReviewPolicySlug(pendingReviewPolicy),
- },
- })
+ !canUpdatePolicies ||
+ !hasWorkspacePermissionV2("bb.reviewConfigs.list")
}
+ onClick={() => setShowReviewDialog(true)}
>
- {pendingReviewPolicy.name}
- </span>
- {canUpdatePolicies && (
- <Button
- appearance="secondary"
- size="sm"
- onClick={() => {
- setPendingReviewPolicy(undefined);
- setEnforceReview(false);
- }}
- >
- <X className="size-4" />
- </Button>
- )}
- </FormControlRow>
- ) : (
- <Button
- appearance="outline"
- disabled={
- !canUpdatePolicies ||
- !hasWorkspacePermissionV2("bb.reviewConfigs.list")
- }
- onClick={() => setShowReviewDialog(true)}
- >
- {t("sql-review.configure-policy")}
- </Button>
- )}
- </div>
- </FormField>
- )}
+ {t("sql-review.configure-policy")}
+ </Button>
+ )}
+ </div>
+ </FormField>
+ )}
{/* Maximum SQL Result Rows */}
<FormField
@@ -975,17 +981,19 @@ export function ProjectSettingsPage() {
"project.settings.issue-related.enforce-issue-title.description"
)}
/>
- <ToggleRow
- checked={enforceSqlReview}
- onCheckedChange={setEnforceSqlReview}
- disabled={!canUpdateProject}
- label={t(
- "project.settings.issue-related.enforce-sql-review.self"
- )}
- description={t(
- "project.settings.issue-related.enforce-sql-review.description"
- )}
- />
+ {!sqlReviewV2 && (
+ <ToggleRow
+ checked={enforceSqlReview}
+ onCheckedChange={setEnforceSqlReview}
+ disabled={!canUpdateProject}
+ label={t(
+ "project.settings.issue-related.enforce-sql-review.self"
+ )}
+ description={t(
+ "project.settings.issue-related.enforce-sql-review.description"
+ )}
+ />
+ )}
<FormField
title={t(
"project.settings.issue-related.approval-permissions.self"
diff --git a/frontend/src/routes/workspace/EnvironmentsPage.tsx b/frontend/src/routes/workspace/EnvironmentsPage.tsx
index a26bfb40a0..ba61d17b86 100644
--- a/frontend/src/routes/workspace/EnvironmentsPage.tsx
+++ b/frontend/src/routes/workspace/EnvironmentsPage.tsx
@@ -95,6 +95,7 @@ import {
import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
import type { Environment } from "@/types/v1/environment";
import { hasWorkspacePermissionV2, sqlReviewPolicySlug } from "@/utils";
+import { sqlReviewV2Enabled } from "@/utils/featureGates";
import {
getEnvironmentListKey,
resolveSelectedEnvironmentId,
@@ -820,12 +821,14 @@ function EnvironmentDetail({
</FormField>
)}
- {/* SQL Review section */}
- <SQLReviewSection
- ref={sqlReviewRef}
- environmentId={environment.id}
- onDirtyChange={setSqlReviewDirty}
- />
+ {/* The v1 review policy goes away with SQL Review V2. */}
+ {!sqlReviewV2Enabled() && (
+ <SQLReviewSection
+ ref={sqlReviewRef}
+ environmentId={environment.id}
+ onDirtyChange={setSqlReviewDirty}
+ />
+ )}
{/* Delete section */}
{allowDelete && (
diff --git a/frontend/src/routes/workspace/SQLReviewPage.test.tsx b/frontend/src/routes/workspace/SQLReviewPage.test.tsx
new file mode 100644
index 0000000000..07e1ed0127
--- /dev/null
+++ b/frontend/src/routes/workspace/SQLReviewPage.test.tsx
@@ -0,0 +1,84 @@
+import { render, screen } from "@testing-library/react";
+import type { ReactNode } from "react";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ sqlReviewV2: { value: true },
+ fetchReviewPolicyList: vi.fn(),
+}));
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock("@/utils/featureGates", () => ({
+ sqlReviewV2Enabled: () => mocks.sqlReviewV2.value,
+}));
+
+vi.mock("./SQLReviewStandardRulesSection", () => ({
+ SQLReviewStandardRulesSection: () => <div>standard-rules-section</div>,
+ useWorkspaceStandardRules: () => ({
+ rules: [],
+ setRules: vi.fn(),
+ isDirty: false,
+ saving: false,
+ revert: vi.fn(),
+ save: vi.fn(),
+ }),
+}));
+
+vi.mock("@/stores/sqlReview", () => {
+ const useSQLReviewStore = () => ({ reviewPolicyList: [] });
+ useSQLReviewStore.getState = () => ({
+ fetchReviewPolicyList: mocks.fetchReviewPolicyList,
+ });
+ return { useSQLReviewStore };
+});
+
+vi.mock("@/app/router", () => ({ router: { push: vi.fn() } }));
+vi.mock("@/components/sql-review/ResourceLink", () => ({
+ ResourceLink: ({ resource }: { resource: string }) => <span>{resource}</span>,
+}));
+vi.mock("@/components/LearnMoreLink", () => ({
+ LearnMoreLink: ({ children }: { children?: ReactNode }) => (
+ <a href="/">{children}</a>
+ ),
+}));
+vi.mock("@/hooks/useUnsavedChangesGuard", () => ({
+ useUnsavedChangesGuard: vi.fn(),
+}));
+vi.mock("@/stores", () => ({ pushNotification: vi.fn() }));
+vi.mock("@/utils", () => ({
+ hasWorkspacePermissionV2: () => true,
+ sqlReviewPolicySlug: () => "slug",
+}));
+
+const { SQLReviewPage } = await import("./SQLReviewPage");
+
+describe("SQLReviewPage", () => {
+ beforeEach(() => {
+ mocks.fetchReviewPolicyList.mockReset();
+ });
+
+ test("shows only the standard rules under SQL Review V2", () => {
+ mocks.sqlReviewV2.value = true;
+ render(<SQLReviewPage />);
+
+ expect(screen.getByText("standard-rules-section")).toBeInTheDocument();
+ expect(screen.queryByText("sql-review.description")).not.toBeInTheDocument();
+ expect(screen.queryByText("common.create")).not.toBeInTheDocument();
+ expect(mocks.fetchReviewPolicyList).not.toHaveBeenCalled();
+ });
+
+ test("keeps the v1 review policies without SQL Review V2", () => {
+ mocks.sqlReviewV2.value = false;
+ render(<SQLReviewPage />);
+
+ expect(
+ screen.queryByText("standard-rules-section")
+ ).not.toBeInTheDocument();
+ expect(screen.getByText("sql-review.description")).toBeInTheDocument();
+ expect(screen.getAllByText("common.create").length).toBeGreaterThan(0);
+ expect(mocks.fetchReviewPolicyList).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/frontend/src/routes/workspace/SQLReviewPage.tsx b/frontend/src/routes/workspace/SQLReviewPage.tsx
index ecbea54fbb..35c51132fb 100644
--- a/frontend/src/routes/workspace/SQLReviewPage.tsx
+++ b/frontend/src/routes/workspace/SQLReviewPage.tsx
@@ -12,6 +12,7 @@ import { ResourceLink } from "@/components/sql-review/ResourceLink";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { SearchInput } from "@/components/ui/search-input";
+import { StickyActionFooter } from "@/components/ui/sticky-action-footer";
import { Switch } from "@/components/ui/switch";
import {
Table,
@@ -27,10 +28,16 @@ import {
WorkspacePageLayout,
WorkspacePageToolbar,
} from "@/components/WorkspacePageLayout";
+import { useUnsavedChangesGuard } from "@/hooks/useUnsavedChangesGuard";
import { pushNotification } from "@/stores";
import { useSQLReviewStore } from "@/stores/sqlReview";
import type { SQLReviewPolicy } from "@/types";
import { hasWorkspacePermissionV2, sqlReviewPolicySlug } from "@/utils";
+import { sqlReviewV2Enabled } from "@/utils/featureGates";
+import {
+ SQLReviewStandardRulesSection,
+ useWorkspaceStandardRules,
+} from "./SQLReviewStandardRulesSection";
// ============================================================
// PolicyTable
@@ -245,14 +252,23 @@ function PolicyTable({
// SQLReviewPage (exported)
// ============================================================
+// The standard rules read as one centered column, and the footer lines its
+// actions up with it.
+const STANDARD_RULES_COLUMN = "mx-auto w-full max-w-3xl";
+
export function SQLReviewPage() {
const { t } = useTranslation();
const sqlReviewStore = useSQLReviewStore();
const [searchText, setSearchText] = useState("");
+ // With SQL Review V2 the standard rules replace the v1 review policies.
+ const sqlReviewV2 = sqlReviewV2Enabled();
+ const standardRules = useWorkspaceStandardRules(sqlReviewV2);
+ useUnsavedChangesGuard(standardRules.isDirty);
useEffect(() => {
+ if (sqlReviewV2) return;
useSQLReviewStore.getState().fetchReviewPolicyList();
- }, []);
+ }, [sqlReviewV2]);
const policyList = sqlReviewStore.reviewPolicyList;
@@ -284,50 +300,82 @@ export function SQLReviewPage() {
return (
<WorkspacePageLayout className="gap-y-4">
- <WorkspacePageInfo
- description={
- <>
- {t("sql-review.description")}{" "}
- <LearnMoreLink
- href="https://docs.bytebase.com/sql-review/review-rules?source=console"
- className="text-accent"
+ {sqlReviewV2 ? (
+ <div className={STANDARD_RULES_COLUMN}>
+ <SQLReviewStandardRulesSection standardRules={standardRules} />
+ </div>
+ ) : (
+ <>
+ <WorkspacePageInfo
+ description={
+ <>
+ {t("sql-review.description")}{" "}
+ <LearnMoreLink
+ href="https://docs.bytebase.com/sql-review/review-rules?source=console"
+ className="text-accent"
+ />
+ </>
+ }
+ />
+
+ <WorkspacePageToolbar align="end">
+ <SearchInput
+ value={searchText}
+ onChange={(e) => setSearchText(e.target.value)}
+ placeholder={t("common.filter-by-name")}
+ autoFocus
+ wrapperClassName="max-w-full"
/>
- </>
- }
- />
+ {hasCreatePermission && (
+ <Button onClick={navigateToCreate}>
+ <Plus className="w-4 h-4 mr-1" />
+ {t("common.create")}
+ </Button>
+ )}
+ </WorkspacePageToolbar>
- <WorkspacePageToolbar align="end">
- <SearchInput
- value={searchText}
- onChange={(e) => setSearchText(e.target.value)}
- placeholder={t("common.filter-by-name")}
- autoFocus
- wrapperClassName="max-w-full"
- />
- {hasCreatePermission && (
- <Button onClick={navigateToCreate}>
- <Plus className="w-4 h-4 mr-1" />
- {t("common.create")}
- </Button>
- )}
- </WorkspacePageToolbar>
+ {policyList.length > 0 ? (
+ <PolicyTable
+ policies={filteredList}
+ searchText={searchText}
+ onDelete={handleDelete}
+ />
+ ) : (
+ <div className="py-12 border rounded-sm flex flex-col items-center justify-center gap-y-3 text-control-light">
+ <span>{t("common.no-data")}</span>
+ {hasCreatePermission && (
+ <Button size="sm" onClick={navigateToCreate}>
+ <Plus className="w-4 h-4 mr-1" />
+ {t("common.create")}
+ </Button>
+ )}
+ </div>
+ )}
+ </>
+ )}
- {policyList.length > 0 ? (
- <PolicyTable
- policies={filteredList}
- searchText={searchText}
- onDelete={handleDelete}
- />
- ) : (
- <div className="py-12 border rounded-sm flex flex-col items-center justify-center gap-y-3 text-control-light">
- <span>{t("common.no-data")}</span>
- {hasCreatePermission && (
- <Button size="sm" onClick={navigateToCreate}>
- <Plus className="w-4 h-4 mr-1" />
- {t("common.create")}
+ {standardRules.isDirty && (
+ <StickyActionFooter
+ contentPadding={false}
+ contentClassName={STANDARD_RULES_COLUMN}
+ left={
+ <Button
+ appearance="outline"
+ disabled={standardRules.saving}
+ onClick={standardRules.revert}
+ >
+ {t("common.cancel")}
</Button>
- )}
- </div>
+ }
+ right={
+ <Button
+ disabled={standardRules.saving}
+ onClick={() => void standardRules.save()}
+ >
+ {t("common.update")}
+ </Button>
+ }
+ />
)}
</WorkspacePageLayout>
);
diff --git a/frontend/src/routes/workspace/SQLReviewStandardRulesSection.test.tsx b/frontend/src/routes/workspace/SQLReviewStandardRulesSection.test.tsx
new file mode 100644
index 0000000000..b4a74a7a24
--- /dev/null
+++ b/frontend/src/routes/workspace/SQLReviewStandardRulesSection.test.tsx
@@ -0,0 +1,182 @@
+import { create } from "@bufbuild/protobuf";
+import { act, fireEvent, render, screen } from "@testing-library/react";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import { STANDARD_RULE_TYPES } from "@/components/sql-review/standardRules";
+import {
+ type Policy,
+ PolicyResourceType,
+ PolicySchema,
+ PolicyType,
+ ReviewRulePolicySchema,
+} from "@/types/proto-es/v1/org_policy_service_pb";
+import { ReviewRuleType } from "@/types/proto-es/v1/review_rule_pb";
+
+const WORKSPACE = "workspaces/ws";
+
+const mocks = vi.hoisted(() => ({
+ canUpdate: { value: true },
+ upsertPolicy: vi.fn(),
+ pushNotification: vi.fn(),
+}));
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock("@/hooks/useAppState", () => ({
+ useWorkspaceResourceName: () => "workspaces/ws",
+}));
+
+vi.mock("@/utils", () => ({
+ hasWorkspacePermissionV2: (permission: string) =>
+ permission === "bb.policies.update" ? mocks.canUpdate.value : true,
+}));
+
+vi.mock("@/stores", () => ({ pushNotification: mocks.pushNotification }));
+
+vi.mock("@/stores/app", async () => {
+ const { create: createStore } = await import("zustand");
+ type StorePolicy = import("@/types/proto-es/v1/org_policy_service_pb").Policy;
+ const useAppStore = createStore<{
+ policies: Record<string, StorePolicy>;
+ getPolicyByParentAndType: (params: {
+ parentPath: string;
+ }) => StorePolicy | undefined;
+ getOrFetchPolicyByParentAndType: (params: {
+ parentPath: string;
+ }) => Promise<StorePolicy | undefined>;
+ upsertPolicy: (params: {
+ parentPath: string;
+ policy: Partial<StorePolicy>;
+ }) => Promise<StorePolicy>;
+ }>()((set, get) => ({
+ policies: {},
+ getPolicyByParentAndType: ({ parentPath }) => get().policies[parentPath],
+ getOrFetchPolicyByParentAndType: async ({ parentPath }) =>
+ get().policies[parentPath],
+ upsertPolicy: async (params) => {
+ await mocks.upsertPolicy(params);
+ const saved = params.policy as StorePolicy;
+ set((state) => ({
+ policies: { ...state.policies, [params.parentPath]: saved },
+ }));
+ return saved;
+ },
+ }));
+ return { useAppStore };
+});
+
+const { useAppStore } = await import("@/stores/app");
+// The mocked store holds only the policy cache.
+const seedPolicies = (policies: Record<string, Policy>) =>
+ (
+ useAppStore as unknown as {
+ setState: (state: { policies: Record<string, Policy> }) => void;
+ }
+ ).setState({ policies });
+const { SQLReviewStandardRulesSection, useWorkspaceStandardRules } =
+ await import("./SQLReviewStandardRulesSection");
+
+const reviewRulePolicy = (rules: ReviewRuleType[]): Policy =>
+ create(PolicySchema, {
+ name: `${WORKSPACE}/policies/review_rule`,
+ type: PolicyType.REVIEW_RULE,
+ policy: {
+ case: "reviewRulePolicy",
+ value: create(ReviewRulePolicySchema, { rules }),
+ },
+ });
+
+function Harness() {
+ const standardRules = useWorkspaceStandardRules(true);
+ return (
+ <>
+ <SQLReviewStandardRulesSection standardRules={standardRules} />
+ <output data-testid="dirty">{String(standardRules.isDirty)}</output>
+ <button type="button" onClick={() => void standardRules.save()}>
+ save
+ </button>
+ <button type="button" onClick={standardRules.revert}>
+ revert
+ </button>
+ </>
+ );
+}
+
+const ruleSwitch = (rule: string) =>
+ screen.getByRole("switch", {
+ name: `sql-review.standard-rules.rule.${rule}.title`,
+ });
+
+describe("SQLReviewStandardRulesSection", () => {
+ beforeEach(() => {
+ mocks.canUpdate.value = true;
+ mocks.upsertPolicy.mockReset();
+ mocks.pushNotification.mockReset();
+ seedPolicies({ [WORKSPACE]: reviewRulePolicy([...STANDARD_RULE_TYPES]) });
+ });
+
+ test("saves the edited rules as the workspace policy", async () => {
+ render(<Harness />);
+ expect(screen.getByTestId("dirty")).toHaveTextContent("false");
+
+ fireEvent.click(ruleSwitch("disallow-truncate"));
+ expect(screen.getByTestId("dirty")).toHaveTextContent("true");
+
+ await act(async () => {
+ fireEvent.click(screen.getByText("save"));
+ });
+
+ expect(mocks.upsertPolicy).toHaveBeenCalledTimes(1);
+ const { parentPath, policy } = mocks.upsertPolicy.mock.calls[0][0];
+ expect(parentPath).toBe(WORKSPACE);
+ expect(policy.type).toBe(PolicyType.REVIEW_RULE);
+ expect(policy.resourceType).toBe(PolicyResourceType.WORKSPACE);
+ expect(policy.policy.value.rules).toEqual(
+ STANDARD_RULE_TYPES.filter(
+ (rule) => rule !== ReviewRuleType.DISALLOW_TRUNCATE
+ )
+ );
+ expect(screen.getByTestId("dirty")).toHaveTextContent("false");
+ expect(ruleSwitch("disallow-truncate")).toHaveAttribute(
+ "aria-checked",
+ "false"
+ );
+ });
+
+ test("switching a rule back is not a change, and revert drops the draft", () => {
+ render(<Harness />);
+
+ fireEvent.click(ruleSwitch("require-where"));
+ fireEvent.click(ruleSwitch("require-where"));
+ expect(screen.getByTestId("dirty")).toHaveTextContent("false");
+
+ fireEvent.click(ruleSwitch("syntax"));
+ expect(screen.getByTestId("dirty")).toHaveTextContent("true");
+ fireEvent.click(screen.getByText("revert"));
+ expect(screen.getByTestId("dirty")).toHaveTextContent("false");
+ expect(ruleSwitch("syntax")).toHaveAttribute("aria-checked", "true");
+ });
+
+ test("keeps the draft when the save fails", async () => {
+ mocks.upsertPolicy.mockRejectedValue(new Error("denied"));
+ render(<Harness />);
+
+ fireEvent.click(ruleSwitch("require-where"));
+ await act(async () => {
+ fireEvent.click(screen.getByText("save"));
+ });
+
+ expect(screen.getByTestId("dirty")).toHaveTextContent("true");
+ expect(mocks.pushNotification).not.toHaveBeenCalled();
+ });
+
+ test("locks the switches without bb.policies.update", () => {
+ mocks.canUpdate.value = false;
+ render(<Harness />);
+
+ for (const control of screen.getAllByRole("switch")) {
+ expect(control).toHaveAttribute("data-disabled");
+ }
+ });
+});
diff --git a/frontend/src/routes/workspace/SQLReviewStandardRulesSection.tsx b/frontend/src/routes/workspace/SQLReviewStandardRulesSection.tsx
new file mode 100644
index 0000000000..4166555c9c
--- /dev/null
+++ b/frontend/src/routes/workspace/SQLReviewStandardRulesSection.tsx
@@ -0,0 +1,125 @@
+import { create } from "@bufbuild/protobuf";
+import { useEffect, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { StandardRuleSwitches } from "@/components/sql-review/StandardRuleSwitches";
+import {
+ reviewRulesOfPolicy,
+ sameStandardRules,
+} from "@/components/sql-review/standardRules";
+import { useWorkspaceResourceName } from "@/hooks/useAppState";
+import { pushNotification } from "@/stores";
+import { useAppStore } from "@/stores/app";
+import {
+ PolicyResourceType,
+ PolicyType,
+ ReviewRulePolicySchema,
+} from "@/types/proto-es/v1/org_policy_service_pb";
+import type { ReviewRuleType } from "@/types/proto-es/v1/review_rule_pb";
+import { hasWorkspacePermissionV2 } from "@/utils";
+
+export interface WorkspaceStandardRules {
+ // Undefined until the workspace policy loads.
+ rules: ReviewRuleType[] | undefined;
+ setRules: (rules: ReviewRuleType[]) => void;
+ isDirty: boolean;
+ saving: boolean;
+ revert: () => void;
+ save: () => Promise<void>;
+}
+
+// The page owns the draft so its sticky footer can sit at the end of the page,
+// below the SQL review policy list.
+export function useWorkspaceStandardRules(
+ enabled: boolean
+): WorkspaceStandardRules {
+ const { t } = useTranslation();
+ const workspace = useWorkspaceResourceName();
+ const policy = useAppStore((state) =>
+ state.getPolicyByParentAndType({
+ parentPath: workspace,
+ policyType: PolicyType.REVIEW_RULE,
+ })
+ );
+ useEffect(() => {
+ if (!enabled || !workspace) return;
+ void useAppStore.getState().getOrFetchPolicyByParentAndType({
+ parentPath: workspace,
+ policyType: PolicyType.REVIEW_RULE,
+ });
+ }, [enabled, workspace]);
+
+ const stored = reviewRulesOfPolicy(policy);
+ const [draft, setDraft] = useState<ReviewRuleType[]>();
+ const [saving, setSaving] = useState(false);
+ const isDirty =
+ draft !== undefined &&
+ stored !== undefined &&
+ !sameStandardRules(draft, stored);
+
+ const save = async () => {
+ if (!draft) return;
+ setSaving(true);
+ try {
+ await useAppStore.getState().upsertPolicy({
+ parentPath: workspace,
+ policy: {
+ type: PolicyType.REVIEW_RULE,
+ resourceType: PolicyResourceType.WORKSPACE,
+ policy: {
+ case: "reviewRulePolicy",
+ value: create(ReviewRulePolicySchema, { rules: draft }),
+ },
+ },
+ });
+ setDraft(undefined);
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.updated"),
+ });
+ } catch {
+ // The response middleware reports the failure; the draft stays for a
+ // retry.
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ return {
+ rules: draft ?? stored,
+ setRules: setDraft,
+ isDirty,
+ saving,
+ revert: () => setDraft(undefined),
+ save,
+ };
+}
+
+export function SQLReviewStandardRulesSection({
+ standardRules,
+}: {
+ standardRules: WorkspaceStandardRules;
+}) {
+ const { t } = useTranslation();
+ const canUpdate = hasWorkspacePermissionV2("bb.policies.update");
+
+ return (
+ <section className="flex flex-col gap-y-6 pt-8">
+ <div className="flex flex-col gap-y-2">
+ <h1 className="text-2xl font-bold text-main">
+ {t("sql-review.standard-rules.self")}
+ </h1>
+ <p className="text-sm text-control-light">
+ {t("sql-review.standard-rules.description")}
+ </p>
+ </div>
+ {standardRules.rules && (
+ <StandardRuleSwitches
+ rules={standardRules.rules}
+ onChange={standardRules.setRules}
+ disabled={!canUpdate || standardRules.saving}
+ />
+ )}
+ </section>
+ );
+}
diff --git a/frontend/src/stores/app/policy.test.ts b/frontend/src/stores/app/policy.test.ts
new file mode 100644
index 0000000000..63f262ecb2
--- /dev/null
+++ b/frontend/src/stores/app/policy.test.ts
@@ -0,0 +1,78 @@
+// @vitest-environment node
+import { create } from "@bufbuild/protobuf";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import {
+ PolicyResourceType,
+ PolicySchema,
+ PolicyType,
+ ReviewRulePolicySchema,
+ type UpdatePolicyRequest,
+} from "@/types/proto-es/v1/org_policy_service_pb";
+import { ReviewRuleType } from "@/types/proto-es/v1/review_rule_pb";
+import { createPolicySlice } from "./policy";
+
+const mocks = vi.hoisted(() => ({
+ updatePolicy: vi.fn(),
+}));
+
+vi.mock("@/api", () => ({
+ orgPolicyServiceClientConnect: {
+ updatePolicy: mocks.updatePolicy,
+ },
+}));
+
+const createStore = () => {
+ const state: Record<string, unknown> = {};
+ const set = (updater: unknown) => {
+ const patch =
+ typeof updater === "function"
+ ? (updater as (value: typeof state) => object)(state)
+ : updater;
+ Object.assign(state, patch);
+ };
+ const get = () => state;
+ Object.assign(
+ state,
+ createPolicySlice(set as never, get as never, {} as never)
+ );
+ return state as ReturnType<typeof createPolicySlice>;
+};
+
+describe("policy store", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.updatePolicy.mockImplementation(
+ async (request: UpdatePolicyRequest) =>
+ create(PolicySchema, request.policy)
+ );
+ });
+
+ test("upserts a review rule policy through its update mask", async () => {
+ const store = createStore();
+
+ await store.upsertPolicy({
+ parentPath: "projects/p",
+ policy: {
+ type: PolicyType.REVIEW_RULE,
+ resourceType: PolicyResourceType.PROJECT,
+ policy: {
+ case: "reviewRulePolicy",
+ value: create(ReviewRulePolicySchema, {
+ rules: [ReviewRuleType.SYNTAX],
+ }),
+ },
+ },
+ });
+
+ const request = mocks.updatePolicy.mock.calls[0][0] as UpdatePolicyRequest;
+ expect(request.policy?.name).toBe("projects/p/policies/review_rule");
+ expect(request.updateMask?.paths).toEqual(["review_rule_policy"]);
+ expect(request.allowMissing).toBe(true);
+ expect(
+ store.getPolicyByParentAndType({
+ parentPath: "projects/p",
+ policyType: PolicyType.REVIEW_RULE,
+ })?.policy.value
+ ).toEqual(expect.objectContaining({ rules: [ReviewRuleType.SYNTAX] }));
+ });
+});
diff --git a/frontend/src/stores/app/policy.ts b/frontend/src/stores/app/policy.ts
index 68da0bb071..a9b7a94894 100644
--- a/frontend/src/stores/app/policy.ts
+++ b/frontend/src/stores/app/policy.ts
@@ -28,6 +28,8 @@ const getUpdateMaskFromPolicyType = (policyType: PolicyType): string[] => {
return [PolicySchema.field.queryDataPolicy.name];
case PolicyType.TAG:
return [PolicySchema.field.tagPolicy.name];
+ case PolicyType.REVIEW_RULE:
+ return [PolicySchema.field.reviewRulePolicy.name];
default:
throw new Error(`unexpected policy type ${policyType}`);
}
diff --git a/frontend/src/types/proto-es/v1/org_policy_service_pb.d.ts b/frontend/src/types/proto-es/v1/org_policy_service_pb.d.ts
index 9ee88552b8..dc90f48e26 100644
--- a/frontend/src/types/proto-es/v1/org_policy_service_pb.d.ts
+++ b/frontend/src/types/proto-es/v1/org_policy_service_pb.d.ts
@@ -277,7 +277,12 @@ export declare const PolicySchema: GenMessage<Policy>;
/**
* Standard review rule policy: the rules switched on. The nearest policy
* wins: a project's own policy applies as is; a project without one uses
- * the workspace policy; with neither, every rule is on.
+ * the workspace policy; with neither, every rule is on. Getting the policy
+ * of a project without its own is NOT_FOUND; getting the workspace's when it
+ * has none returns every rule on.
+ *
+ * SYNTAX gates the rest: the other rules judge only SQL that parses, so a
+ * list without SYNTAX switches every rule off.
*
* A saved list is explicit, so a rule added to the standard set in a later
* release is appended to every saved policy by a data migration in that
diff --git a/frontend/src/types/proto-es/v1/review_rule_pb.d.ts b/frontend/src/types/proto-es/v1/review_rule_pb.d.ts
index defdbe8682..b93fbede34 100644
--- a/frontend/src/types/proto-es/v1/review_rule_pb.d.ts
+++ b/frontend/src/types/proto-es/v1/review_rule_pb.d.ts
@@ -28,7 +28,8 @@ export enum ReviewRuleType {
REVIEW_RULE_TYPE_UNSPECIFIED = 0,
/**
- * P0: the statements do not parse for the target engine.
+ * P0: the statements do not parse for the target engine. It gates the
+ * other rules (see ReviewRulePolicy).
*
* @generated from enum value: SYNTAX = 1;
*/
diff --git a/frontend/src/utils/featureGates.test.ts b/frontend/src/utils/featureGates.test.ts
new file mode 100644
index 0000000000..46891ee12a
--- /dev/null
+++ b/frontend/src/utils/featureGates.test.ts
@@ -0,0 +1,26 @@
+// @vitest-environment node
+import { expect, test, vi } from "vitest";
+
+test("the gate follows the dev build flag", async () => {
+ vi.resetModules();
+ vi.doMock("./util", () => ({ isDev: () => false }));
+ const disabled = await import("./featureGates");
+ expect(disabled.sqlReviewV2Enabled()).toBe(false);
+
+ vi.resetModules();
+ vi.doMock("./util", () => ({ isDev: () => true }));
+ const enabled = await import("./featureGates");
+ expect(enabled.sqlReviewV2Enabled()).toBe(true);
+
+ vi.doUnmock("./util");
+ vi.resetModules();
+});
+
+// Vitest reports DEV, so every other suite exercises the feature as an engineer
+// on the dev server sees it. A release bundle is the opposite case, and only the
+// suites that stub the gate cover it.
+test("the suite runs with the gate on, matching the dev server", async () => {
+ const { sqlReviewV2Enabled } = await import("./featureGates");
+ expect(import.meta.env.DEV).toBe(true);
+ expect(sqlReviewV2Enabled()).toBe(true);
+});
diff --git a/frontend/src/utils/featureGates.ts b/frontend/src/utils/featureGates.ts
new file mode 100644
index 0000000000..8bab869fbd
--- /dev/null
+++ b/frontend/src/utils/featureGates.ts
@@ -0,0 +1,10 @@
+import { isDev } from "./util";
+
+// SQL Review V2 is dark-launched: nothing triggers review runs yet and their
+// results do not render, so its settings stay on the Vite dev server only. The
+// review rule policy API stays live.
+//
+// `isDev()` is a build-time constant, so a release bundle folds every call to
+// `false` and drops the UI rather than hiding it. Flipping this to `true` is
+// the whole un-gate.
+export const sqlReviewV2Enabled = (): boolean => isDev();
diff --git a/proto/gen/grpc-doc/openapi.yaml b/proto/gen/grpc-doc/openapi.yaml
index 8f1f2eb90e..e2458c71ea 100644
--- a/proto/gen/grpc-doc/openapi.yaml
+++ b/proto/gen/grpc-doc/openapi.yaml
@@ -26876,7 +26876,12 @@ components:
description: |-
Standard review rule policy: the rules switched on. The nearest policy
wins: a project's own policy applies as is; a project without one uses
- the workspace policy; with neither, every rule is on.
+ the workspace policy; with neither, every rule is on. Getting the policy
+ of a project without its own is NOT_FOUND; getting the workspace's when it
+ has none returns every rule on.
+
+ SYNTAX gates the rest: the other rules judge only SQL that parses, so a
+ list without SYNTAX switches every rule off.
A saved list is explicit, so a rule added to the standard set in a later
release is appended to every saved policy by a data migration in that
diff --git a/proto/gen/grpc-doc/v1/README.md b/proto/gen/grpc-doc/v1/README.md
index 879883a121..cafd06e15f 100644
--- a/proto/gen/grpc-doc/v1/README.md
+++ b/proto/gen/grpc-doc/v1/README.md
@@ -3376,7 +3376,7 @@ needs a person&#39;s acceptance, not that it is forbidden.
| Name | Number | Description |
| ---- | ------ | ----------- |
| REVIEW_RULE_TYPE_UNSPECIFIED | 0 | |
-| SYNTAX | 1 | P0: the statements do not parse for the target engine. |
+| SYNTAX | 1 | P0: the statements do not parse for the target engine. It gates the other rules (see ReviewRulePolicy). |
| WALK_THROUGH | 2 | P0: applying the statements to the synced schema fails: a missing table or column, a duplicate object, or an invalid reference. |
| ONLINE_MIGRATION | 3 | P0: the change requests online migration but is not eligible. |
| PRIOR_BACKUP | 4 | P0: the change enables prior backup but the backup cannot be taken. |
@@ -10025,7 +10025,12 @@ the reviewer, and the project policy wins where they conflict.
### ReviewRulePolicy
Standard review rule policy: the rules switched on. The nearest policy
wins: a project&#39;s own policy applies as is; a project without one uses
-the workspace policy; with neither, every rule is on.
+the workspace policy; with neither, every rule is on. Getting the policy
+of a project without its own is NOT_FOUND; getting the workspace&#39;s when it
+has none returns every rule on.
+
+SYNTAX gates the rest: the other rules judge only SQL that parses, so a
+list without SYNTAX switches every rule off.
A saved list is explicit, so a rule added to the standard set in a later
release is appended to every saved policy by a data migration in that
diff --git a/proto/gen/grpc-doc/v1/index.html b/proto/gen/grpc-doc/v1/index.html
index cd72c388af..cd079035ca 100644
--- a/proto/gen/grpc-doc/v1/index.html
+++ b/proto/gen/grpc-doc/v1/index.html
@@ -10351,7 +10351,8 @@ Permissions required: bb.planCheckRuns.run</p></td>
<tr>
<td>SYNTAX</td>
<td>1</td>
- <td><p>P0: the statements do not parse for the target engine.</p></td>
+ <td><p>P0: the statements do not parse for the target engine. It gates the
+other rules (see ReviewRulePolicy).</p></td>
</tr>
<tr>
@@ -28524,7 +28525,7 @@ If false,
<h3 id="bytebase.v1.ReviewRulePolicy">ReviewRulePolicy</h3>
- <p>Standard review rule policy: the rules switched on. The nearest policy</p><p>wins: a project's own policy applies as is; a project without one uses</p><p>the workspace policy; with neither, every rule is on.</p><p>A saved list is explicit, so a rule added to the standard set in a later</p><p>release is appended to every saved policy by a data migration in that</p><p>release.</p>
+ <p>Standard review rule policy: the rules switched on. The nearest policy</p><p>wins: a project's own policy applies as is; a project without one uses</p><p>the workspace policy; with neither, every rule is on. Getting the policy</p><p>of a project without its own is NOT_FOUND; getting the workspace's when it</p><p>has none returns every rule on.</p><p>SYNTAX gates the rest: the other rules judge only SQL that parses, so a</p><p>list without SYNTAX switches every rule off.</p><p>A saved list is explicit, so a rule added to the standard set in a later</p><p>release is appended to every saved policy by a data migration in that</p><p>release.</p>
<table class="field-table">
diff --git a/proto/v1/v1/org_policy_service.proto b/proto/v1/v1/org_policy_service.proto
index bad9083aa8..6d137aaa9b 100644
--- a/proto/v1/v1/org_policy_service.proto
+++ b/proto/v1/v1/org_policy_service.proto
@@ -261,7 +261,12 @@ enum PolicyResourceType {
// Standard review rule policy: the rules switched on. The nearest policy
// wins: a project's own policy applies as is; a project without one uses
-// the workspace policy; with neither, every rule is on.
+// the workspace policy; with neither, every rule is on. Getting the policy
+// of a project without its own is NOT_FOUND; getting the workspace's when it
+// has none returns every rule on.
+//
+// SYNTAX gates the rest: the other rules judge only SQL that parses, so a
+// list without SYNTAX switches every rule off.
//
// A saved list is explicit, so a rule added to the standard set in a later
// release is appended to every saved policy by a data migration in that
diff --git a/proto/v1/v1/review_rule.proto b/proto/v1/v1/review_rule.proto
index 255ecdd6d1..651648cffe 100644
--- a/proto/v1/v1/review_rule.proto
+++ b/proto/v1/v1/review_rule.proto
@@ -15,7 +15,8 @@ option go_package = "github.com/bytebase/bytebase/backend/generated-go/v1";
enum ReviewRuleType {
REVIEW_RULE_TYPE_UNSPECIFIED = 0;
- // P0: the statements do not parse for the target engine.
+ // P0: the statements do not parse for the target engine. It gates the
+ // other rules (see ReviewRulePolicy).
SYNTAX = 1;
// P0: applying the statements to the synced schema fails: a missing
// table or column, a duplicate object, or an invalid reference.