Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
fix: restore Create Database direct-to-Issue flow (#21103)
boojackd57da99791ec
diff --git a/frontend/src/components/IssueLabelSelect.tsx b/frontend/src/components/IssueLabelSelect.tsxindex e5870ff9dd..94d47f1808 100644--- a/frontend/src/components/IssueLabelSelect.tsx+++ b/frontend/src/components/IssueLabelSelect.tsx@@ -1,9 +1,12 @@import { ChevronDown, X } from "lucide-react";-import { useCallback, useRef, useState } from "react";+import { useState } from "react";import { useTranslation } from "react-i18next";import { Checkbox } from "@/components/ui/checkbox";-import { LAYER_SURFACE_CLASS } from "@/components/ui/layer";-import { useClickOutside } from "@/hooks/useClickOutside";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@/components/ui/popover";import { cn } from "@/lib/utils";import type { Color } from "@/types/proto-es/google/type/color_pb";import { colorToHex } from "@/utils";@@ -25,7 +28,9 @@ interface IssueLabelSelectProps {** Rendered as a dropdown with chip-style selected labels. Shared between* drawers that need to attach labels to a new issue (e.g. Data Export,- * Request Role).+ * Request Role). The menu renders through the shared Popover portal so it+ * cannot be clipped by a scrollable sheet body — selection must stay+ * reachable when the project makes labels required.*/export function IssueLabelSelect({labels,@@ -35,9 +40,6 @@ export function IssueLabelSelect({}: IssueLabelSelectProps) {const { t } = useTranslation();const [open, setOpen] = useState(false);- const containerRef = useRef<HTMLDivElement>(null);- const closeDropdown = useCallback(() => setOpen(false), []);- useClickOutside(containerRef, open, closeDropdown);const toggleLabel = (value: string) => {onChange(@@ -54,15 +56,13 @@ export function IssueLabelSelect({{t("issue.labels")}{required && <span className="text-error"> *</span>}</label>- <div ref={containerRef} className="relative">- <button- type="button"+ <Popover open={open} onOpenChange={setOpen}>+ <PopoverTriggerclassName={cn("w-full flex items-center justify-between gap-2 border border-control-border rounded-sm h-9 px-3 text-sm bg-background text-left transition-colors","hover:border-control-border",open && "border-accent shadow-[0_0_0_1px_var(--color-accent)]")}- onClick={() => setOpen(!open)}>{selected.length > 0 ? (<div className="flex items-center gap-1.5 truncate">@@ -100,43 +100,39 @@ export function IssueLabelSelect({open && "rotate-180")}/>- </button>- {open && (- <div- className={cn(- "absolute mt-1 w-full bg-background border border-block-border rounded-sm shadow-lg overflow-hidden",- LAYER_SURFACE_CLASS+ </PopoverTrigger>+ <PopoverContent+ align="start"+ className="w-(--anchor-width) p-0 overflow-hidden"+ >+ <div className="max-h-60 overflow-y-auto">+ {labels.length === 0 ? (+ <div className="px-3 py-6 text-sm text-control-placeholder text-center">+ {t("common.no-data")}+ </div>+ ) : (+ labels.map((label) => {+ const isSelected = selected.includes(label.value);+ return (+ <button+ key={label.value}+ type="button"+ className="w-full text-left px-3 py-2 text-sm flex items-center gap-2 hover:bg-control-bg transition-colors"+ onClick={() => toggleLabel(label.value)}+ >+ <Checkbox checked={isSelected} />+ <span+ className="size-4 rounded-sm shrink-0"+ style={{ backgroundColor: getColor(label.color) }}+ />+ <span>{label.value}</span>+ </button>+ );+ }))}- >- <div className="max-h-60 overflow-y-auto">- {labels.length === 0 ? (- <div className="px-3 py-6 text-sm text-control-placeholder text-center">- {t("common.no-data")}- </div>- ) : (- labels.map((label) => {- const isSelected = selected.includes(label.value);- return (- <button- key={label.value}- type="button"- className="w-full text-left px-3 py-2 text-sm flex items-center gap-2 hover:bg-control-bg transition-colors"- onClick={() => toggleLabel(label.value)}- >- <Checkbox checked={isSelected} />- <span- className="size-4 rounded-sm shrink-0"- style={{ backgroundColor: getColor(label.color) }}- />- <span>{label.value}</span>- </button>- );- })- )}- </div></div>- )}- </div>+ </PopoverContent>+ </Popover></div>);}diff --git a/frontend/src/components/database/CreateDatabaseSheet.test.tsx b/frontend/src/components/database/CreateDatabaseSheet.test.tsxindex 50509e444a..813c761132 100644--- a/frontend/src/components/database/CreateDatabaseSheet.test.tsx+++ b/frontend/src/components/database/CreateDatabaseSheet.test.tsx@@ -97,8 +97,22 @@ vi.mock("@/components/ui/combobox", () => ({}),}));-vi.mock("@/hooks/useClickOutside", () => ({- useClickOutside: () => undefined,+vi.mock("@/components/ui/popover", () => ({+ Popover: ({ children }: { children: ReactNode }) => children,+ PopoverTrigger: ({+ children,+ className: _c,+ }: {+ children: ReactNode;+ className?: string;+ }) => createElement("button", { type: "button" }, children),+ PopoverContent: ({+ children,+ className: _c,+ }: {+ children: ReactNode;+ className?: string;+ }) => createElement("div", { "data-testid": "popover-content" }, children),}));vi.mock("@/lib/utils", () => ({@@ -119,7 +133,6 @@ vi.mock("@/types/proto-es/v1/plan_service_pb", () => ({vi.mock("@/types/proto-es/v1/issue_service_pb", () => ({Issue_Type: { DATABASE_CHANGE: 1 },- IssueStatus: { OPEN: 1 },CreateIssueRequestSchema: {},IssueSchema: {},}));@@ -225,10 +238,18 @@ vi.mock("@/types", () => ({}));vi.mock("@/utils", () => ({+ colorToHex: () => undefined,enginesSupportCreateDatabase: () => [],extractPlanUID: (name: string) => name.split("/").at(-1) ?? "",extractProjectResourceName: (name: string) => name.split("/")[1] ?? "",getDefaultPagination: () => 20,+ getIssueRoute: (issue: { name: string }) => ({+ name: "workspace.project.issue.detail",+ params: {+ projectId: issue.name.split("/")[1] ?? "",+ issueId: issue.name.split("/").at(-1) ?? "",+ },+ }),instanceV1HasCollationAndCharacterSet: () => false,normalizeTitle: (s: string) => s.trim(),}));@@ -261,7 +282,7 @@ beforeEach(() => {});mocks.createIssue.mockResolvedValue({name: "projects/foo/issues/456",- draft: true,+ draft: false,plan: "projects/foo/plans/123",});});@@ -273,20 +294,34 @@ afterEach(() => {document.body.removeChild(container);});-function setupProjectMock(enforceIssueTitle: boolean) {+interface ProjectMockOptions {+ issueLabels?: { value: string }[];+ forceIssueLabels?: boolean;+}++function setupProjectMock(+ enforceIssueTitle: boolean,+ {+ issueLabels = [],+ forceIssueLabels = false,+ }: ProjectMockOptions = {}+) {mocks.getOrFetchProjectByName.mockImplementation(async (name: string) => ({name,enforceIssueTitle,- issueLabels: [],- forceIssueLabels: false,+ issueLabels,+ forceIssueLabels,}));appStoreState.instancesByName[TEST_INSTANCE.name] = TEST_INSTANCE;mocks.instancesByName[TEST_INSTANCE.name] = TEST_INSTANCE;mocks.getOrFetchInstanceByName.mockResolvedValue(TEST_INSTANCE);}-async function renderSheet(enforceIssueTitle: boolean): Promise<void> {- setupProjectMock(enforceIssueTitle);+async function renderSheet(+ enforceIssueTitle: boolean,+ options?: ProjectMockOptions+): Promise<void> {+ setupProjectMock(enforceIssueTitle, options);await act(async () => {root.render(createElement(CreateDatabaseSheet, {@@ -343,6 +378,21 @@ function getCreateButton(): HTMLButtonElement {) as HTMLButtonElement;}+async function selectIssueLabel(value: string): Promise<void> {+ const toggle = [...container.querySelectorAll("button")].find((b) =>+ b.textContent?.includes("common.select")+ ) as HTMLButtonElement;+ await act(async () => {+ toggle.click();+ });+ const option = [...container.querySelectorAll("button")].find(+ (b) => b !== toggle && b.textContent?.trim() === value+ ) as HTMLButtonElement;+ await act(async () => {+ option.click();+ });+}+async function flush(): Promise<void> {await act(async () => {await Promise.resolve();@@ -733,31 +783,20 @@ describe("CreateDatabaseSheet — enforceIssueTitle (BYT-9310)", () => {expect(getCreateButton().disabled).toBe(true);});- it("creates one Plan and one linked draft Issue with the exact payload", async () => {- mocks.getOrFetchProjectByName.mockImplementation(async (name: string) => ({- name,- enforceIssueTitle: false,+ it("creates one Plan and one linked non-draft Issue, then opens Issue Detail (BYT-10015)", async () => {+ await renderSheet(false, {issueLabels: [{ value: "required" }],forceIssueLabels: true,- }));- mocks.instancesByName[TEST_INSTANCE.name] = TEST_INSTANCE;- mocks.getOrFetchInstanceByName.mockResolvedValue(TEST_INSTANCE);- await act(async () => {- root.render(- createElement(CreateDatabaseSheet, {- open: true,- onClose: () => {},- projectName: "projects/foo",- })- );- await Promise.resolve();- await Promise.resolve();});await fillInstance();await fillDatabaseName("widgets");await flush();+ // forceIssueLabels: Create stays disabled until a label is selected.+ expect(getCreateButton().disabled).toBe(true);+ await selectIssueLabel("required");expect(getCreateButton().disabled).toBe(false);+await act(async () => {getCreateButton().click();await Promise.resolve();@@ -794,22 +833,34 @@ describe("CreateDatabaseSheet — enforceIssueTitle (BYT-9310)", () => {expect(mocks.createIssue).toHaveBeenCalledWith({issue: {creator: "users/[email protected]",- description: undefined,- draft: true,- labels: [],+ draft: false,+ labels: ["required"],plan: "projects/foo/plans/123",- status: 1,- title: "Create database 'widgets'",+ title: "quick-action.create-db 'widgets'",type: 1,},parent: "projects/foo",});expect(mocks.routerPush).toHaveBeenCalledWith({- name: "workspace.project.plan.detail",- params: { planId: "123", projectId: "foo" },+ name: "workspace.project.issue.detail",+ params: { issueId: "456", projectId: "foo" },});});+ it("blocks Create and warns when the project requires issue labels but has none configured", async () => {+ await renderSheet(false, {+ forceIssueLabels: true,+ });+ await fillInstance();+ await fillDatabaseName("widgets");+ await flush();++ const alert = container.querySelector("[role='alert']");+ expect(alert?.textContent).toContain("create-db.labels-misconfigured");+ expect(getCreateButton().disabled).toBe(true);+ expect(mocks.createPlan).not.toHaveBeenCalled();+ });+it("ignores a stale create completion after close, reopen, and project switch", async () => {setupProjectMock(false);const onClose = vi.fn();@@ -870,8 +921,8 @@ describe("CreateDatabaseSheet — enforceIssueTitle (BYT-9310)", () => {expect(getCreateButton().disabled).toBe(true);});- it("routes to the malformed Plan and surfaces the Issue error without retrying", async () => {- const failure = new Error("draft issue failed");+ it("routes to the orphaned Plan and surfaces the Issue error without retrying", async () => {+ const failure = new Error("issue failed");mocks.createIssue.mockRejectedValue(failure);await renderSheet(false);await fillInstance();@@ -892,13 +943,13 @@ describe("CreateDatabaseSheet — enforceIssueTitle (BYT-9310)", () => {});expect(mocks.pushNotification).toHaveBeenCalledWith(expect.objectContaining({- description: "Error: draft issue failed",+ description: "Error: issue failed",style: "CRITICAL",}));});- it("requires both create permissions but only warns when issue-update is missing", async () => {+ it("requires only the create permissions — bb.issues.update is not needed (BYT-10015)", async () => {mocks.permissions["bb.issues.update"] = false;await renderSheet(false);await fillInstance();@@ -906,10 +957,7 @@ describe("CreateDatabaseSheet — enforceIssueTitle (BYT-9310)", () => {await flush();expect(getCreateButton().disabled).toBe(false);- const permissionAlert = container.querySelector("[role='alert']");- expect(permissionAlert?.textContent).toContain(- "plan.draft-update-permission-required"- );+ expect(container.querySelector("[role='alert']")).toBeNull();mocks.permissions["bb.issues.create"] = false;await act(async () => {diff --git a/frontend/src/components/database/CreateDatabaseSheet.tsx b/frontend/src/components/database/CreateDatabaseSheet.tsxindex cc0c6f8915..5c85d621dc 100644--- a/frontend/src/components/database/CreateDatabaseSheet.tsx+++ b/frontend/src/components/database/CreateDatabaseSheet.tsx@@ -34,10 +34,6 @@ import {} from "@/components/ui/sheet";import { useCurrentUser } from "@/hooks/useAppState";import { useProjectByName } from "@/hooks/useProjectByName";-import {- createPlanWithDraftReview,- DraftReviewIssueCreationError,-} from "@/lib/plan/workflow";import { cn } from "@/lib/utils";import { pushNotification } from "@/stores";import { useAppStore } from "@/stores/app";@@ -50,6 +46,12 @@ import {import { Engine } from "@/types/proto-es/v1/common_pb";import type { Instance } from "@/types/proto-es/v1/instance_service_pb";import {+ CreateIssueRequestSchema,+ Issue_Type,+ IssueSchema,+} from "@/types/proto-es/v1/issue_service_pb";+import {+ CreatePlanRequestSchema,Plan_CreateDatabaseConfigSchema,Plan_SpecSchema,PlanSchema,@@ -58,6 +60,7 @@ import {enginesSupportCreateDatabase,extractPlanUID,extractProjectResourceName,+ getIssueRoute,instanceV1HasCollationAndCharacterSet,normalizeTitle,} from "@/utils";@@ -189,6 +192,8 @@ function CreateDatabaseForm({projectReactive !== undefined;const enforceIssueTitle =projectHydrated && (projectReactive?.enforceIssueTitle ?? false);+ const forceIssueLabels =+ projectHydrated && (projectReactive?.forceIssueLabels ?? false);const projectFetchRef = useRef(0);useEffect(() => {@@ -254,14 +259,12 @@ function CreateDatabaseForm({}, [databaseName, enforceIssueTitle, projectHydrated]);const projectIssueLabels = selectedProject?.issueLabels ?? [];- const [canCreateDraftReview, createPermissionReason] = usePermissionCheck(+ const labelsMisconfigured =+ forceIssueLabels && projectIssueLabels.length === 0;+ const [canCreateIssue, createPermissionReason] = usePermissionCheck(["bb.plans.create", "bb.issues.create"],projectReactive);- const [canUpdateIssue] = usePermissionCheck(- ["bb.issues.update"],- projectReactive- );const requireOwner =selectedInstance &&@@ -277,8 +280,10 @@ function CreateDatabaseForm({!isReservedName &&(!requireOwner || !!ownerName) &&projectHydrated &&- canCreateDraftReview &&- !(enforceIssueTitle && !normalizeTitle(title));+ canCreateIssue &&+ !(enforceIssueTitle && !normalizeTitle(title)) &&+ !labelsMisconfigured &&+ (!forceIssueLabels || issueLabels.length > 0);const instanceFetchRef = useRef(0);useEffect(() => {@@ -392,44 +397,61 @@ function CreateDatabaseForm({specs: [spec],creator: currentUser.name,});- const { plan: createdPlan } = await createPlanWithDraftReview({- createIssue: (request) =>- issueServiceClientConnect.createIssue(request),- createPlan: (request) => planServiceClientConnect.createPlan(request),- creator: `users/${currentUser.email}`,- labels: issueLabels,- parent: effectiveProjectName,- plan: planCreate,- });- if (!isSessionActive(sessionId)) return;-- onClose();- await router.push({- name: PROJECT_V1_ROUTE_PLAN_DETAIL,- params: {- projectId: extractProjectResourceName(createdPlan.name),- planId: extractPlanUID(createdPlan.name),- },- });- } catch (error: unknown) {- if (!isSessionActive(sessionId)) return;- if (error instanceof DraftReviewIssueCreationError) {+ // Create Database bypasses the draft review workflow (BYT-10015): the+ // plan gets a submitted issue immediately and the user lands on Issue+ // Detail. The rollout is still created on demand.+ const createdPlan = await planServiceClientConnect.createPlan(+ create(CreatePlanRequestSchema, {+ parent: effectiveProjectName,+ plan: planCreate,+ })+ );+ let createdIssue;+ try {+ createdIssue = await issueServiceClientConnect.createIssue(+ create(CreateIssueRequestSchema, {+ parent: effectiveProjectName,+ issue: create(IssueSchema, {+ creator: `users/${currentUser.email}`,+ draft: false,+ labels: issueLabels,+ plan: createdPlan.name,+ title: effectiveTitle,+ type: Issue_Type.DATABASE_CHANGE,+ }),+ })+ );+ } catch (error: unknown) {+ // The plan exists but its issue was not created. Land on Plan Detail+ // so the user can recover from there instead of orphaning the plan.+ if (!isSessionActive(sessionId)) return;onClose();await router.push({name: PROJECT_V1_ROUTE_PLAN_DETAIL,params: {- projectId: extractProjectResourceName(error.plan.name),- planId: extractPlanUID(error.plan.name),+ projectId: extractProjectResourceName(createdPlan.name),+ planId: extractPlanUID(createdPlan.name),},});+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("common.failed"),+ description: String(error),+ });+ return;}+ if (!isSessionActive(sessionId)) return;++ onClose();+ await router.push(getIssueRoute(createdIssue));+ } catch (error: unknown) {+ if (!isSessionActive(sessionId)) return;pushNotification({module: "bytebase",style: "CRITICAL",title: t("common.failed"),- description: String(- error instanceof DraftReviewIssueCreationError ? error.cause : error- ),+ description: String(error),});} finally {if (isSessionActive(sessionId)) {@@ -465,20 +487,22 @@ function CreateDatabaseForm({</FormField>)}- {selectedProject && projectIssueLabels.length > 0 && (- <IssueLabelSelect- labels={projectIssueLabels}- selected={issueLabels}- required={false}- onChange={setIssueLabels}- />- )}- {projectHydrated && !canUpdateIssue && (+ {labelsMisconfigured && (<Alertvariant="warning"- description={t("plan.draft-update-permission-required")}+ title={t("create-db.labels-misconfigured.title")}+ description={t("create-db.labels-misconfigured.description")}/>)}+ {selectedProject &&+ (projectIssueLabels.length > 0 || forceIssueLabels) && (+ <IssueLabelSelect+ labels={projectIssueLabels}+ selected={issueLabels}+ required={forceIssueLabels}+ onChange={setIssueLabels}+ />+ )}<FormFieldtitle={diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 1956e20dda..a2ae2541a0 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -496,6 +496,10 @@"cluster": "Cluster","database-owner-name": "Database owner name","issue-title": "Issue title",+ "labels-misconfigured": {+ "description": "This project requires issue labels, but no labels have been configured. Please contact the project owner to add labels before creating a database.",+ "title": "Issue labels required but not configured"+ },"new-collection-name": "New Collection Name","new-database-name": "New database name","reserved-db-error": "{{databaseName}} is a reserved name"diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex 170b2e206e..f2fdd01628 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -496,6 +496,10 @@"cluster": "Clúster","database-owner-name": "Nombre del propietario de la base de datos","issue-title": "Título del problema",+ "labels-misconfigured": {+ "description": "Este proyecto requiere etiquetas de incidencia, pero no se ha configurado ninguna etiqueta. Contacte con el propietario del proyecto para añadir etiquetas antes de crear una base de datos.",+ "title": "Se requieren etiquetas de incidencia pero no están configuradas"+ },"new-collection-name": "Nuevo Nombre de Colección","new-database-name": "Nuevo nombre de la base de datos","reserved-db-error": "{{databaseName}} es un nombre reservado"diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex cfbbe183fe..6a170f65ba 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -496,6 +496,10 @@"cluster": "集まる","database-owner-name": "データベース所有者","issue-title": "課題タイトル",+ "labels-misconfigured": {+ "description": "このプロジェクトはイシューラベルを必須にしていますが、ラベルが設定されていません。データベースを作成する前に、プロジェクトのオーナーに連絡してラベルを追加してください。",+ "title": "イシューラベルが必須ですが設定されていません"+ },"new-collection-name": "新しいコレクション名","new-database-name": "新しいデータベース名","reserved-db-error": "{{databaseName}} は予約された名前です"diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex 7bab61f145..04569493d0 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -496,6 +496,10 @@"cluster": "Cụm","database-owner-name": "Tên chủ sở hữu cơ sở dữ liệu","issue-title": "Tiêu đề vấn đề",+ "labels-misconfigured": {+ "description": "Dự án này yêu cầu nhãn vấn đề, nhưng chưa có nhãn nào được cấu hình. Vui lòng liên hệ chủ sở hữu dự án để thêm nhãn trước khi tạo cơ sở dữ liệu.",+ "title": "Dự án yêu cầu nhãn vấn đề nhưng chưa cấu hình"+ },"new-collection-name": "Tên bộ sưu tập mới","new-database-name": "Tên cơ sở dữ liệu mới","reserved-db-error": "{{databaseName}} là một tên dành riêng"diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex d4c733f467..3328903bcf 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -496,6 +496,10 @@"cluster": "集群","database-owner-name": "数据库所有者","issue-title": "工单标题",+ "labels-misconfigured": {+ "description": "此项目要求选择工单标签,但尚未配置任何标签。请联系项目所有者添加标签后再创建数据库。",+ "title": "项目要求工单标签但未配置"+ },"new-collection-name": "新集合名称","new-database-name": "新数据库名称","reserved-db-error": "{{databaseName}} 是一个预留名称"