Skip to content

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

feat(review): switch a dev build between SQL Review V1 and V2 (#21856)

rebelice4eb6213dd3c1
diff --git a/backend/runner/plancheck/executor_combined.go b/backend/runner/plancheck/executor_combined.go
index f196cafdfc..f971184844 100644
--- a/backend/runner/plancheck/executor_combined.go
+++ b/backend/runner/plancheck/executor_combined.go
@@ -2,8 +2,10 @@ package plancheck
import (
"context"
+ "log/slog"
"github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/common/log"
"github.com/bytebase/bytebase/backend/component/dbfactory"
"github.com/bytebase/bytebase/backend/component/sheet"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
@@ -70,20 +72,32 @@ func (e *CombinedExecutor) RunForTarget(ctx context.Context, target *CheckTarget
}
// supersededBySQLReviewV2 reports whether the standard rule review replaces
-// the check where SQL Review V2 is on: only the SQL review advice, and only on
-// an engine the rule review covers; V1 keeps advising the others. The gh-ost
-// check stays, since it dry-runs the migration against the instance, which
-// the ONLINE_MIGRATION rule, reading the SQL alone, cannot.
+// the check where SQL Review V2 is on: only the SQL review advice, only on an
+// engine the rule review covers, and only where the project's review rule
+// policy leaves a rule on. V1 advises everywhere else, so a policy with every
+// rule off hands the project back to V1. The gh-ost check stays, since it
+// dry-runs the migration against the instance, which the ONLINE_MIGRATION
+// rule, reading the SQL alone, cannot.
func (e *CombinedExecutor) supersededBySQLReviewV2(ctx context.Context, target *CheckTarget, checkType storepb.PlanCheckType) bool {
if e.ruleReviewCovers == nil || checkType != storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_ADVISE {
return false
}
- instance, _, err := ResolveDatabaseTarget(ctx, e.store, target.Target)
+ instance, database, err := ResolveDatabaseTarget(ctx, e.store, target.Target)
if err != nil {
// The advice runs, and reports the target it cannot resolve.
return false
}
- return e.ruleReviewCovers(instance.Metadata.GetEngine())
+ if !e.ruleReviewCovers(instance.Metadata.GetEngine()) {
+ return false
+ }
+ policy, err := e.store.GetEffectiveReviewRulePolicy(ctx, instance.Workspace, database.ProjectID)
+ if err != nil {
+ slog.Warn("failed to get the review rule policy; running the SQL review advice",
+ slog.String("target", target.Target),
+ log.BBError(err))
+ return false
+ }
+ return len(policy.GetRules()) > 0
}
func (e *CombinedExecutor) runCheck(ctx context.Context, target *CheckTarget, checkType storepb.PlanCheckType) ([]*storepb.PlanCheckRunResult_Result, error) {
diff --git a/backend/runner/plancheck/executor_combined_test.go b/backend/runner/plancheck/executor_combined_test.go
index 894606cb6f..e1c1430575 100644
--- a/backend/runner/plancheck/executor_combined_test.go
+++ b/backend/runner/plancheck/executor_combined_test.go
@@ -5,7 +5,9 @@ import (
"testing"
"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"
"github.com/bytebase/bytebase/backend/store"
)
@@ -55,3 +57,49 @@ func TestCombinedExecutorLeavesSQLReviewToV2(t *testing.T) {
require.NoError(t, err)
require.Empty(t, results)
}
+
+func TestCombinedExecutorHandsSQLReviewToV1WhereEveryRuleIsOff(t *testing.T) {
+ ctx := context.Background()
+ s := setupPlancheckStore(ctx, t)
+ _, err := s.CreateInstance(ctx, &store.InstanceMessage{
+ ResourceID: "pg",
+ Workspace: "default",
+ Metadata: &storepb.Instance{
+ Engine: storepb.Engine_POSTGRES,
+ DataSources: []*storepb.DataSource{{Id: "admin", Type: storepb.DataSourceType_ADMIN}},
+ },
+ })
+ require.NoError(t, err)
+ _, err = s.UpsertDatabase(ctx, &store.DatabaseMessage{
+ ProjectID: "project-a",
+ InstanceID: "pg",
+ DatabaseName: "app",
+ Metadata: &storepb.DatabaseMetadata{Labels: map[string]string{}},
+ })
+ require.NoError(t, err)
+ setRules := func(resourceType storepb.Policy_Resource, resource string, rules ...storepb.ReviewRuleType) {
+ payload, err := protojson.Marshal(&storepb.ReviewRulePolicy{Rules: rules})
+ require.NoError(t, err)
+ _, err = s.CreatePolicy(ctx, &store.PolicyMessage{
+ Workspace: "default",
+ ResourceType: resourceType,
+ Resource: resource,
+ Type: storepb.Policy_REVIEW_RULE,
+ Payload: string(payload),
+ Enforce: true,
+ })
+ require.NoError(t, err)
+ }
+ executor := NewCombinedExecutor(s, nil, nil, func(storepb.Engine) bool { return true })
+ target := &CheckTarget{Target: "instances/pg/databases/app"}
+ advise := storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_ADVISE
+
+ setRules(storepb.Policy_WORKSPACE, common.FormatWorkspace("default"))
+ require.False(t, executor.supersededBySQLReviewV2(ctx, target, advise))
+
+ setRules(storepb.Policy_PROJECT, common.FormatProject("project-a"), storepb.ReviewRuleType_SYNTAX)
+ require.True(t, executor.supersededBySQLReviewV2(ctx, target, advise), "the project's own policy wins over the workspace's")
+
+ setRules(storepb.Policy_PROJECT, common.FormatProject("project-a"), storepb.ReviewRuleType_REQUIRE_WHERE)
+ require.False(t, executor.supersededBySQLReviewV2(ctx, target, advise), "without SYNTAX no rule runs")
+}
diff --git a/frontend/src/locales/sql-review/en-US.json b/frontend/src/locales/sql-review/en-US.json
index cfaf6f2de4..9aaecdf7ef 100644
--- a/frontend/src/locales/sql-review/en-US.json
+++ b/frontend/src/locales/sql-review/en-US.json
@@ -835,5 +835,19 @@
"number-positive": "Enter a positive number for {{rule}}.",
"rule-required": "Select at least one rule.",
"string-array-required": "Add at least one value for {{rule}}."
+ },
+ "version-switch": {
+ "description": "Dev builds only. The server runs V1 for a project whose standard rules are all off, and V2 otherwise. This browser shows the pages of the version you choose.",
+ "self": "SQL Review version",
+ "to-v1": {
+ "confirm": "Switch to V1",
+ "description": "This turns every workspace standard rule off, so the plan checks run the V1 SQL review. Projects that customize their standard rules keep them.",
+ "title": "Switch to SQL Review V1?"
+ },
+ "to-v2": {
+ "confirm": "Switch to V2",
+ "description": "This turns every workspace standard rule on, so the standard rule review replaces the V1 SQL review.",
+ "title": "Switch to SQL Review V2?"
+ }
}
}
diff --git a/frontend/src/locales/sql-review/es-ES.json b/frontend/src/locales/sql-review/es-ES.json
index 803f93c854..57506dca46 100644
--- a/frontend/src/locales/sql-review/es-ES.json
+++ b/frontend/src/locales/sql-review/es-ES.json
@@ -835,5 +835,19 @@
"number-positive": "Ingrese un número positivo para {{rule}}.",
"rule-required": "Seleccione al menos una regla.",
"string-array-required": "Agregue al menos un valor para {{rule}}."
+ },
+ "version-switch": {
+ "description": "Solo en compilaciones dev. El servidor ejecuta V1 en un proyecto con todas sus reglas estándar desactivadas, y V2 en los demás. Este navegador muestra las páginas de la versión que elijas.",
+ "self": "Versión de la revisión SQL",
+ "to-v1": {
+ "confirm": "Cambiar a V1",
+ "description": "Esto desactiva todas las reglas estándar del espacio de trabajo, así que la comprobación del plan ejecuta la revisión SQL V1. Los proyectos que personalizan sus reglas estándar las conservan.",
+ "title": "¿Cambiar a la revisión SQL V1?"
+ },
+ "to-v2": {
+ "confirm": "Cambiar a V2",
+ "description": "Esto activa todas las reglas estándar del espacio de trabajo, así que la revisión de reglas estándar sustituye a la revisión SQL V1.",
+ "title": "¿Cambiar a la revisión SQL V2?"
+ }
}
}
diff --git a/frontend/src/locales/sql-review/ja-JP.json b/frontend/src/locales/sql-review/ja-JP.json
index 71210e53f3..46e55e7f1b 100644
--- a/frontend/src/locales/sql-review/ja-JP.json
+++ b/frontend/src/locales/sql-review/ja-JP.json
@@ -835,5 +835,19 @@
"number-positive": "{{rule}} には正の数を入力してください。",
"rule-required": "少なくとも 1 つのルールを選択してください。",
"string-array-required": "{{rule}} に少なくとも 1 つの値を追加してください。"
+ },
+ "version-switch": {
+ "description": "dev ビルドのみ。標準ルールがすべてオフのプロジェクトではサーバーが V1 を実行し、それ以外では V2 を実行します。このブラウザーには選択したバージョンのページが表示されます。",
+ "self": "SQL レビューのバージョン",
+ "to-v1": {
+ "confirm": "V1 に切り替える",
+ "description": "ワークスペースの標準ルールをすべてオフにし、プランチェックで V1 の SQL レビューを実行します。標準ルールをカスタマイズしたプロジェクトはそのままです。",
+ "title": "SQL レビュー V1 に切り替えますか?"
+ },
+ "to-v2": {
+ "confirm": "V2 に切り替える",
+ "description": "ワークスペースの標準ルールをすべてオンにし、標準ルールのレビューが V1 の SQL レビューに置き換わります。",
+ "title": "SQL レビュー V2 に切り替えますか?"
+ }
}
}
diff --git a/frontend/src/locales/sql-review/vi-VN.json b/frontend/src/locales/sql-review/vi-VN.json
index 251a4606b7..e5b85d8b6e 100644
--- a/frontend/src/locales/sql-review/vi-VN.json
+++ b/frontend/src/locales/sql-review/vi-VN.json
@@ -835,5 +835,19 @@
"number-positive": "Nhập số dương cho {{rule}}.",
"rule-required": "Chọn ít nhất một quy tắc.",
"string-array-required": "Thêm ít nhất một giá trị cho {{rule}}."
+ },
+ "version-switch": {
+ "description": "Chỉ dành cho bản dev. Máy chủ chạy V1 cho dự án tắt toàn bộ quy tắc tiêu chuẩn, và chạy V2 cho các dự án còn lại. Trình duyệt này hiển thị các trang của phiên bản bạn chọn.",
+ "self": "Phiên bản đánh giá SQL",
+ "to-v1": {
+ "confirm": "Chuyển sang V1",
+ "description": "Thao tác này tắt mọi quy tắc tiêu chuẩn của workspace, nên kiểm tra kế hoạch sẽ chạy đánh giá SQL V1. Các dự án tùy chỉnh quy tắc tiêu chuẩn vẫn giữ nguyên.",
+ "title": "Chuyển sang đánh giá SQL V1?"
+ },
+ "to-v2": {
+ "confirm": "Chuyển sang V2",
+ "description": "Thao tác này bật mọi quy tắc tiêu chuẩn của workspace, nên đánh giá theo quy tắc tiêu chuẩn sẽ thay thế đánh giá SQL V1.",
+ "title": "Chuyển sang đánh giá SQL V2?"
+ }
}
}
diff --git a/frontend/src/locales/sql-review/zh-CN.json b/frontend/src/locales/sql-review/zh-CN.json
index 535c7522f0..8c45e5a1da 100644
--- a/frontend/src/locales/sql-review/zh-CN.json
+++ b/frontend/src/locales/sql-review/zh-CN.json
@@ -835,5 +835,19 @@
"number-positive": "请为 {{rule}} 输入一个正数。",
"rule-required": "请选择至少一条规则。",
"string-array-required": "请为 {{rule}} 添加至少一个值。"
+ },
+ "version-switch": {
+ "description": "仅限 dev 构建。标准规则全部关闭的项目,服务端运行 V1,其余运行 V2。此浏览器显示所选版本的页面。",
+ "self": "SQL 审核版本",
+ "to-v1": {
+ "confirm": "切换到 V1",
+ "description": "这会关闭工作空间的全部标准规则,计划检查改为运行 V1 SQL 审核。自定义了标准规则的项目保持不变。",
+ "title": "切换到 SQL 审核 V1?"
+ },
+ "to-v2": {
+ "confirm": "切换到 V2",
+ "description": "这会开启工作空间的全部标准规则,由标准规则审核取代 V1 SQL 审核。",
+ "title": "切换到 SQL 审核 V2?"
+ }
}
}
diff --git a/frontend/src/routes/workspace/SQLReviewPage.test.tsx b/frontend/src/routes/workspace/SQLReviewPage.test.tsx
index c24b89d544..37c6357232 100644
--- a/frontend/src/routes/workspace/SQLReviewPage.test.tsx
+++ b/frontend/src/routes/workspace/SQLReviewPage.test.tsx
@@ -3,6 +3,7 @@ import type { ReactNode } from "react";
import { beforeEach, describe, expect, test, vi } from "vitest";
const mocks = vi.hoisted(() => ({
+ dev: { value: true },
sqlReviewV2: { value: true },
fetchReviewPolicyList: vi.fn(),
standardRules: {
@@ -46,6 +47,10 @@ vi.mock("./SQLReviewStandardRulesSection", () => ({
useWorkspaceStandardRules: () => mocks.standardRules,
}));
+vi.mock("./SQLReviewVersionSwitch", () => ({
+ SQLReviewVersionSwitch: () => <div>version-switch</div>,
+}));
+
vi.mock("./SQLReviewAIReviewSection", () => ({
SQLReviewAIReviewSection: () => <div>ai-review-section</div>,
useWorkspaceAIReview: () => mocks.aiReview,
@@ -78,6 +83,7 @@ vi.mock("@/hooks/useUnsavedChangesGuard", () => ({
vi.mock("@/stores", () => ({ pushNotification: mocks.pushNotification }));
vi.mock("@/utils", () => ({
hasWorkspacePermissionV2: () => true,
+ isDev: () => mocks.dev.value,
sqlReviewPolicySlug: () => "slug",
}));
@@ -101,6 +107,7 @@ describe("SQLReviewPage", () => {
part.revert.mockReset();
part.save.mockReset().mockResolvedValue(true);
}
+ mocks.dev.value = true;
mocks.aiReviewPolicy.error = undefined;
mocks.aiReview.aiEnabled = true;
mocks.aiReview.enabled = true;
@@ -150,6 +157,24 @@ describe("SQLReviewPage", () => {
expect(mocks.aiReviewPolicyEnabled).toHaveBeenLastCalledWith(false);
});
+ test.each([
+ true,
+ false,
+ ])("offers the SQL Review version switch on a dev build (V2: %s)", (v2) => {
+ mocks.sqlReviewV2.value = v2;
+ render(<SQLReviewPage />);
+
+ expect(screen.getByText("version-switch")).toBeInTheDocument();
+ });
+
+ test("leaves the SQL Review version switch out of a release build", () => {
+ mocks.dev.value = false;
+ mocks.sqlReviewV2.value = false;
+ render(<SQLReviewPage />);
+
+ expect(screen.queryByText("version-switch")).not.toBeInTheDocument();
+ });
+
test("keeps the review policy draft mounted while AI is unavailable", () => {
mocks.sqlReviewV2.value = true;
mocks.aiReview.aiEnabled = false;
diff --git a/frontend/src/routes/workspace/SQLReviewPage.tsx b/frontend/src/routes/workspace/SQLReviewPage.tsx
index 47cffd06ab..d1d5587384 100644
--- a/frontend/src/routes/workspace/SQLReviewPage.tsx
+++ b/frontend/src/routes/workspace/SQLReviewPage.tsx
@@ -32,7 +32,7 @@ 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 { hasWorkspacePermissionV2, isDev, sqlReviewPolicySlug } from "@/utils";
import { sqlReviewV2Enabled } from "@/utils/featureGates";
import {
SQLReviewAIReviewSection,
@@ -43,6 +43,7 @@ import {
SQLReviewStandardRulesSection,
useWorkspaceStandardRules,
} from "./SQLReviewStandardRulesSection";
+import { SQLReviewVersionSwitch } from "./SQLReviewVersionSwitch";
// ============================================================
// PolicyTable
@@ -313,6 +314,7 @@ export function SQLReviewPage() {
return (
<WorkspacePageLayout className="gap-y-4">
+ {isDev() && <SQLReviewVersionSwitch />}
{sqlReviewV2 ? (
<>
<SQLReviewStandardRulesSection standardRules={standardRules} />
diff --git a/frontend/src/routes/workspace/SQLReviewVersionSwitch.test.tsx b/frontend/src/routes/workspace/SQLReviewVersionSwitch.test.tsx
new file mode 100644
index 0000000000..8bd6325099
--- /dev/null
+++ b/frontend/src/routes/workspace/SQLReviewVersionSwitch.test.tsx
@@ -0,0 +1,132 @@
+import { act, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+import { STANDARD_RULE_TYPES } from "@/components/sql-review/standardRules";
+import { PolicyResourceType } from "@/types/proto-es/v1/org_policy_service_pb";
+import {
+ devSqlReviewVersion,
+ setDevSqlReviewVersion,
+} from "@/utils/featureGates";
+
+const mocks = vi.hoisted(() => ({
+ canUpdate: { value: true },
+ upsertPolicy: vi.fn(),
+ reload: vi.fn(),
+}));
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock("@/hooks/useAppState", () => ({
+ useWorkspaceResourceName: () => "workspaces/ws",
+}));
+
+vi.mock("@/stores/app", () => ({
+ useAppStore: {
+ getState: () => ({ upsertPolicy: mocks.upsertPolicy }),
+ },
+}));
+
+vi.mock("@/utils", () => ({
+ hasWorkspacePermissionV2: () => mocks.canUpdate.value,
+}));
+
+const { SQLReviewVersionSwitch } = await import("./SQLReviewVersionSwitch");
+
+const choose = (label: string) =>
+ act(async () => {
+ fireEvent.click(screen.getByRole("radio", { name: label }));
+ });
+
+const click = (name: string) =>
+ act(async () => {
+ fireEvent.click(screen.getByRole("button", { name }));
+ });
+
+const savedRules = () => {
+ const { parentPath, policy } = mocks.upsertPolicy.mock.lastCall?.[0] ?? {};
+ expect(parentPath).toBe("workspaces/ws");
+ expect(policy.resourceType).toBe(PolicyResourceType.WORKSPACE);
+ expect(policy.enforce).toBe(true);
+ return policy.policy.value.rules;
+};
+
+describe("SQLReviewVersionSwitch", () => {
+ const location = globalThis.location;
+
+ beforeEach(() => {
+ mocks.canUpdate.value = true;
+ mocks.upsertPolicy.mockReset().mockResolvedValue(undefined);
+ mocks.reload.mockReset();
+ Object.defineProperty(globalThis, "location", {
+ writable: true,
+ value: { ...location, reload: mocks.reload },
+ });
+ });
+
+ afterEach(() => {
+ Object.defineProperty(globalThis, "location", {
+ writable: true,
+ value: location,
+ });
+ localStorage.clear();
+ });
+
+ test("switching to V1 turns every workspace standard rule off", async () => {
+ render(<SQLReviewVersionSwitch />);
+
+ await choose("V1");
+ expect(
+ screen.getByText("sql-review.version-switch.to-v1.description")
+ ).toBeInTheDocument();
+ await click("sql-review.version-switch.to-v1.confirm");
+
+ expect(savedRules()).toEqual([]);
+ expect(devSqlReviewVersion()).toBe("v1");
+ expect(mocks.reload).toHaveBeenCalledTimes(1);
+ });
+
+ test("switching to V2 turns every workspace standard rule on", async () => {
+ setDevSqlReviewVersion("v1");
+ render(<SQLReviewVersionSwitch />);
+
+ await choose("V2");
+ await click("sql-review.version-switch.to-v2.confirm");
+
+ expect(savedRules()).toEqual([...STANDARD_RULE_TYPES]);
+ expect(devSqlReviewVersion()).toBe("v2");
+ expect(mocks.reload).toHaveBeenCalledTimes(1);
+ });
+
+ test("cancelling changes nothing", async () => {
+ render(<SQLReviewVersionSwitch />);
+
+ await choose("V1");
+ await click("common.cancel");
+
+ expect(mocks.upsertPolicy).not.toHaveBeenCalled();
+ expect(devSqlReviewVersion()).toBe("v2");
+ expect(mocks.reload).not.toHaveBeenCalled();
+ });
+
+ test("keeps this browser's version when the rules fail to save", async () => {
+ mocks.upsertPolicy.mockRejectedValue(new Error("denied"));
+ render(<SQLReviewVersionSwitch />);
+
+ await choose("V1");
+ await click("sql-review.version-switch.to-v1.confirm");
+
+ expect(devSqlReviewVersion()).toBe("v2");
+ expect(mocks.reload).not.toHaveBeenCalled();
+ });
+
+ test("is disabled without permission to update policies", () => {
+ mocks.canUpdate.value = false;
+ render(<SQLReviewVersionSwitch />);
+
+ expect(screen.getByRole("radio", { name: "V1" })).toHaveAttribute(
+ "aria-disabled",
+ "true"
+ );
+ });
+});
diff --git a/frontend/src/routes/workspace/SQLReviewVersionSwitch.tsx b/frontend/src/routes/workspace/SQLReviewVersionSwitch.tsx
new file mode 100644
index 0000000000..01aa68580d
--- /dev/null
+++ b/frontend/src/routes/workspace/SQLReviewVersionSwitch.tsx
@@ -0,0 +1,127 @@
+import { create } from "@bufbuild/protobuf";
+import { useState } from "react";
+import { useTranslation } from "react-i18next";
+import { STANDARD_RULE_TYPES } from "@/components/sql-review/standardRules";
+import {
+ AlertDialog,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogTitle,
+} from "@/components/ui/alert-dialog";
+import { Button } from "@/components/ui/button";
+import { FormSection } from "@/components/ui/form";
+import { SegmentedControl } from "@/components/ui/segmented-control";
+import { useWorkspaceResourceName } from "@/hooks/useAppState";
+import { useAppStore } from "@/stores/app";
+import {
+ PolicyResourceType,
+ PolicyType,
+ ReviewRulePolicySchema,
+} from "@/types/proto-es/v1/org_policy_service_pb";
+import { hasWorkspacePermissionV2 } from "@/utils";
+import {
+ devSqlReviewVersion,
+ type SqlReviewVersion,
+ setDevSqlReviewVersion,
+} from "@/utils/featureGates";
+
+const VERSION_OPTIONS = [
+ { value: "v1" as const, label: "V1" },
+ { value: "v2" as const, label: "V2" },
+];
+
+// Dev builds only. The server runs V1's SQL review for a project whose
+// standard rules are all off, so switching writes the workspace standard rules
+// as well as this browser's choice of pages. The page then reloads, since the
+// SQL review gate is read outside React state.
+export function SQLReviewVersionSwitch() {
+ const { t } = useTranslation();
+ const workspace = useWorkspaceResourceName();
+ const current = devSqlReviewVersion();
+ const [target, setTarget] = useState<SqlReviewVersion>();
+ const [switching, setSwitching] = useState(false);
+
+ const switchVersion = async (version: SqlReviewVersion) => {
+ setSwitching(true);
+ try {
+ await useAppStore.getState().upsertPolicy({
+ parentPath: workspace,
+ policy: {
+ type: PolicyType.REVIEW_RULE,
+ resourceType: PolicyResourceType.WORKSPACE,
+ enforce: true,
+ policy: {
+ case: "reviewRulePolicy",
+ value: create(ReviewRulePolicySchema, {
+ rules: version === "v1" ? [] : [...STANDARD_RULE_TYPES],
+ }),
+ },
+ },
+ });
+ } catch {
+ // The response middleware reports the failure.
+ setSwitching(false);
+ return;
+ }
+ setDevSqlReviewVersion(version);
+ globalThis.location.reload();
+ };
+
+ return (
+ <FormSection
+ layout="single-column"
+ padding="none"
+ title={t("sql-review.version-switch.self")}
+ description={t("sql-review.version-switch.description")}
+ >
+ <SegmentedControl
+ value={current}
+ options={VERSION_OPTIONS}
+ onValueChange={(version) => {
+ if (version !== current) setTarget(version);
+ }}
+ ariaLabel={t("sql-review.version-switch.self")}
+ disabled={!hasWorkspacePermissionV2("bb.policies.update") || switching}
+ />
+ <AlertDialog
+ open={target !== undefined}
+ onOpenChange={(open) => {
+ if (!open && !switching) setTarget(undefined);
+ }}
+ >
+ <AlertDialogContent>
+ <AlertDialogTitle>
+ {target === "v1"
+ ? t("sql-review.version-switch.to-v1.title")
+ : t("sql-review.version-switch.to-v2.title")}
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ {target === "v1"
+ ? t("sql-review.version-switch.to-v1.description")
+ : t("sql-review.version-switch.to-v2.description")}
+ </AlertDialogDescription>
+ <AlertDialogFooter>
+ <Button
+ appearance="outline"
+ disabled={switching}
+ onClick={() => setTarget(undefined)}
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button
+ disabled={switching}
+ onClick={() => {
+ if (target) void switchVersion(target);
+ }}
+ >
+ {target === "v1"
+ ? t("sql-review.version-switch.to-v1.confirm")
+ : t("sql-review.version-switch.to-v2.confirm")}
+ </Button>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </FormSection>
+ );
+}
diff --git a/frontend/src/utils/featureGates.test.ts b/frontend/src/utils/featureGates.test.ts
index 46891ee12a..3a899747e0 100644
--- a/frontend/src/utils/featureGates.test.ts
+++ b/frontend/src/utils/featureGates.test.ts
@@ -1,5 +1,8 @@
-// @vitest-environment node
-import { expect, test, vi } from "vitest";
+import { afterEach, expect, test, vi } from "vitest";
+
+afterEach(() => {
+ localStorage.clear();
+});
test("the gate follows the dev build flag", async () => {
vi.resetModules();
@@ -24,3 +27,16 @@ test("the suite runs with the gate on, matching the dev server", async () => {
expect(import.meta.env.DEV).toBe(true);
expect(sqlReviewV2Enabled()).toBe(true);
});
+
+test("a dev browser switched to V1 turns the gate off until it switches back", async () => {
+ const { devSqlReviewVersion, setDevSqlReviewVersion, sqlReviewV2Enabled } =
+ await import("./featureGates");
+ expect(devSqlReviewVersion()).toBe("v2");
+
+ setDevSqlReviewVersion("v1");
+ expect(devSqlReviewVersion()).toBe("v1");
+ expect(sqlReviewV2Enabled()).toBe(false);
+
+ setDevSqlReviewVersion("v2");
+ expect(sqlReviewV2Enabled()).toBe(true);
+});
diff --git a/frontend/src/utils/featureGates.ts b/frontend/src/utils/featureGates.ts
index b58801e311..b9871f15ea 100644
--- a/frontend/src/utils/featureGates.ts
+++ b/frontend/src/utils/featureGates.ts
@@ -1,14 +1,28 @@
+import { STORAGE_KEY_SQL_REVIEW_VERSION } from "./storage-keys";
import { isDev } from "./util";
+export type SqlReviewVersion = "v1" | "v2";
+
+// The SQL review this browser shows on the Vite dev server. The workspace SQL
+// Review page switches it, together with the workspace standard rules the
+// server reads to choose between V1 and V2.
+export const devSqlReviewVersion = (): SqlReviewVersion =>
+ localStorage.getItem(STORAGE_KEY_SQL_REVIEW_VERSION) === "v1" ? "v1" : "v2";
+
+export const setDevSqlReviewVersion = (version: SqlReviewVersion): void => {
+ localStorage.setItem(STORAGE_KEY_SQL_REVIEW_VERSION, version);
+};
+
// SQL Review V2 is dark-launched: its settings and the standard rule review in
-// the plan page's Checks row stay on the Vite dev server only. The review rule
-// policy API stays live. On the server, the profile's SQLReviewV2 is the same
-// switch, on only in a dev build.
+// the plan page's Checks row stay on the Vite dev server only, unless that
+// browser switched back to V1. The review rule policy API stays live. On the
+// server, the profile's SQLReviewV2 is the same switch, on only in a dev build.
//
// `isDev()` is a build-time constant, so a release bundle folds every call to
// `false` and drops the UI rather than hiding it. Un-gating flips this and the
// server switch together.
-export const sqlReviewV2Enabled = (): boolean => isDev();
+export const sqlReviewV2Enabled = (): boolean =>
+ isDev() && devSqlReviewVersion() === "v2";
export const isSaaSOrDev = (isSaaSMode: boolean): boolean =>
isSaaSMode || isDev();
diff --git a/frontend/src/utils/storage-keys.ts b/frontend/src/utils/storage-keys.ts
index 2bc282fa0a..e4303ef757 100644
--- a/frontend/src/utils/storage-keys.ts
+++ b/frontend/src/utils/storage-keys.ts
@@ -46,6 +46,7 @@ export const STORAGE_KEY_SQL_EDITOR_DETAIL_LINE_WRAP =
export const STORAGE_KEY_SQL_EDITOR_NOSQL_TABLE_VIEW =
"bb.sql-editor.es-table-view";
export const STORAGE_KEY_MY_ISSUES_TAB = "bb.components.MY_ISSUES.id";
+export const STORAGE_KEY_SQL_REVIEW_VERSION = "bb.sql-review.version";
// --- User-scoped (cleaned on logout) ---
// Workspace-scoped: holds route paths / project names that are workspace-local.