Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: allow delete/add specs for created plans without rollout (#17199)
boojack6685f84a5e7f
diff --git a/backend/api/v1/plan_service.go b/backend/api/v1/plan_service.goindex f305daadc7..32be202a1f 100644--- a/backend/api/v1/plan_service.go+++ b/backend/api/v1/plan_service.go@@ -398,16 +398,31 @@ func (s *PlanService) UpdatePlan(ctx context.Context, request *connect.Request[v// Compare specs directlyoldSpecs := convertToPlanSpecs(oldPlan.Config.Specs)-removed, added, updated := diffSpecsDirectly(oldSpecs, req.Plan.Specs)- if len(removed) > 0 {- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("cannot remove specs from plan"))++ // Check if there are any changes at all.+ hasChanges := len(removed) > 0 || len(added) > 0 || len(updated) > 0+ if !hasChanges {+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("no specs updated"))}- if len(added) > 0 {- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("cannot add specs to plan"))++ // Validate spec modifications based on pipeline existence.+ if oldPlan.PipelineUID != nil {+ // Plan has a pipeline - only updates are allowed, no adding/removing.+ if len(removed) > 0 {+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("cannot remove specs from plan that has a pipeline"))+ }+ if len(added) > 0 {+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("cannot add specs to plan that has a pipeline"))+ }+ if len(updated) == 0 {+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("no specs updated"))+ }}- if len(updated) == 0 {- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("no specs updated"))++ // Validate the new specs+ if err := validateSpecs(req.Plan.Specs); err != nil {+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("failed to validate plan specs, error: %v", err))}oldSpecsByID := make(map[string]*v1pb.Plan_Spec)@@ -1187,13 +1202,14 @@ func (s *PlanService) getUserByIdentifier(ctx context.Context, identifier stringreturn user, nil}-// diffSpecs check if there are any specs removed, added or updated in the new plan.-// Only updating sheet is taken into account.+// diffSpecsDirectly checks if there are any specs removed, added or updated in the new plan.+// It performs a deep comparison of all spec fields using protocol buffer comparison.+// Returns (removed, added, updated) slices of specs.func diffSpecsDirectly(oldSpecs []*v1pb.Plan_Spec, newSpecs []*v1pb.Plan_Spec) ([]*v1pb.Plan_Spec, []*v1pb.Plan_Spec, []*v1pb.Plan_Spec) {- oldSpecsMap := make(map[string]*v1pb.Plan_Spec)- newSpecsMap := make(map[string]*v1pb.Plan_Spec)- var removed, added, updated []*v1pb.Plan_Spec+ oldSpecsMap := make(map[string]*v1pb.Plan_Spec, len(oldSpecs))+ newSpecsMap := make(map[string]*v1pb.Plan_Spec, len(newSpecs))+ // Build maps for efficient lookupfor _, spec := range oldSpecs {oldSpecsMap[spec.Id] = spec}@@ -1201,14 +1217,18 @@ func diffSpecsDirectly(oldSpecs []*v1pb.Plan_Spec, newSpecs []*v1pb.Plan_Spec) (newSpecsMap[spec.Id] = spec}+ var removed, added, updated []*v1pb.Plan_Spec++ // Find removed specs - specs in old but not in new.for _, spec := range oldSpecs {- if _, ok := newSpecsMap[spec.Id]; !ok {+ if _, exists := newSpecsMap[spec.Id]; !exists {removed = append(removed, spec)}}+ // Find added and updated specs - specs in new but not in old, or changed.for _, spec := range newSpecs {- if oldSpec, ok := oldSpecsMap[spec.Id]; !ok {+ if oldSpec, exists := oldSpecsMap[spec.Id]; !exists {added = append(added, spec)} else if !cmp.Equal(oldSpec, spec, protocmp.Transform()) {updated = append(updated, spec)diff --git a/frontend/src/components/Plan/components/HeaderSection/Actions/Actions.vue b/frontend/src/components/Plan/components/HeaderSection/Actions/Actions.vueindex e4e430f4a7..e94d858b1a 100644--- a/frontend/src/components/Plan/components/HeaderSection/Actions/Actions.vue+++ b/frontend/src/components/Plan/components/HeaderSection/Actions/Actions.vue@@ -34,6 +34,7 @@ import { head } from "lodash-es";import { useDialog } from "naive-ui";import { computed, ref } from "vue";import { useI18n } from "vue-i18n";+import { useSpecsValidation } from "@/components/Plan/components/common";import { usePlanContext } from "@/components/Plan/logic";import { useIssueReviewContext } from "@/components/Plan/logic/issue-review";import { useResourcePoller } from "@/components/Plan/logic/poller";@@ -76,6 +77,9 @@ const { project } = useCurrentProjectV1();const planStore = usePlanStore();const editorState = useEditorState();+// Use the validation hook for all specs+const { isSpecEmpty } = useSpecsValidation(plan.value.specs);+// Provide issue review context when an issue existsconst reviewContext = useIssueReviewContext();@@ -136,6 +140,7 @@ const availableActions = computed(() => {plan.value.state === State.ACTIVE &¤tUserEmail === extractUserId(plan.value.creator || "") &&hasProjectPermissionV2(project.value, "bb.issues.create");+if (canCreateIssue) {actions.push("ISSUE_CREATE");}@@ -223,7 +228,13 @@ const primaryAction = computed((): ActionConfig | undefined => {// ISSUE_CREATE is the highest priority when no issue existsif (actions.includes("ISSUE_CREATE")) {- return { action: "ISSUE_CREATE" };+ // Check if all specs have valid statements (not empty)+ const hasValidSpecs = !plan.value.specs.some((spec) => isSpecEmpty(spec));+ return {+ action: "ISSUE_CREATE",+ disabled: !hasValidSpecs,+ description: hasValidSpecs ? undefined : "Missing statement",+ };}// PLAN_REOPEN is primary when plan is deleteddiff --git a/frontend/src/components/Plan/components/HeaderSection/Actions/unified/UnifiedActionGroup.vue b/frontend/src/components/Plan/components/HeaderSection/Actions/unified/UnifiedActionGroup.vueindex 8c39aa7b20..a366b8c43c 100644--- a/frontend/src/components/Plan/components/HeaderSection/Actions/unified/UnifiedActionGroup.vue+++ b/frontend/src/components/Plan/components/HeaderSection/Actions/unified/UnifiedActionGroup.vue@@ -5,7 +5,7 @@v-if="primaryAction":action="primaryAction.action":disabled="disabled || primaryAction.disabled"- :disabled-tooltip="disabled ? disabledTooltip : undefined"+ :disabled-tooltip="disabled ? disabledTooltip : primaryAction.description"@perform-action="handleAction"/>@@ -81,8 +81,8 @@ const dropdownOptions = computed(() => {key: config.action,label: actionDisplayName(config.action),action: config.action,- disabled: config.disabled,- description: config.description,+ disabled: props.disabled || config.disabled,+ description: props.disabled ? props.disabledTooltip : config.description,}));});@@ -96,8 +96,10 @@ const renderDropdownOption = ({const actionOption = props.secondaryActions.find((config) => config.action === (option as any).key);- const disabled = actionOption?.disabled;- const description = actionOption?.description;+ const disabled = props.disabled || actionOption?.disabled;+ const description = props.disabled+ ? props.disabledTooltip+ : actionOption?.description;const errors = disabled? [description ||diff --git a/frontend/src/components/Plan/components/SpecDetailView/SpecListSection.vue b/frontend/src/components/Plan/components/SpecDetailView/SpecListSection.vueindex c698579f30..8a012ccd6d 100644--- a/frontend/src/components/Plan/components/SpecDetailView/SpecListSection.vue+++ b/frontend/src/components/Plan/components/SpecDetailView/SpecListSection.vue@@ -23,7 +23,7 @@*</span><NButton- v-if="isCreating && plan.specs.length > 1"+ v-if="canModifySpecs && plan.specs.length > 1"quaternarysize="tiny":title="$t('common.delete')"@@ -39,7 +39,7 @@<template #suffix><div class="pr-4"><NButton- v-if="isCreating"+ v-if="canModifySpecs"type="default"size="small"@click="showAddSpecDrawer = true"@@ -61,13 +61,17 @@</template><script setup lang="ts">+import { create } from "@bufbuild/protobuf";import { PlusIcon, XIcon } from "lucide-vue-next";import { NTabs, NTab, NButton, useDialog } from "naive-ui";-import { ref } from "vue";+import { ref, computed } from "vue";import { useI18n } from "vue-i18n";import { useRouter } from "vue-router";+import { planServiceClientConnect } from "@/grpcweb";import { PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL } from "@/router/dashboard/projectV1";+import { pushNotification } from "@/store";import type { Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";+import { UpdatePlanRequestSchema } from "@/types/proto-es/v1/plan_service_pb";import { usePlanContext } from "../../logic/context";import { getSpecTitle } from "../../logic/utils";import AddSpecDrawer from "../AddSpecDrawer.vue";@@ -83,6 +87,13 @@ const { isSpecEmpty } = useSpecsValidation(plan.value.specs);const showAddSpecDrawer = ref(false);+// Allow adding/removing specs when:+// 1. Plan is being created (isCreating = true), OR+// 2. Plan is created but rollout is empty (plan.rollout === "")+const canModifySpecs = computed(() => {+ return isCreating.value || plan.value.rollout === "";+});+const handleTabChange = (specId: string) => {if (selectedSpec.value.id !== specId) {gotoSpec(specId);@@ -92,6 +103,37 @@ const handleTabChange = (specId: string) => {const handleSpecCreated = async (spec: Plan_Spec) => {// Add the new spec to the plan.plan.value.specs.push(spec);++ // If the plan is not being created (already exists), call UpdatePlan API+ if (!isCreating.value) {+ try {+ const request = create(UpdatePlanRequestSchema, {+ plan: plan.value,+ updateMask: { paths: ["specs"] },+ });+ const response = await planServiceClientConnect.updatePlan(request);+ Object.assign(plan.value, response);+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("common.updated"),+ });+ } catch (error) {+ // If the API call fails, remove the spec from local state+ const specIndex = plan.value.specs.findIndex((s) => s.id === spec.id);+ if (specIndex >= 0) {+ plan.value.specs.splice(specIndex, 1);+ }+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("common.error"),+ description: `Failed to add spec: ${error}`,+ });+ return;+ }+ }+gotoSpec(spec.id);};@@ -113,16 +155,53 @@ const handleDeleteSpec = (spec: Plan_Spec) => {content: t("plan.spec.delete-change.content"),positiveText: t("common.delete"),negativeText: t("common.cancel"),- onPositiveClick: () => {+ onPositiveClick: async () => {+ if (plan.value.specs.length <= 1) {+ pushNotification({+ module: "bytebase",+ style: "WARN",+ title: "Cannot delete last spec",+ });+ return;+ }+const specIndex = plan.value.specs.findIndex((s) => s.id === spec.id);- if (specIndex >= 0) {- plan.value.specs.splice(specIndex, 1);+ if (specIndex < 0) return;- // If we deleted the currently selected spec, navigate to the first remaining spec- if (selectedSpec.value.id === spec.id && plan.value.specs.length > 0) {- gotoSpec(plan.value.specs[0].id);+ // Remove the spec from local state+ const removedSpec = plan.value.specs.splice(specIndex, 1)[0];++ // If the plan is not being created (already exists), call UpdatePlan API+ if (!isCreating.value) {+ try {+ const request = create(UpdatePlanRequestSchema, {+ plan: plan.value,+ updateMask: { paths: ["specs"] },+ });+ const response = await planServiceClientConnect.updatePlan(request);+ Object.assign(plan.value, response);+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("common.updated"),+ });+ } catch (error) {+ // If the API call fails, restore the spec to local state+ plan.value.specs.splice(specIndex, 0, removedSpec);+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("common.error"),+ description: `Failed to delete spec: ${error}`,+ });+ return;}}++ // If we deleted the currently selected spec, navigate to the first remaining spec+ if (selectedSpec.value.id === spec.id && plan.value.specs.length > 0) {+ gotoSpec(plan.value.specs[0].id);+ }},});};