Skip to content

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

feat: implement plan-only pages (#12071)

boojack702c17b2b59d
diff --git a/backend/api/v1/plan_service.go b/backend/api/v1/plan_service.go
index 315cebecea..0b36100853 100644
--- a/backend/api/v1/plan_service.go
+++ b/backend/api/v1/plan_service.go
@@ -207,6 +207,9 @@ func (s *PlanService) UpdatePlan(ctx context.Context, request *v1pb.UpdatePlanRe
if request.UpdateMask == nil {
return nil, status.Errorf(codes.InvalidArgument, "update_mask must be set")
}
+ if len(request.UpdateMask.Paths) == 0 {
+ return nil, status.Errorf(codes.InvalidArgument, "update_mask must not be empty")
+ }
user, ok := ctx.Value(common.UserContextKey).(*store.UserMessage)
if !ok {
return nil, status.Errorf(codes.Internal, "user not found")
@@ -258,6 +261,10 @@ func (s *PlanService) UpdatePlan(ctx context.Context, request *v1pb.UpdatePlanRe
description := request.Plan.Description
planUpdate.Description = &description
case "steps":
+ planUpdate.Config = &storepb.PlanConfig{
+ Steps: convertPlanSteps(request.Plan.Steps),
+ }
+
if _, err := GetPipelineCreate(ctx, s.store, s.licenseService, s.dbFactory, convertPlanSteps(request.Plan.GetSteps()), project); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "failed to get pipeline from the plan, please check you request, error: %v", err)
}
@@ -711,9 +718,6 @@ func (s *PlanService) UpdatePlan(ctx context.Context, request *v1pb.UpdatePlanRe
}
}
- planUpdate.Config = &storepb.PlanConfig{
- Steps: convertPlanSteps(request.Plan.Steps),
- }
if err := s.store.UpdatePlan(ctx, planUpdate); err != nil {
return nil, status.Errorf(codes.Internal, "failed to update plan %q: %v", request.Plan.Name, err)
}
diff --git a/backend/api/v1/rollout_service_converter.go b/backend/api/v1/rollout_service_converter.go
index 88bbe3200a..fa98c0889c 100644
--- a/backend/api/v1/rollout_service_converter.go
+++ b/backend/api/v1/rollout_service_converter.go
@@ -74,6 +74,7 @@ func convertToPlanSteps(steps []*storepb.PlanConfig_Step) []*v1pb.Plan_Step {
func convertToPlanStep(step *storepb.PlanConfig_Step) *v1pb.Plan_Step {
return &v1pb.Plan_Step{
+ Title: step.Title,
Specs: convertToPlanSpecs(step.Specs),
}
}
@@ -191,6 +192,7 @@ func convertPlanSteps(steps []*v1pb.Plan_Step) []*storepb.PlanConfig_Step {
func convertPlanStep(step *v1pb.Plan_Step) *storepb.PlanConfig_Step {
return &storepb.PlanConfig_Step{
+ Title: step.Title,
Specs: convertPlanSpecs(step.Specs),
}
}
diff --git a/frontend/src/components/IssueV1/logic/base.ts b/frontend/src/components/IssueV1/logic/base.ts
index 59eec27f2e..cf989101b2 100644
--- a/frontend/src/components/IssueV1/logic/base.ts
+++ b/frontend/src/components/IssueV1/logic/base.ts
@@ -209,8 +209,8 @@ export const useBaseIssueContext = (
return !issue.value.plan && !issue.value.planEntity;
});
const formatOnSave = computed({
- get: () => uiStateStore.issueFormatStatementOnSave,
- set: (value: boolean) => uiStateStore.setIssueFormatStatementOnSave(value),
+ get: () => uiStateStore.editorFormatStatementOnSave,
+ set: (value: boolean) => uiStateStore.setEditorFormatStatementOnSave(value),
});
return {
diff --git a/frontend/src/components/Plan/PlanDetailPage.vue b/frontend/src/components/Plan/PlanDetailPage.vue
new file mode 100644
index 0000000000..d16c1ce148
--- /dev/null
+++ b/frontend/src/components/Plan/PlanDetailPage.vue
@@ -0,0 +1,41 @@
+<template>
+ <div class="h-full flex flex-col">
+ <div class="border-b">
+ <HeaderSection />
+ </div>
+ <div class="flex-1 flex flex-row">
+ <div
+ class="flex-1 flex flex-col hide-scrollbar divide-y overflow-x-hidden"
+ >
+ <StepSection />
+ <SpecListSection />
+
+ <SQLCheckSection v-if="isCreating" />
+ <PlanCheckSection v-if="!isCreating" />
+
+ <StatementSection />
+ <DescriptionSection />
+ </div>
+ </div>
+ </div>
+</template>
+
+<script setup lang="ts">
+import { provideSQLCheckContext } from "../SQLCheck";
+import {
+ HeaderSection,
+ PlanCheckSection,
+ StatementSection,
+ DescriptionSection,
+ SQLCheckSection,
+ StepSection,
+ SpecListSection,
+} from "./components";
+import { usePlanContext, usePollPlan } from "./logic";
+
+const { isCreating } = usePlanContext();
+
+usePollPlan();
+
+provideSQLCheckContext();
+</script>
diff --git a/frontend/src/components/Plan/components/DescriptionSection/DescriptionSection.vue b/frontend/src/components/Plan/components/DescriptionSection/DescriptionSection.vue
new file mode 100644
index 0000000000..17ce73d2db
--- /dev/null
+++ b/frontend/src/components/Plan/components/DescriptionSection/DescriptionSection.vue
@@ -0,0 +1,189 @@
+<template>
+ <div class="px-4 py-2 flex flex-col gap-y-2">
+ <div class="flex items-center justify-between">
+ <span class="textlabel">
+ {{ title }}
+ </span>
+
+ <div v-if="!isCreating && allowEdit" class="flex items-center gap-x-2">
+ <NButton v-if="!state.isEditing" size="tiny" @click.prevent="beginEdit">
+ {{ $t("common.edit") }}
+ </NButton>
+ <NButton
+ v-if="state.isEditing"
+ size="tiny"
+ :disabled="state.description === plan.description"
+ :loading="state.isUpdating"
+ @click.prevent="saveEdit"
+ >
+ {{ $t("common.save") }}
+ </NButton>
+ <NButton
+ v-if="state.isEditing"
+ size="tiny"
+ quaternary
+ @click.prevent="cancelEdit"
+ >
+ {{ $t("common.cancel") }}
+ </NButton>
+ </div>
+ </div>
+
+ <div class="text-sm">
+ <NInput
+ v-if="isCreating || state.isEditing"
+ ref="inputRef"
+ v-model:value="state.description"
+ :placeholder="$t('issue.add-some-description')"
+ :autosize="{ minRows: 3, maxRows: 10 }"
+ :disabled="state.isUpdating"
+ :loading="state.isUpdating"
+ style="
+ width: 100%;
+ --n-placeholder-color: rgb(var(--color-control-placeholder));
+ "
+ type="textarea"
+ size="small"
+ @update:value="onDescriptionChange"
+ />
+ <div
+ v-else
+ class="min-h-[3rem] max-h-[12rem] whitespace-pre-wrap px-[10px] py-[4.5px] text-sm"
+ >
+ <template v-if="plan.description">
+ <iframe
+ v-if="plan.description"
+ ref="contentPreviewArea"
+ :srcdoc="renderedContent"
+ class="rounded-md w-full overflow-hidden"
+ />
+ </template>
+ <span v-else class="text-control-placeholder">
+ {{ $t("issue.add-some-description") }}
+ </span>
+ </div>
+ </div>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { NInput, NButton } from "naive-ui";
+import { computed, nextTick, reactive, ref, watch } from "vue";
+import { useI18n } from "vue-i18n";
+import { useRenderMarkdown } from "@/components/MarkdownEditor";
+import { planServiceClient } from "@/grpcweb";
+import { pushNotification, useCurrentUserV1 } from "@/store";
+import { Plan } from "@/types/proto/v1/plan_service";
+import { extractUserResourceName, hasProjectPermissionV2 } from "@/utils";
+import { usePlanContext } from "../../logic";
+
+type LocalState = {
+ isEditing: boolean;
+ isUpdating: boolean;
+ description: string;
+};
+
+const { t } = useI18n();
+const { isCreating, plan } = usePlanContext();
+const currentUser = useCurrentUserV1();
+const contentPreviewArea = ref<HTMLIFrameElement>();
+
+const state = reactive<LocalState>({
+ isEditing: false,
+ isUpdating: false,
+ description: plan.value.description,
+});
+
+const inputRef = ref<InstanceType<typeof NInput>>();
+
+const title = computed(() => {
+ return t("common.description");
+});
+
+const allowEdit = computed(() => {
+ if (isCreating.value) {
+ return true;
+ }
+
+ if (extractUserResourceName(plan.value.creator) === currentUser.value.email) {
+ // Allowed if current user is the assignee or creator.
+ return true;
+ }
+
+ if (
+ hasProjectPermissionV2(
+ plan.value.projectEntity,
+ currentUser.value,
+ "bb.plans.update"
+ )
+ ) {
+ // Allowed if current has plan update permission in the project
+ return true;
+ }
+ return false;
+});
+
+const onDescriptionChange = (description: string) => {
+ if (isCreating.value) {
+ plan.value.description = description;
+ }
+};
+
+const beginEdit = () => {
+ state.description = plan.value.description;
+ state.isEditing = true;
+ nextTick(() => {
+ inputRef.value?.focus();
+ });
+};
+
+const saveEdit = async () => {
+ try {
+ state.isUpdating = true;
+ const planPatch = Plan.fromJSON({
+ ...plan.value,
+ description: state.description,
+ });
+ const updated = await planServiceClient.updatePlan({
+ plan: planPatch,
+ updateMask: ["description"],
+ });
+ Object.assign(plan.value, updated);
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.updated"),
+ });
+ state.isEditing = false;
+ } finally {
+ state.isUpdating = false;
+ }
+};
+
+const cancelEdit = () => {
+ state.description = plan.value.description;
+ state.isEditing = false;
+};
+
+const { renderedContent } = useRenderMarkdown(
+ computed(() => plan.value.description),
+ contentPreviewArea,
+ computed(() => plan.value.projectEntity)
+);
+
+// Reset the edit state after creating the plan.
+watch(isCreating, (curr, prev) => {
+ if (!curr && prev) {
+ state.isEditing = false;
+ }
+});
+
+watch(
+ () => plan.value,
+ (plan) => {
+ if (state.isEditing) return;
+ state.description = plan.description;
+ },
+ { immediate: true }
+);
+</script>
diff --git a/frontend/src/components/Plan/components/DescriptionSection/index.ts b/frontend/src/components/Plan/components/DescriptionSection/index.ts
new file mode 100644
index 0000000000..4652881be2
--- /dev/null
+++ b/frontend/src/components/Plan/components/DescriptionSection/index.ts
@@ -0,0 +1,3 @@
+import DescriptionSection from "./DescriptionSection.vue";
+
+export default DescriptionSection;
diff --git a/frontend/src/components/Plan/components/HeaderSection/Actions/Actions.vue b/frontend/src/components/Plan/components/HeaderSection/Actions/Actions.vue
new file mode 100644
index 0000000000..d2228d9e56
--- /dev/null
+++ b/frontend/src/components/Plan/components/HeaderSection/Actions/Actions.vue
@@ -0,0 +1,21 @@
+<template>
+ <div class="flex flex-col items-end">
+ <CreateButton v-if="actionType === 'CREATE'" />
+ </div>
+</template>
+
+<script setup lang="ts">
+import { asyncComputed } from "@vueuse/core";
+import { usePlanContext } from "@/components/Plan/logic";
+import { CreateButton } from "./create";
+
+type ActionType = "CREATE";
+
+const { isCreating } = usePlanContext();
+
+const actionType = asyncComputed(async (): Promise<ActionType | undefined> => {
+ if (isCreating.value) {
+ return "CREATE";
+ }
+}, undefined);
+</script>
diff --git a/frontend/src/components/Plan/components/HeaderSection/Actions/create/CreateButton.vue b/frontend/src/components/Plan/components/HeaderSection/Actions/create/CreateButton.vue
new file mode 100644
index 0000000000..6fef8ab571
--- /dev/null
+++ b/frontend/src/components/Plan/components/HeaderSection/Actions/create/CreateButton.vue
@@ -0,0 +1,218 @@
+<template>
+ <NTooltip :disabled="planCreateErrorList.length === 0" placement="top">
+ <template #trigger>
+ <NButton
+ type="primary"
+ size="medium"
+ tag="div"
+ :disabled="planCreateErrorList.length > 0 || loading"
+ :loading="loading"
+ @click="doCreatePlan"
+ >
+ {{ loading ? $t("common.creating") : $t("common.create") }}
+ </NButton>
+ </template>
+
+ <template #default>
+ <ErrorList :errors="planCreateErrorList" />
+ </template>
+ </NTooltip>
+
+ <!-- prevent clicking the page when creating in progress -->
+ <div
+ v-if="loading"
+ v-zindexable="{ enabled: true }"
+ class="fixed inset-0 pointer-events-auto flex flex-col items-center justify-center"
+ @click.stop.prevent
+ />
+</template>
+
+<script setup lang="ts">
+import { NTooltip, NButton } from "naive-ui";
+import { zindexable as vZindexable } from "vdirs";
+import { computed, nextTick, ref } from "vue";
+import { useI18n } from "vue-i18n";
+import { useRouter } from "vue-router";
+import formatSQL from "@/components/MonacoEditor/sqlFormatter";
+import { ErrorList } from "@/components/Plan/components/common";
+import {
+ databaseEngineForSpec,
+ getLocalSheetByName,
+ isValidSpec,
+} from "@/components/Plan/logic";
+import { usePlanContext } from "@/components/Plan/logic";
+import { useSQLCheckContext } from "@/components/SQLCheck";
+import { planServiceClient } from "@/grpcweb";
+import { PROJECT_V1_ROUTE_PLAN_DETAIL } from "@/router/dashboard/projectV1";
+import { useCurrentUserV1, useDatabaseV1Store, useSheetV1Store } from "@/store";
+import { dialectOfEngineV1, languageOfEngineV1 } from "@/types";
+import type { Plan_ExportDataConfig } from "@/types/proto/v1/plan_service";
+import { type Plan_ChangeDatabaseConfig } from "@/types/proto/v1/plan_service";
+import type { Sheet } from "@/types/proto/v1/sheet_service";
+import type { ComposedPlan } from "@/types/v1/issue/plan";
+import {
+ extractDeploymentConfigName,
+ extractProjectResourceName,
+ extractSheetUID,
+ getSheetStatement,
+ hasProjectPermissionV2,
+ planSlug,
+ setSheetStatement,
+} from "@/utils";
+
+const MAX_FORMATTABLE_STATEMENT_SIZE = 10000; // 10K characters
+
+const { t } = useI18n();
+const router = useRouter();
+const { plan, formatOnSave } = usePlanContext();
+const { runSQLCheck } = useSQLCheckContext();
+const sheetStore = useSheetV1Store();
+const me = useCurrentUserV1();
+const loading = ref(false);
+
+const planCreateErrorList = computed(() => {
+ const errorList: string[] = [];
+ if (
+ !hasProjectPermissionV2(
+ plan.value.projectEntity,
+ me.value,
+ "bb.plans.create"
+ )
+ ) {
+ errorList.push(t("common.missing-permission"));
+ }
+ if (!plan.value.title.trim()) {
+ errorList.push("Missing plan title");
+ }
+ if (
+ !plan.value.steps.every((step) =>
+ step.specs.every((spec) => isValidSpec(spec))
+ )
+ ) {
+ errorList.push("Missing SQL statement in some specs");
+ }
+
+ return errorList;
+});
+
+const doCreatePlan = async () => {
+ loading.value = true;
+ const check = runSQLCheck.value;
+ if (check && !(await check())) {
+ loading.value = false;
+ return;
+ }
+
+ try {
+ await createSheets();
+ const createdPlan = await planServiceClient.createPlan({
+ parent: plan.value.project,
+ plan: plan.value,
+ });
+ if (!createdPlan) return;
+
+ const composedPlan: ComposedPlan = {
+ ...plan.value,
+ ...createdPlan,
+ };
+
+ nextTick(() => {
+ router.push({
+ name: PROJECT_V1_ROUTE_PLAN_DETAIL,
+ params: {
+ projectId: extractProjectResourceName(composedPlan.project),
+ planSlug: planSlug(composedPlan.title, composedPlan.uid),
+ },
+ });
+ });
+
+ return composedPlan;
+ } catch {
+ loading.value = false;
+ }
+};
+
+// Create sheets for spec configs and update their resource names.
+const createSheets = async () => {
+ const steps = plan.value.steps ?? [];
+ const flattenSpecList = steps.flatMap((step) => {
+ return step.specs;
+ });
+
+ const configWithSheetList: (
+ | Plan_ChangeDatabaseConfig
+ | Plan_ExportDataConfig
+ )[] = [];
+ const pendingCreateSheetMap = new Map<string, Sheet>();
+
+ for (let i = 0; i < flattenSpecList.length; i++) {
+ const spec = flattenSpecList[i];
+ const config = spec.changeDatabaseConfig || spec.exportDataConfig;
+ if (!config) continue;
+ configWithSheetList.push(config);
+ if (pendingCreateSheetMap.has(config.sheet)) continue;
+ const uid = extractSheetUID(config.sheet);
+ if (uid.startsWith("-")) {
+ // The sheet is pending create
+ const sheet = getLocalSheetByName(config.sheet);
+ sheet.database = config.target;
+ const engine = await databaseEngineForSpec(
+ plan.value.projectEntity,
+ spec
+ );
+ sheet.engine = engine;
+ pendingCreateSheetMap.set(sheet.name, sheet);
+
+ await maybeFormatSQL(sheet, sheet.database);
+ }
+ }
+ const pendingCreateSheetList = Array.from(pendingCreateSheetMap.values());
+ const sheetNameMap = new Map<string, string>();
+ for (let i = 0; i < pendingCreateSheetList.length; i++) {
+ const sheet = pendingCreateSheetList[i];
+ if (extractDeploymentConfigName(sheet.database)) {
+ // If a sheet's target is a deploymentConfig, it should be unset
+ // since it actually doesn't belongs to any exact database.
+ sheet.database = "";
+ }
+ sheet.title = plan.value.title;
+ const createdSheet = await sheetStore.createSheet(
+ plan.value.project,
+ sheet
+ );
+ sheetNameMap.set(sheet.name, createdSheet.name);
+ }
+ configWithSheetList.forEach((config) => {
+ const uid = extractSheetUID(config.sheet);
+ if (uid.startsWith("-")) {
+ config.sheet = sheetNameMap.get(config.sheet) ?? "";
+ }
+ });
+};
+
+const maybeFormatSQL = async (sheet: Sheet, target: string) => {
+ if (!formatOnSave.value) {
+ return;
+ }
+ const db = useDatabaseV1Store().getDatabaseByName(target);
+ if (!db) {
+ return;
+ }
+ const language = languageOfEngineV1(db.instanceEntity.engine);
+ if (language !== "sql") {
+ return;
+ }
+
+ const dialect = dialectOfEngineV1(db.instanceEntity.engine);
+ const statement = getSheetStatement(sheet);
+ if (statement.length > MAX_FORMATTABLE_STATEMENT_SIZE) {
+ return;
+ }
+ const { error, data: formatted } = await formatSQL(statement, dialect);
+ if (error) {
+ return;
+ }
+
+ setSheetStatement(sheet, formatted);
+};
+</script>
diff --git a/frontend/src/components/Plan/components/HeaderSection/Actions/create/index.ts b/frontend/src/components/Plan/components/HeaderSection/Actions/create/index.ts
new file mode 100644
index 0000000000..b30ba24e7e
--- /dev/null
+++ b/frontend/src/components/Plan/components/HeaderSection/Actions/create/index.ts
@@ -0,0 +1,3 @@
+import CreateButton from "./CreateButton.vue";
+
+export { CreateButton };
diff --git a/frontend/src/components/Plan/components/HeaderSection/Actions/index.ts b/frontend/src/components/Plan/components/HeaderSection/Actions/index.ts
new file mode 100644
index 0000000000..9793717924
--- /dev/null
+++ b/frontend/src/components/Plan/components/HeaderSection/Actions/index.ts
@@ -0,0 +1,3 @@
+import Actions from "./Actions.vue";
+
+export default Actions;
diff --git a/frontend/src/components/Plan/components/HeaderSection/HeaderSection.vue b/frontend/src/components/Plan/components/HeaderSection/HeaderSection.vue
new file mode 100644
index 0000000000..c241ae62bc
--- /dev/null
+++ b/frontend/src/components/Plan/components/HeaderSection/HeaderSection.vue
@@ -0,0 +1,18 @@
+<template>
+ <div
+ class="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-2 py-2 px-4"
+ >
+ <div class="flex-1 flex items-center gap-x-2">
+ <Title />
+ </div>
+
+ <div class="flex flex-row items-center justify-end">
+ <Actions />
+ </div>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import Actions from "./Actions";
+import Title from "./Title.vue";
+</script>
diff --git a/frontend/src/components/Plan/components/HeaderSection/Title.vue b/frontend/src/components/Plan/components/HeaderSection/Title.vue
new file mode 100644
index 0000000000..debbb07409
--- /dev/null
+++ b/frontend/src/components/Plan/components/HeaderSection/Title.vue
@@ -0,0 +1,148 @@
+<template>
+ <div class="flex-1">
+ <NInput
+ :value="state.title"
+ :style="style"
+ :loading="state.isUpdating"
+ :disabled="!allowEdit || state.isUpdating"
+ size="medium"
+ required
+ class="bb-plan-title-input"
+ @focus="state.isEditing = true"
+ @blur="onBlur"
+ @keyup.enter="onEnter"
+ @update:value="onUpdateValue"
+ />
+ </div>
+</template>
+
+<script setup lang="ts">
+import { NInput } from "naive-ui";
+import type { CSSProperties } from "vue";
+import { computed, reactive, watch } from "vue";
+import { useI18n } from "vue-i18n";
+import { planServiceClient } from "@/grpcweb";
+import { pushNotification, useCurrentUserV1 } from "@/store";
+import { Plan } from "@/types/proto/v1/plan_service";
+import { extractUserResourceName, hasProjectPermissionV2 } from "@/utils";
+import { usePlanContext } from "../../logic";
+
+type ViewMode = "EDIT" | "VIEW";
+
+const { t } = useI18n();
+const currentUser = useCurrentUserV1();
+const { isCreating, plan } = usePlanContext();
+
+const state = reactive({
+ isEditing: false,
+ isUpdating: false,
+ title: plan.value.title,
+});
+
+const viewMode = computed((): ViewMode => {
+ if (isCreating.value) return "EDIT";
+ return state.isEditing ? "EDIT" : "VIEW";
+});
+
+const style = computed(() => {
+ const style: CSSProperties = {
+ cursor: "default",
+ "--n-color-disabled": "transparent",
+ "--n-font-size": "18px",
+ "font-weight": "bold",
+ };
+ const border =
+ viewMode.value === "EDIT"
+ ? "1px solid rgb(var(--color-control-border))"
+ : "none";
+ style["--n-border"] = border;
+ style["--n-border-disabled"] = border;
+
+ return style;
+});
+
+const allowEdit = computed(() => {
+ if (isCreating.value) {
+ return true;
+ }
+
+ if (extractUserResourceName(plan.value.creator) === currentUser.value.email) {
+ // Allowed if current user is the assignee or creator.
+ return true;
+ }
+
+ if (
+ hasProjectPermissionV2(
+ plan.value.projectEntity,
+ currentUser.value,
+ "bb.plans.update"
+ )
+ ) {
+ // Allowed if current has plan update permission in the project
+ return true;
+ }
+ return false;
+});
+
+const onBlur = async () => {
+ const cleanup = () => {
+ state.isEditing = false;
+ state.isUpdating = false;
+ };
+
+ if (isCreating.value) {
+ cleanup();
+ return;
+ }
+ if (state.title === plan.value.title) {
+ cleanup();
+ return;
+ }
+ try {
+ state.isUpdating = true;
+ const planPatch = Plan.fromJSON({
+ ...plan.value,
+ title: state.title,
+ });
+ const updated = await planServiceClient.updatePlan({
+ plan: planPatch,
+ updateMask: ["title"],
+ });
+ Object.assign(plan.value, updated);
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.updated"),
+ });
+ } finally {
+ cleanup();
+ }
+};
+
+const onEnter = (e: Event) => {
+ const input = e.target as HTMLInputElement;
+ input.blur();
+};
+
+const onUpdateValue = (title: string) => {
+ state.title = title;
+ if (isCreating.value) {
+ plan.value.title = title;
+ }
+};
+
+watch(
+ () => plan.value.title,
+ (title) => {
+ state.title = title;
+ }
+);
+</script>
+
+<style>
+.bb-plan-title-input input {
+ cursor: text !important;
+ color: var(--n-text-color) !important;
+ text-decoration-color: var(--n-text-color) !important;
+}
+</style>
diff --git a/frontend/src/components/Plan/components/HeaderSection/index.ts b/frontend/src/components/Plan/components/HeaderSection/index.ts
new file mode 100644
index 0000000000..3843a93df5
--- /dev/null
+++ b/frontend/src/components/Plan/components/HeaderSection/index.ts
@@ -0,0 +1,3 @@
+import HeaderSection from "./HeaderSection.vue";
+
+export default HeaderSection;
diff --git a/frontend/src/components/Plan/components/PlanCheckSection/PlanCheckBar/PlanCheckBadge.vue b/frontend/src/components/Plan/components/PlanCheckSection/PlanCheckBar/PlanCheckBadge.vue
new file mode 100644
index 0000000000..7068f5b888
--- /dev/null
+++ b/frontend/src/components/Plan/components/PlanCheckSection/PlanCheckBar/PlanCheckBadge.vue
@@ -0,0 +1,155 @@
+<template>
+ <button
+ class="inline-flex items-center px-3 leading-6 rounded-full text-sm border"
+ :class="buttonClasses"
+ @click="clickable && $emit('click')"
+ >
+ <template v-if="status === PlanCheckRun_Status.RUNNING">
+ <TaskSpinner class="-ml-1 mr-1.5 h-4 w-4 text-info" />
+ </template>
+ <template v-else-if="status === PlanCheckRun_Status.DONE">
+ <template v-if="resultStatus === PlanCheckRun_Result_Status.SUCCESS">
+ <heroicons-outline:check
+ class="-ml-1 mr-1.5 mt-0.5 h-4 w-4 text-success"
+ />
+ </template>
+ <template v-else-if="resultStatus === PlanCheckRun_Result_Status.WARNING">
+ <heroicons-outline:exclamation
+ class="-ml-1 mr-1.5 mt-0.5 h-4 w-4 text-warning"
+ />
+ </template>
+ <template v-else-if="resultStatus === PlanCheckRun_Result_Status.ERROR">
+ <span class="mr-1.5 font-medium text-error" aria-hidden="true">
+ !
+ </span>
+ </template>
+ </template>
+ <template v-else-if="status === PlanCheckRun_Status.FAILED">
+ <span class="mr-1.5 font-medium text-error" aria-hidden="true"> ! </span>
+ </template>
+ <template v-else-if="status === PlanCheckRun_Status.CANCELED">
+ <heroicons-outline:ban class="-ml-1 mr-1.5 mt-0.5 h-4 w-4 text-control" />
+ </template>
+
+ <span>{{ name }}</span>
+ </button>
+</template>
+
+<script setup lang="ts">
+import { maxBy } from "lodash-es";
+import { computed } from "vue";
+import { useI18n } from "vue-i18n";
+import { planCheckRunResultStatus } from "@/components/Plan/logic";
+import type { PlanCheckRun } from "@/types/proto/v1/plan_service";
+import {
+ PlanCheckRun_Result_Status,
+ PlanCheckRun_Status,
+ PlanCheckRun_Type,
+} from "@/types/proto/v1/plan_service";
+import { TaskSpinner } from "../../common";
+
+const props = defineProps<{
+ planCheckRunList: PlanCheckRun[];
+ type: PlanCheckRun_Type;
+ clickable?: boolean;
+ selected?: boolean;
+}>();
+
+defineEmits<{
+ (event: "click"): void;
+}>();
+
+const { t } = useI18n();
+
+const latestPlanCheckRun = computed(() => {
+ return maxBy(props.planCheckRunList, (check) => Number(check.uid))!;
+});
+
+const status = computed(() => {
+ return latestPlanCheckRun.value.status;
+});
+
+const resultStatus = computed(() => {
+ return planCheckRunResultStatus(latestPlanCheckRun.value);
+});
+
+const buttonClasses = computed(() => {
+ let bgColor = "";
+ let textColor = "";
+ switch (status.value) {
+ case PlanCheckRun_Status.RUNNING:
+ bgColor = "bg-blue-100";
+ textColor = "text-blue-800";
+ break;
+ case PlanCheckRun_Status.FAILED:
+ bgColor = "bg-red-100";
+ textColor = "text-red-800";
+ break;
+ case PlanCheckRun_Status.CANCELED:
+ bgColor = "bg-yellow-100";
+ textColor = "text-yellow-800";
+ break;
+ case PlanCheckRun_Status.DONE:
+ switch (resultStatus.value) {
+ case PlanCheckRun_Result_Status.SUCCESS:
+ bgColor = "bg-gray-100";
+ textColor = "text-gray-800";
+ break;
+ case PlanCheckRun_Result_Status.WARNING:
+ bgColor = "bg-yellow-100";
+ textColor = "text-yellow-800";
+ break;
+ case PlanCheckRun_Result_Status.ERROR:
+ bgColor = "bg-red-100";
+ textColor = "text-red-800";
+ break;
+ }
+ break;
+ }
+
+ const styleList: string[] = [textColor];
+ if (props.clickable) {
+ styleList.push("cursor-pointer");
+ if (props.selected) {
+ styleList.push("shadow", "font-medium", "border-control-border");
+ } else {
+ styleList.push(bgColor, "hover:opacity-80", "border-transparent");
+ }
+ } else {
+ styleList.push(bgColor);
+ styleList.push("cursor-default");
+ }
+ styleList.push("cursor-pointer");
+ styleList.push(bgColor);
+
+ return styleList.join(" ");
+});
+
+// Defines the mapping from PlanCheckRun_Type to an i18n resource keypath
+const PlanCheckRunTypeNameDict = new Map<PlanCheckRun_Type, string>([
+ [PlanCheckRun_Type.DATABASE_STATEMENT_FAKE_ADVISE, "task.check-type.fake"],
+ [
+ PlanCheckRun_Type.DATABASE_STATEMENT_COMPATIBILITY,
+ "task.check-type.compatibility",
+ ],
+ [PlanCheckRun_Type.DATABASE_STATEMENT_ADVISE, "task.check-type.sql-review"],
+ [PlanCheckRun_Type.DATABASE_STATEMENT_TYPE, "task.check-type.statement-type"],
+ [PlanCheckRun_Type.DATABASE_CONNECT, "task.check-type.connection"],
+ [PlanCheckRun_Type.DATABASE_GHOST_SYNC, "task.check-type.ghost-sync"],
+ [
+ PlanCheckRun_Type.DATABASE_STATEMENT_SUMMARY_REPORT,
+ "task.check-type.summary-report",
+ ],
+]);
+
+const name = computed(() => {
+ const { type } = latestPlanCheckRun.value;
+ const has = PlanCheckRunTypeNameDict.has(type);
+ console.assert(has, `Missing PlanCheckType name of "${type}"`);
+ if (has) {
+ const key = PlanCheckRunTypeNameDict.get(type)!;
+ return t(key);
+ }
+ return type;
+});
+</script>
diff --git a/frontend/src/components/Plan/components/PlanCheckSection/PlanCheckBar/PlanCheckBadgeBar.vue b/frontend/src/components/Plan/components/PlanCheckSection/PlanCheckBar/PlanCheckBadgeBar.vue
new file mode 100644
index 0000000000..a853ead435
--- /dev/null
+++ b/frontend/src/components/Plan/components/PlanCheckSection/PlanCheckBar/PlanCheckBadgeBar.vue
@@ -0,0 +1,58 @@
+<template>
+ <div class="flex items-center flex-wrap gap-2 flex-1">
+ <PlanCheckBadge
+ v-for="group in planCheckRunsGroupByType"
+ :key="group.type"
+ :type="group.type"
+ :clickable="true"
+ :selected="group.type === selectedType"
+ :plan-check-run-list="group.list"
+ @click="$emit('select-type', group.type)"
+ />
+ <!-- Default slot for other actions -->
+ <slot></slot>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { orderBy } from "lodash-es";
+import { computed } from "vue";
+import type { PlanCheckRun } from "@/types/proto/v1/plan_service";
+import { PlanCheckRun_Type } from "@/types/proto/v1/plan_service";
+import { groupBy } from "@/utils/collections";
+import PlanCheckBadge from "./PlanCheckBadge.vue";
+
+const props = defineProps<{
+ planCheckRunList: PlanCheckRun[];
+ selectedType?: PlanCheckRun_Type;
+}>();
+
+defineEmits<{
+ (event: "select-type", type: PlanCheckRun_Type): void;
+}>();
+
+const planCheckRunsGroupByType = computed(() => {
+ const groups = groupBy(props.planCheckRunList, (checkRun) => checkRun.type);
+ const list = Array.from(groups.entries()).map(([type, list]) => ({
+ type,
+ list,
+ }));
+ // Sort by pre-defined orders
+ // If an item's order is not defined, put it behind
+ return orderBy(
+ list,
+ [(group) => PlanCheckTypeOrderDict.get(group.type) ?? 99999],
+ "asc"
+ );
+});
+
+const PlanCheckTypeOrderList: PlanCheckRun_Type[] = [
+ PlanCheckRun_Type.DATABASE_STATEMENT_COMPATIBILITY,
+ PlanCheckRun_Type.DATABASE_STATEMENT_TYPE,
+ PlanCheckRun_Type.DATABASE_CONNECT,
+ PlanCheckRun_Type.DATABASE_STATEMENT_ADVISE,
+];
+const PlanCheckTypeOrderDict = new Map<PlanCheckRun_Type, number>(
+ PlanCheckTypeOrderList.map((type, order) => [type, order])
+);
+</script>
diff --git a/frontend/src/components/Plan/components/PlanCheckSection/PlanCheckBar/PlanCheckBar.vue b/frontend/src/components/Plan/components/PlanCheckSection/PlanCheckBar/PlanCheckBar.vue
new file mode 100644
index 0000000000..4526cc9851
--- /dev/null
+++ b/frontend/src/components/Plan/components/PlanCheckSection/PlanCheckBar/PlanCheckBar.vue
@@ -0,0 +1,42 @@
+<template>
+ <div class="w-full flex flex-col items-start gap-4">
+ <div class="w-full flex flex-row justify-between items-center">
+ <div class="textlabel h-[26px] inline-flex items-center">
+ {{ $t("task.task-checks") }}
+ </div>
+
+ <div class="flex justify-end items-center shrink-0">
+ <PlanCheckRunButton v-if="allowRunChecks" @run-checks="runChecks" />
+ </div>
+ </div>
+
+ <PlanCheckPanel :plan-check-run-list="planCheckRunList" />
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { usePlanContext } from "@/components/Plan/logic";
+import { planServiceClient } from "@/grpcweb";
+import type { PlanCheckRun } from "@/types/proto/v1/plan_service";
+import PlanCheckPanel from "./PlanCheckPanel.vue";
+import PlanCheckRunButton from "./PlanCheckRunButton.vue";
+
+withDefaults(
+ defineProps<{
+ allowRunChecks?: boolean;
+ planCheckRunList?: PlanCheckRun[];
+ }>(),
+ {
+ allowRunChecks: true,
+ planCheckRunList: () => [],
+ }
+);
+
+const { plan } = usePlanContext();
+
+const runChecks = () => {
+ planServiceClient.runPlanChecks({
+ name: plan.value.name,
+ });
+};
+</script>
diff --git a/frontend/src/components/Plan/components/PlanCheckSection/PlanCheckBar/PlanCheckDetail.vue b/frontend/src/components/Plan/components/PlanCheckSection/PlanCheckBar/PlanCheckDetail.vue
new file mode 100644
index 0000000000..d7f73a59bc
--- /dev/null
+++ b/frontend/src/components/Plan/components/PlanCheckSection/PlanCheckBar/PlanCheckDetail.vue
@@ -0,0 +1,338 @@
+<template>
+ <div class="space-y-3 divide-y pb-4 px-2">
+ <div
+ v-for="(row, i) in tableRows"
+ :key="i"
+ class="pt-3 first:pt-2 space-y-2"
+ >
+ <div class="flex items-center space-x-3">
+ <div
+ class="relative w-5 h-5 flex flex-shrink-0 items-center justify-center rounded-full select-none"
+ :class="statusIconClass(row.checkResult.status)"
+ >
+ <template
+ v-if="row.checkResult.status === PlanCheckRun_Result_Status.SUCCESS"
+ >
+ <heroicons-solid:check class="w-4 h-4" />
+ </template>
+ <template
+ v-if="row.checkResult.status === PlanCheckRun_Result_Status.WARNING"
+ >
+ <heroicons-outline:exclamation class="h-4 w-4" />
+ </template>
+ <template
+ v-else-if="
+ row.checkResult.status === PlanCheckRun_Result_Status.ERROR
+ "
+ >
+ <span class="text-white font-medium text-base" aria-hidden="true">
+ !
+ </span>
+ </template>
+ </div>
+ <div v-if="showCategoryColumn" class="shrink-0">
+ {{ row.category }}
+ </div>
+ <div class="font-semibold">{{ row.title }}</div>
+ </div>
+ <div class="textinfolabel">
+ <span>{{ row.checkResult.content }}</span>
+ <template v-if="row.checkResult.sqlReviewReport?.detail">
+ <span
+ class="ml-1 normal-link"
+ @click="
+ state.activeResultDefinition =
+ row.checkResult.sqlReviewReport!.detail
+ "
+ >{{ $t("sql-review.view-definition") }}</span
+ >
+ <span class="border-r border-control-border ml-1"></span>
+ </template>
+ <template
+ v-if="
+ row.checkResult.sqlReviewReport &&
+ getActiveRule(row.checkResult.title)
+ "
+ >
+ <span
+ class="ml-1 normal-link"
+ @click="setActiveRule(row.checkResult.title)"
+ >{{ $t("sql-review.rule-detail") }}</span
+ >
+ <span class="border-r border-control-border ml-1"></span>
+ </template>
+ <template v-if="row.checkResult.sqlSummaryReport">
+ {{ row.checkResult.sqlSummaryReport.affectedRows }}
+ </template>
+
+ <HideInStandaloneMode>
+ <a
+ v-if="row.link"
+ class="ml-1 normal-link"
+ :href="row.link.url"
+ :target="row.link.target"
+ >
+ {{ row.link.title }}
+ </a>
+ </HideInStandaloneMode>
+
+ <!-- Only show the error line for latest plan check run -->
+ <template v-if="isLatest && row.checkResult.sqlReviewReport?.line">
+ <span class="border-r border-control-border ml-1"></span>
+ <span
+ class="ml-1 normal-link"
+ @click="
+ handleClickPlanCheckDetailLine(
+ row.checkResult.sqlReviewReport!.line
+ )
+ "
+ >
+ L{{ row.checkResult.sqlReviewReport.line }}
+ </span>
+ </template>
+
+ <slot name="row-extra" :row="row" />
+ </div>
+ </div>
+ </div>
+
+ <SQLRuleEditDialog
+ v-if="state.activeRule"
+ :editable="false"
+ :rule="state.activeRule.rule"
+ :payload="state.activeRule.payload"
+ :disabled="true"
+ @cancel="state.activeRule = undefined"
+ />
+
+ <ResultDefinitionModal
+ v-if="state.activeResultDefinition"
+ :definition="state.activeResultDefinition"
+ @cancel="state.activeResultDefinition = undefined"
+ />
+</template>
+
+<script setup lang="ts">
+import { computed, reactive } from "vue";
+import { useI18n } from "vue-i18n";
+import { useRouter } from "vue-router";
+import { SQLRuleEditDialog } from "@/components/SQLReview/components";
+import type { PayloadValueType } from "@/components/SQLReview/components/RuleConfigComponents";
+import { WORKSPACE_ROUTE_SQL_REVIEW } from "@/router/dashboard/workspaceRoutes";
+import { useReviewPolicyByEnvironmentName } from "@/store";
+import type { RuleTemplate } from "@/types";
+import {
+ GeneralErrorCode,
+ SQLReviewPolicyErrorCode,
+ UNKNOWN_ENVIRONMENT_NAME,
+ findRuleTemplate,
+ getRuleLocalization,
+ ruleTemplateMap,
+} from "@/types";
+import type { PlanCheckRun } from "@/types/proto/v1/plan_service";
+import {
+ PlanCheckRun_Result,
+ PlanCheckRun_Result_Status,
+ PlanCheckRun_Status,
+} from "@/types/proto/v1/plan_service";
+import ResultDefinitionModal from "./ResultDefinitionModal.vue";
+
+interface ErrorCodeLink {
+ title: string;
+ target: string;
+ url: string;
+}
+type PreviewSQLReviewRule = {
+ rule: RuleTemplate;
+ payload: PayloadValueType[];
+};
+
+export type PlanCheckDetailTableRow = {
+ checkResult: PlanCheckRun_Result;
+ category: string;
+ title: string;
+ link: ErrorCodeLink | undefined;
+};
+
+type LocalState = {
+ activeRule?: PreviewSQLReviewRule;
+ activeResultDefinition?: string;
+};
+
+const props = defineProps<{
+ planCheckRun: PlanCheckRun;
+ environment?: string;
+ isLatest?: boolean;
+}>();
+
+const { t } = useI18n();
+const router = useRouter();
+const state = reactive<LocalState>({
+ activeRule: undefined,
+ activeResultDefinition: undefined,
+});
+
+const emit = defineEmits<{
+ (event: "close"): void;
+}>();
+
+const statusIconClass = (status: PlanCheckRun_Result_Status) => {
+ switch (status) {
+ case PlanCheckRun_Result_Status.SUCCESS:
+ return "bg-success text-white";
+ case PlanCheckRun_Result_Status.WARNING:
+ return "bg-warning text-white";
+ case PlanCheckRun_Result_Status.ERROR:
+ return "bg-error text-white";
+ }
+};
+
+const checkResultList = computed((): PlanCheckRun_Result[] => {
+ if (props.planCheckRun.status === PlanCheckRun_Status.DONE) {
+ return props.planCheckRun.results;
+ } else if (props.planCheckRun.status === PlanCheckRun_Status.FAILED) {
+ return [
+ PlanCheckRun_Result.fromPartial({
+ status: PlanCheckRun_Result_Status.ERROR,
+ title: t("common.error"),
+ content: props.planCheckRun.error,
+ }),
+ ];
+ } else if (props.planCheckRun.status === PlanCheckRun_Status.CANCELED) {
+ return [
+ PlanCheckRun_Result.fromPartial({
+ status: PlanCheckRun_Result_Status.WARNING,
+ title: t("common.canceled"),
+ content: props.planCheckRun.error,
+ }),
+ ];
+ }
+
+ return [];
+});
+
+const categoryAndTitle = (
+ checkResult: PlanCheckRun_Result
+): [string, string] => {
+ if (checkResult.sqlReviewReport) {
+ const code = checkResult.sqlReviewReport?.code ?? checkResult.code;
+ if (!code) {
+ return ["", checkResult.title];
+ }
+ if (code === SQLReviewPolicyErrorCode.EMPTY_POLICY) {
+ const title = messageWithCode(checkResult.title, code);
+ return ["", title];
+ }
+ const rule = ruleTemplateMap.get(checkResult.title);
+ if (rule) {
+ const ruleLocalization = getRuleLocalization(rule.type);
+ const key = `sql-review.category.${rule.category.toLowerCase()}`;
+ const category = t(key);
+ const title = messageWithCode(ruleLocalization.title, code);
+ return [category, title];
+ }
+ return ["", messageWithCode(checkResult.title, code)];
+ }
+ if (checkResult.sqlSummaryReport) {
+ if (typeof checkResult.sqlSummaryReport.affectedRows === "number") {
+ return ["", t("task.check-type.affected-rows")];
+ }
+ return ["", checkResult.title];
+ }
+
+ return ["", checkResult.title];
+};
+
+const messageWithCode = (message: string, code: number) => {
+ return `${message} #${code}`;
+};
+
+const errorCodeLink = (
+ checkResult: PlanCheckRun_Result
+): ErrorCodeLink | undefined => {
+ const code = checkResult.sqlReviewReport?.code ?? checkResult.code;
+ switch (code) {
+ case undefined:
+ return;
+ case GeneralErrorCode.OK:
+ return;
+ case SQLReviewPolicyErrorCode.EMPTY_POLICY:
+ return {
+ title: t("sql-review.configure-policy"),
+ target: "__blank",
+ url: router.resolve({
+ name: WORKSPACE_ROUTE_SQL_REVIEW,
+ }).fullPath,
+ };
+ default: {
+ const errorCodeNamespace =
+ checkResult.sqlReviewReport !== undefined ? "advisor" : "core";
+ const domain = "https://www.bytebase.com";
+ const path = `/docs/reference/error-code/${errorCodeNamespace}/`;
+ const query = `source=console#${code}`;
+ const url = `${domain}${path}?${query}`;
+ return {
+ title: t("common.view-doc"),
+ target: "__blank",
+ url: url,
+ };
+ }
+ }
+};
+
+const tableRows = computed(() => {
+ return checkResultList.value.map<PlanCheckDetailTableRow>((checkResult) => {
+ const [category, title] = categoryAndTitle(checkResult);
+ const link = errorCodeLink(checkResult);
+ return {
+ checkResult,
+ category,
+ title,
+ link,
+ };
+ });
+});
+
+const showCategoryColumn = computed((): boolean =>
+ tableRows.value.some((row) => row.category !== "")
+);
+
+const reviewPolicy = useReviewPolicyByEnvironmentName(
+ computed(() => {
+ return props.environment || UNKNOWN_ENVIRONMENT_NAME;
+ })
+);
+const getActiveRule = (type: string): PreviewSQLReviewRule | undefined => {
+ const rule = reviewPolicy.value?.ruleList.find((rule) => rule.type === type);
+ if (!rule) {
+ return undefined;
+ }
+
+ const ruleTemplate = findRuleTemplate(type);
+ if (!ruleTemplate) {
+ return undefined;
+ }
+ ruleTemplate.comment = rule.comment;
+ const { componentList } = ruleTemplate;
+ const payload = componentList.reduce<PayloadValueType[]>(
+ (list, component) => {
+ list.push(component.payload.value ?? component.payload.default);
+ return list;
+ },
+ []
+ );
+
+ return {
+ rule: ruleTemplate,
+ payload: payload,
+ };
+};
+const setActiveRule = (type: string) => {
+ state.activeRule = getActiveRule(type);
+};
+
+const handleClickPlanCheckDetailLine = (line: number) => {
+ window.location.hash = `L${line}`;
+ emit("close");
+};
+</script>
diff --git a/frontend/src/components/Plan/components/PlanCheckSection/PlanCheckBar/PlanCheckPanel.vue b/frontend/src/components/Plan/components/PlanCheckSection/PlanCheckBar/PlanCheckPanel.vue
new file mode 100644
index 0000000000..f2f7698bec
--- /dev/null
+++ b/frontend/src/components/Plan/components/PlanCheckSection/PlanCheckBar/PlanCheckPanel.vue
@@ -0,0 +1,131 @@
+<template>
+ <div class="space-y-2">
+ <TabFilter
+ v-if="selectedPlanCheckRunUID && tabItemList.length > 1"
+ v-model:value="selectedPlanCheckRunUID"
+ :items="tabItemList"
+ />
+
+ <PlanCheckBadgeBar
+ :plan-check-run-list="planCheckRunList"
+ :selected-type="selectedTypeRef"
+ @select-type="(type) => (selectedTypeRef = type)"
+ />
+
+ <PlanCheckDetail
+ v-if="selectedPlanCheckRun"
+ :plan-check-run="selectedPlanCheckRun"
+ :environment="environment"
+ :is-latest="isLatestPlanCheckRun"
+ @close="$emit('close')"
+ />
+ </div>
+</template>
+
+<script setup lang="ts">
+import { first, orderBy } from "lodash-es";
+import { computed, ref, watch } from "vue";
+import { useI18n } from "vue-i18n";
+import { databaseForSpec } from "@/components/Plan/logic";
+import type { TabFilterItem } from "@/components/v2";
+import { TabFilter } from "@/components/v2";
+import { EMPTY_ID } from "@/types";
+import {
+ PlanCheckRun_Result_Status,
+ PlanCheckRun_Type,
+ type PlanCheckRun,
+} from "@/types/proto/v1/plan_service";
+import { humanizeDate } from "@/utils";
+import PlanCheckBadgeBar from "./PlanCheckBadgeBar.vue";
+import PlanCheckDetail from "./PlanCheckDetail.vue";
+import { usePlanContext } from "@/components/Plan/logic";
+
+const props = defineProps<{
+ planCheckRunList: PlanCheckRun[];
+ selectedType?: PlanCheckRun_Type;
+}>();
+
+defineEmits<{
+ (event: "close"): void;
+}>();
+
+const getInitialSelectedType = () => {
+ if (props.selectedType) {
+ return props.selectedType;
+ }
+
+ // Find the first plan check run with error or warning.
+ const planCheck = props.planCheckRunList.find((checkRun) =>
+ [PlanCheckRun_Result_Status.ERROR, PlanCheckRun_Result_Status.WARNING].some(
+ (status) =>
+ checkRun.results.map((result) => result.status).includes(status)
+ )
+ );
+ if (planCheck) {
+ return planCheck.type;
+ }
+ return (
+ first(props.planCheckRunList)?.type ?? PlanCheckRun_Type.TYPE_UNSPECIFIED
+ );
+};
+
+const { t } = useI18n();
+const { plan, selectedSpec } = usePlanContext();
+const selectedTypeRef = ref<PlanCheckRun_Type>(getInitialSelectedType());
+
+const selectedPlanCheckRunList = computed(() => {
+ return orderBy(
+ props.planCheckRunList.filter(
+ (checkRun) => checkRun.type === selectedTypeRef.value
+ ),
+ (checkRun) => parseInt(checkRun.uid, 10),
+ "desc"
+ );
+});
+
+const selectedPlanCheckRunUID = ref(first(selectedPlanCheckRunList.value)?.uid);
+
+const selectedPlanCheckRun = computed(() => {
+ const uid = selectedPlanCheckRunUID.value;
+ if (!uid) return undefined;
+ return selectedPlanCheckRunList.value.find(
+ (checkRun) => checkRun.uid === uid
+ );
+});
+
+const isLatestPlanCheckRun = computed(() => {
+ return (
+ selectedPlanCheckRunUID.value === first(selectedPlanCheckRunList.value)?.uid
+ );
+});
+
+const tabItemList = computed(() => {
+ return selectedPlanCheckRunList.value.map<TabFilterItem<string>>(
+ (checkRun, i) => {
+ const label =
+ i === 0
+ ? t("common.latest")
+ : checkRun.createTime
+ ? humanizeDate(checkRun.createTime)
+ : `UID(${checkRun.uid})`;
+ return {
+ label,
+ value: checkRun.uid,
+ };
+ }
+ );
+});
+
+watch(selectedPlanCheckRunList, (list) => {
+ selectedPlanCheckRunUID.value = first(list)?.uid;
+});
+
+const environment = computed(() => {
+ const spec = selectedSpec.value;
+ if (!spec || spec.id === String(EMPTY_ID)) {
+ return;
+ }
+ const database = databaseForSpec(plan.value, spec);
+ return database.effectiveEnvironmentEntity.name;
+});
+</script>
diff --git a/frontend/src/components/Plan/components/PlanCheckSection/PlanCheckBar/PlanCheckRunButton.vue b/frontend/src/components/Plan/components/PlanCheckSection/PlanCheckBar/PlanCheckRunButton.vue
new file mode 100644
index 0000000000..29dacf0a99
--- /dev/null
+++ b/frontend/src/components/Plan/components/PlanCheckSection/PlanCheckBar/PlanCheckRunButton.vue
@@ -0,0 +1,71 @@
+<template>
+ <ContextMenuButton
+ v-if="actionList.length > 0"
+ :action-list="actionList"
+ :disabled="hasRunningPlanCheck"
+ preference-key="plan.task.run-checks"
+ default-action-key="RUN-CHECKS"
+ @click="$emit('run-checks')"
+ >
+ <template #icon>
+ <BBSpin v-if="hasRunningPlanCheck" :size="20" />
+ <heroicons-outline:play v-else class="w-4 h-4" />
+ </template>
+ <template #default="{ action }">
+ <template v-if="hasRunningPlanCheck">
+ {{ $t("task.checking") }}
+ </template>
+ <template v-else>
+ {{ action.text }}
+ </template>
+ </template>
+ </ContextMenuButton>
+</template>
+
+<script setup lang="ts">
+import { computed } from "vue";
+import { useI18n } from "vue-i18n";
+import { planCheckRunListForSpec } from "@/components/Plan/logic";
+import { usePlanContext } from "@/components/Plan/logic";
+import type { ContextMenuButtonAction } from "@/components/v2";
+import { ContextMenuButton } from "@/components/v2";
+import { PlanCheckRun_Status } from "@/types/proto/v1/plan_service";
+
+defineEmits<{
+ (event: "run-checks"): void;
+}>();
+
+const { t } = useI18n();
+const { isCreating, plan, selectedSpec } = usePlanContext();
+
+const allowRunCheckForPlan = computed(() => {
+ if (isCreating.value) {
+ return false;
+ }
+ return true;
+});
+
+const actionList = computed(() => {
+ if (!allowRunCheckForPlan.value) return [];
+
+ const actionList: ContextMenuButtonAction[] = [];
+ actionList.push({
+ key: "RUN-CHECKS",
+ text: t("task.run-checks"),
+ params: {},
+ });
+ return actionList;
+});
+
+const hasRunningPlanCheck = computed((): boolean => {
+ if (isCreating.value) return false;
+
+ const planCheckRunList = planCheckRunListForSpec(
+ plan.value,
+ selectedSpec.value
+ );
+ return planCheckRunList.some(
+ (checkRun) => checkRun.status === PlanCheckRun_Status.RUNNING
+ );
+});
+</script>
diff --git a/frontend/src/components/Plan/components/PlanCheckSection/PlanCheckBar/ResultDefinitionModal.vue b/frontend/src/components/Plan/components/PlanCheckSection/PlanCheckBar/ResultDefinitionModal.vue
new file mode 100644
index 0000000000..9dd9277c4b
--- /dev/null
+++ b/frontend/src/components/Plan/components/PlanCheckSection/PlanCheckBar/ResultDefinitionModal.vue
@@ -0,0 +1,29 @@
+<template>
+ <BBModal :title="$t('sql-review.view-definition')" @close="emit('cancel')">
+ <div class="space-y-4 w-[calc(100vw-5rem)] sm:w-[40rem] pb-1">
+ <div class="space-y-1">
+ <div class="flex flex-col gap-x-2 whitespace-pre-wrap">
+ {{ definition }}
+ </div>
+ </div>
+ <div class="mt-4 pt-2 border-t flex justify-end">
+ <NButton @click.prevent="emit('cancel')">
+ {{ $t("common.cancel") }}
+ </NButton>
+ </div>
+ </div>
+ </BBModal>
+</template>
+
+<script lang="ts" setup>
+defineProps({
+ definition: {
+ required: true,
+ type: String,
+ },
+});
+
+const emit = defineEmits<{
+ (event: "cancel"): void;
+}>();
+</script>
diff --git a/frontend/src/components/Plan/components/PlanCheckSection/PlanCheckBar/index.ts b/frontend/src/components/Plan/components/PlanCheckSection/PlanCheckBar/index.ts
new file mode 100644
index 0000000000..86b498a89c
--- /dev/null
+++ b/frontend/src/components/Plan/components/PlanCheckSection/PlanCheckBar/index.ts
@@ -0,0 +1,3 @@
+import PlanCheckBar from "./PlanCheckBar.vue";
+
+export default PlanCheckBar;
diff --git a/frontend/src/components/Plan/components/PlanCheckSection/PlanCheckSection.vue b/frontend/src/components/Plan/components/PlanCheckSection/PlanCheckSection.vue
new file mode 100644
index 0000000000..3b5ddb9e5d
--- /dev/null
+++ b/frontend/src/components/Plan/components/PlanCheckSection/PlanCheckSection.vue
@@ -0,0 +1,59 @@
+<template>
+ <PlanCheckBar
+ v-if="show"
+ :allow-run-checks="allowRunChecks"
+ :plan-check-run-list="planCheckRunList"
+ class="px-4 py-2"
+ />
+</template>
+
+<script lang="ts" setup>
+import { computed } from "vue";
+import {
+ planCheckRunListForSpec,
+ planSpecHasPlanChecks,
+ usePlanContext,
+} from "@/components/Plan/logic";
+import { useCurrentUserV1 } from "@/store";
+import { EMPTY_ID } from "@/types";
+import { extractUserResourceName, hasProjectPermissionV2 } from "@/utils";
+import PlanCheckBar from "./PlanCheckBar";
+
+const currentUser = useCurrentUserV1();
+const { isCreating, plan, selectedSpec } = usePlanContext();
+
+const show = computed(() => {
+ if (isCreating.value) {
+ return false;
+ }
+ if (selectedSpec.value.id === String(EMPTY_ID)) {
+ return false;
+ }
+ return planSpecHasPlanChecks(selectedSpec.value);
+});
+
+const allowRunChecks = computed(() => {
+ // Allowing below users to run plan checks
+ // - the creator of the plan
+ // - ones who have bb.planCheckRuns.run permission in the project
+ const me = currentUser.value;
+ if (extractUserResourceName(plan.value.creator) === me.email) {
+ return true;
+ }
+ if (
+ hasProjectPermissionV2(plan.value.projectEntity, me, "bb.planCheckRuns.run")
+ ) {
+ return true;
+ }
+ return false;
+});
+
+const planCheckRunList = computed(() => {
+ // If a spec is selected, show plan checks for the spec.
+ if (selectedSpec.value && selectedSpec.value.id !== String(EMPTY_ID)) {
+ return planCheckRunListForSpec(plan.value, selectedSpec.value);
+ }
+ // Otherwise, show plan checks for the plan.
+ return plan.value.planCheckRunList;
+});
+</script>
diff --git a/frontend/src/components/Plan/components/PlanCheckSection/index.ts b/frontend/src/components/Plan/components/PlanCheckSection/index.ts
new file mode 100644
index 0000000000..bf5c827d15
--- /dev/null
+++ b/frontend/src/components/Plan/components/PlanCheckSection/index.ts
@@ -0,0 +1,6 @@
+import PlanCheckBar from "./PlanCheckBar";
+import PlanCheckSection from "./PlanCheckSection.vue";
+
+export default PlanCheckSection;
+
+export { PlanCheckBar };
diff --git a/frontend/src/components/Plan/components/SQLCheckSection/SQLCheckBadge.vue b/frontend/src/components/Plan/components/SQLCheckSection/SQLCheckBadge.vue
new file mode 100644
index 0000000000..34d90f4dde
--- /dev/null
+++ b/frontend/src/components/Plan/components/SQLCheckSection/SQLCheckBadge.vue
@@ -0,0 +1,117 @@
+<template>
+ <button
+ class="inline-flex items-center px-3 py-0.5 rounded-full text-sm border border-control-border"
+ :class="buttonClasses"
+ @click="handleClick"
+ >
+ <template v-if="status === 'RUNNING'">
+ <TaskSpinner class="-ml-1 mr-1.5 h-4 w-4 text-info" />
+ </template>
+ <template v-else-if="status === 'SUCCESS'">
+ <heroicons-outline:check
+ class="-ml-1 mr-1.5 mt-0.5 h-4 w-4 text-success"
+ />
+ </template>
+ <template v-else-if="status === 'WARNING'">
+ <heroicons-outline:exclamation
+ class="-ml-1 mr-1.5 mt-0.5 h-4 w-4 text-warning"
+ />
+ </template>
+ <template v-else-if="status === 'ERROR'">
+ <span class="mr-1.5 font-medium text-error" aria-hidden="true"> ! </span>
+ </template>
+
+ <span>{{ $t("task.check-type.sql-review") }}</span>
+
+ <SQLCheckPanel
+ v-if="showDetailPanel"
+ :database="database"
+ :advices="advices"
+ @close="showDetailPanel = false"
+ >
+ </SQLCheckPanel>
+ </button>
+</template>
+
+<script setup lang="ts">
+import { computed, ref } from "vue";
+import { SQLCheckPanel } from "@/components/SQLCheck";
+import type { Advice } from "@/types/proto/v1/sql_service";
+import { Advice_Status } from "@/types/proto/v1/sql_service";
+import { databaseForSpec, usePlanContext } from "../../logic";
+
+const props = defineProps<{
+ isRunning: boolean;
+ advices: Advice[];
+}>();
+
+defineEmits<{
+ (event: "click"): void;
+}>();
+
+const { plan, selectedSpec } = usePlanContext();
+const showDetailPanel = ref(false);
+
+const database = computed(() => {
+ return databaseForSpec(plan.value, selectedSpec.value);
+});
+
+const status = computed(() => {
+ const { isRunning, advices } = props;
+ if (isRunning) {
+ return "RUNNING";
+ }
+ if (advices.some((adv) => adv.status === Advice_Status.ERROR)) {
+ return "ERROR";
+ }
+ if (advices.some((adv) => adv.status === Advice_Status.WARNING)) {
+ return "WARNING";
+ }
+ return "SUCCESS";
+});
+
+const clickable = computed(() => {
+ return status.value === "ERROR" || status.value === "WARNING";
+});
+
+const buttonClasses = computed(() => {
+ let bgColor = "";
+ let bgHoverColor = "";
+ let textColor = "";
+ switch (status.value) {
+ case "RUNNING":
+ bgColor = "bg-blue-100";
+ bgHoverColor = "bg-blue-300";
+ textColor = "text-blue-800";
+ break;
+ case "SUCCESS":
+ bgColor = "bg-gray-100";
+ bgHoverColor = "bg-gray-300";
+ textColor = "text-gray-800";
+ break;
+ case "WARNING":
+ bgColor = "bg-yellow-100";
+ bgHoverColor = "bg-yellow-300";
+ textColor = "text-yellow-800";
+ break;
+ case "ERROR":
+ bgColor = "bg-red-100";
+ bgHoverColor = "bg-red-300";
+ textColor = "text-red-800";
+ break;
+ }
+
+ const styleList: string[] = [textColor, bgColor];
+ if (clickable.value) {
+ styleList.push("cursor-pointer", `hover:${bgHoverColor}`);
+ } else {
+ styleList.push("cursor-default");
+ }
+
+ return styleList.join(" ");
+});
+
+const handleClick = () => {
+ showDetailPanel.value = true;
+};
+</script>
diff --git a/frontend/src/components/Plan/components/SQLCheckSection/SQLCheckSection.vue b/frontend/src/components/Plan/components/SQLCheckSection/SQLCheckSection.vue
new file mode 100644
index 0000000000..01a3146e45
--- /dev/null
+++ b/frontend/src/components/Plan/components/SQLCheckSection/SQLCheckSection.vue
@@ -0,0 +1,66 @@
+<template>
+ <div class="flex items-center gap-x-4 px-4 py-2">
+ <div class="textlabel h-[26px] inline-flex items-center">
+ {{ $t("issue.sql-check.sql-checks") }}
+ </div>
+
+ <SQLCheckButton
+ v-if="database"
+ :key="selectedSpec.id"
+ :get-statement="getStatement"
+ :database="database"
+ :change-type="changeType"
+ :button-props="{
+ size: 'tiny',
+ }"
+ button-style="--n-padding: 0 8px 0 6px; --n-icon-margin: 3px;"
+ class="justify-between flex-1"
+ >
+ <template #result="{ advices, isRunning }">
+ <template v-if="advices === undefined">
+ <span class="textinfolabel">
+ {{ $t("issue.sql-check.not-executed-yet") }}
+ </span>
+ </template>
+ <SQLCheckBadge v-else :is-running="isRunning" :advices="advices" />
+ </template>
+ </SQLCheckButton>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { computed } from "vue";
+import { databaseForSpec } from "@/components/Plan/logic";
+import { SQLCheckButton } from "@/components/SQLCheck";
+import { Plan_ChangeDatabaseConfig_Type } from "@/types/proto/v1/plan_service";
+import { CheckRequest_ChangeType } from "@/types/proto/v1/sql_service";
+import { usePlanContext } from "../../logic";
+import { useSpecSheet } from "../StatementSection/useSpecSheet";
+import SQLCheckBadge from "./SQLCheckBadge.vue";
+
+const { plan, selectedSpec } = usePlanContext();
+const { sheetStatement } = useSpecSheet();
+
+const database = computed(() => {
+ return databaseForSpec(plan.value, selectedSpec.value);
+});
+
+const getStatement = async () => {
+ return {
+ statement: sheetStatement.value,
+ errors: [],
+ };
+};
+
+const changeType = computed((): CheckRequest_ChangeType | undefined => {
+ switch (selectedSpec.value?.changeDatabaseConfig?.type) {
+ case Plan_ChangeDatabaseConfig_Type.MIGRATE:
+ return CheckRequest_ChangeType.DDL;
+ case Plan_ChangeDatabaseConfig_Type.MIGRATE_GHOST:
+ return CheckRequest_ChangeType.DDL_GHOST;
+ case Plan_ChangeDatabaseConfig_Type.DATA:
+ return CheckRequest_ChangeType.DML;
+ }
+ return undefined;
+});
+</script>
diff --git a/frontend/src/components/Plan/components/SQLCheckSection/index.ts b/frontend/src/components/Plan/components/SQLCheckSection/index.ts
new file mode 100644
index 0000000000..2028b2b13c
--- /dev/null
+++ b/frontend/src/components/Plan/components/SQLCheckSection/index.ts
@@ -0,0 +1,3 @@
+import SQLCheckSection from "./SQLCheckSection.vue";
+
+export default SQLCheckSection;
diff --git a/frontend/src/components/Plan/components/SpecListSection/SpecCard.vue b/frontend/src/components/Plan/components/SpecListSection/SpecCard.vue
new file mode 100644
index 0000000000..69718c984e
--- /dev/null
+++ b/frontend/src/components/Plan/components/SpecListSection/SpecCard.vue
@@ -0,0 +1,51 @@
+<template>
+ <div
+ class="spec px-2 py-1 pr-1 cursor-pointer border rounded lg:flex-1 flex justify-between items-stretch overflow-hidden gap-x-1"
+ :class="specClass"
+ @click="onClickSpec(spec)"
+ >
+ <div class="w-full flex items-center gap-2">
+ <InstanceV1Name
+ :instance="databaseForSpec(plan, spec).instanceEntity"
+ :link="false"
+ class="text-gray-500 text-sm"
+ />
+ <span class="truncate">{{
+ databaseForSpec(plan, spec).databaseName
+ }}</span>
+ </div>
+ </div>
+</template>
+
+<script setup lang="ts">
+import { computed } from "vue";
+import type { Plan_Spec } from "@/types/proto/v1/plan_service";
+import { databaseForSpec, usePlanContext } from "../../logic";
+
+const props = defineProps<{
+ spec: Plan_Spec;
+}>();
+
+const { isCreating, plan, selectedSpec, events } = usePlanContext();
+const selected = computed(() => props.spec === selectedSpec.value);
+
+const specClass = computed(() => {
+ const classes: string[] = [];
+ if (isCreating.value) classes.push("create");
+ if (selected.value) classes.push("selected");
+ return classes;
+});
+
+const onClickSpec = (spec: Plan_Spec) => {
+ events.emit("select-spec", { spec });
+};
+</script>
+
+<style scoped lang="postcss">
+.spec.selected {
+ @apply border-accent bg-accent bg-opacity-5 shadow;
+}
+.spec .name {
+ @apply whitespace-pre-wrap break-all;
+}
+</style>
diff --git a/frontend/src/components/Plan/components/SpecListSection/SpecListSection.vue b/frontend/src/components/Plan/components/SpecListSection/SpecListSection.vue
new file mode 100644
index 0000000000..9ccda6af2c
--- /dev/null
+++ b/frontend/src/components/Plan/components/SpecListSection/SpecListSection.vue
@@ -0,0 +1,60 @@
+<template>
+ <div v-if="shouldShowSpecBar" class="relative py-2">
+ <div
+ ref="specBar"
+ class="spec-list gap-2 px-4 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 3xl:grid-cols-5 4xl:grid-cols-6 overflow-y-auto"
+ :class="{
+ 'more-bottom': specBarScrollState.bottom,
+ 'more-top': specBarScrollState.top,
+ }"
+ :style="{
+ 'max-height': `${MAX_LIST_HEIGHT}px`,
+ }"
+ >
+ <SpecCard v-for="(spec, i) in specList" :key="i" :spec="spec" />
+ </div>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { computed, ref } from "vue";
+import { useVerticalScrollState } from "@/composables/useScrollState";
+import { usePlanContext } from "../../logic";
+import SpecCard from "./SpecCard.vue";
+
+const MAX_LIST_HEIGHT = 207;
+
+const { plan, selectedSpec, selectedStep } = usePlanContext();
+const specBar = ref<HTMLDivElement>();
+const specBarScrollState = useVerticalScrollState(specBar, MAX_LIST_HEIGHT);
+
+const specList = computed(
+ () =>
+ plan.value.steps.find((step) => step.specs.includes(selectedSpec.value))
+ ?.specs || []
+);
+
+// Show the spec bar when some of the steps have more than one specs.
+const shouldShowSpecBar = computed(() => {
+ return selectedStep.value && selectedStep.value.specs.length > 0;
+});
+</script>
+
+<style scoped lang="postcss">
+.spec-list::before {
+ @apply absolute top-0 h-4 w-full -ml-2 z-10 pointer-events-none transition-shadow;
+ content: "";
+ box-shadow: none;
+}
+.spec-list::after {
+ @apply absolute bottom-0 h-4 w-full -ml-2 z-10 pointer-events-none transition-shadow;
+ content: "";
+ box-shadow: none;
+}
+.spec-list.more-top::before {
+ box-shadow: inset 0 0.3rem 0.25rem -0.25rem rgb(0 0 0 / 10%);
+}
+.spec-list.more-bottom::after {
+ box-shadow: inset 0 -0.3rem 0.25rem -0.25rem rgb(0 0 0 / 10%);
+}
+</style>
diff --git a/frontend/src/components/Plan/components/SpecListSection/index.ts b/frontend/src/components/Plan/components/SpecListSection/index.ts
new file mode 100644
index 0000000000..cc15800de3
--- /dev/null
+++ b/frontend/src/components/Plan/components/SpecListSection/index.ts
@@ -0,0 +1,3 @@
+import SpecListSection from "./SpecListSection.vue";
+
+export default SpecListSection;
diff --git a/frontend/src/components/Plan/components/StatementSection/EditorView/EditorView.vue b/frontend/src/components/Plan/components/StatementSection/EditorView/EditorView.vue
new file mode 100644
index 0000000000..3b92ab49cb
--- /dev/null
+++ b/frontend/src/components/Plan/components/StatementSection/EditorView/EditorView.vue
@@ -0,0 +1,660 @@
+<template>
+ <div class="flex flex-col gap-y-2">
+ <div class="flex items-center justify-between">
+ <div class="flex items-center gap-x-4">
+ <div class="flex items-center gap-x-1 text-sm font-medium">
+ <span
+ :class="isEmpty(state.statement) ? 'text-red-600' : 'text-control'"
+ >
+ {{ statementTitle }}
+ </span>
+ <span v-if="isCreating" class="text-red-600">*</span>
+ <NButton
+ v-if="!isCreating && !hasFeature('bb.feature.sql-review')"
+ size="tiny"
+ @click.prevent="state.showFeatureModal = true"
+ >
+ 🎈{{ $t("sql-review.unlock-full-feature") }}
+ </NButton>
+ </div>
+
+ <NButton
+ v-if="isCreating && allowApplySpecStateToOthers"
+ :disabled="isEmpty(state.statement)"
+ size="tiny"
+ @click.prevent="applySpecStateToOthers"
+ >
+ {{ $t("issue.apply-to-other-tasks") }}
+ </NButton>
+ </div>
+
+ <div class="flex items-center justify-end gap-x-2">
+ <template v-if="isCreating">
+ <FormatOnSaveCheckbox
+ v-model:value="formatOnSave"
+ :language="language"
+ />
+ <SQLUploadButton
+ size="tiny"
+ :loading="state.isUploadingFile"
+ @update:sql="handleUpdateStatement"
+ >
+ {{ $t("issue.upload-sql") }}
+ </SQLUploadButton>
+ </template>
+
+ <template v-else>
+ <template v-if="!state.isEditing">
+ <template v-if="shouldShowEditButton">
+ <!-- for small size sheets, show full featured UI editing button group -->
+ <NTooltip :disabled="denyEditStatementReasons.length === 0">
+ <template #trigger>
+ <NButton
+ v-if="!isSheetOversize"
+ size="tiny"
+ tag="div"
+ :disabled="denyEditStatementReasons.length > 0"
+ @click.prevent="beginEdit"
+ >
+ {{ $t("common.edit") }}
+ </NButton>
+ <!-- for oversized sheets, only allow to upload and overwrite the sheet -->
+ <SQLUploadButton
+ v-else
+ size="tiny"
+ :loading="state.isUploadingFile"
+ @update:sql="handleUpdateStatementAndOverwrite"
+ >
+ {{ $t("issue.upload-sql") }}
+ </SQLUploadButton>
+ </template>
+ <template #default>
+ <ErrorList :errors="denyEditStatementReasons" />
+ </template>
+ </NTooltip>
+ </template>
+ </template>
+ <template v-else>
+ <FormatOnSaveCheckbox
+ v-model:value="formatOnSave"
+ :language="language"
+ />
+ <SQLUploadButton
+ size="tiny"
+ :loading="state.isUploadingFile"
+ @update:sql="handleUpdateStatement"
+ >
+ {{ $t("issue.upload-sql") }}
+ </SQLUploadButton>
+ <NButton
+ v-if="state.isEditing"
+ size="tiny"
+ :disabled="!allowSaveSQL"
+ @click.prevent="saveEdit"
+ >
+ {{ $t("common.save") }}
+ </NButton>
+ <NButton
+ v-if="state.isEditing"
+ size="tiny"
+ quaternary
+ @click.prevent="cancelEdit"
+ >
+ {{ $t("common.cancel") }}
+ </NButton>
+ </template>
+ </template>
+ </div>
+ </div>
+
+ <BBAttention
+ v-if="isSheetOversize"
+ type="warning"
+ :title="$t('issue.statement-from-sheet-warning')"
+ >
+ <template #action>
+ <DownloadSheetButton v-if="sheetName" :sheet="sheetName" size="small" />
+ </template>
+ </BBAttention>
+
+ <div
+ ref="editorContainerElRef"
+ class="whitespace-pre-wrap overflow-hidden min-h-[120px] relative"
+ :data-height="editorContainerHeight"
+ >
+ <MonacoEditor
+ ref="monacoEditorRef"
+ class="w-full h-auto max-h-[240px] min-h-[120px] border rounded-[3px]"
+ :filename="filename"
+ :content="state.statement"
+ :language="language"
+ :auto-focus="false"
+ :readonly="isEditorReadonly"
+ :dialect="dialect"
+ :advices="isEditorReadonly ? markers : []"
+ :auto-height="{ min: 120, max: 240 }"
+ :auto-complete-context="{
+ instance: database.instance,
+ database: database.name,
+ }"
+ @update:content="handleStatementChange"
+ />
+ <div class="absolute bottom-[3px] right-[18px]">
+ <NButton
+ size="small"
+ :quaternary="true"
+ style="--n-padding: 0 5px"
+ @click="state.showEditorModal = true"
+ >
+ <template #icon>
+ <ExpandIcon class="w-4 h-4" />
+ </template>
+ </NButton>
+ </div>
+ </div>
+ </div>
+
+ <BBModal
+ v-model:show="state.showEditorModal"
+ :title="statementTitle"
+ :trap-focus="true"
+ header-class="!border-b-0"
+ container-class="!pt-0 !overflow-hidden"
+ >
+ <div
+ id="modal-editor-container"
+ style="
+ width: calc(100vw - 10rem);
+ height: calc(100vh - 10rem);
+ overflow: hidden;
+ position: relative;
+ "
+ class="border rounded-[3px]"
+ >
+ <MonacoEditor
+ v-if="state.showEditorModal"
+ class="w-full h-full"
+ :filename="filename"
+ :content="state.statement"
+ :language="language"
+ :auto-focus="false"
+ :readonly="isEditorReadonly"
+ :dialect="dialect"
+ :advices="isEditorReadonly ? markers : []"
+ :auto-complete-context="{
+ instance: database.instance,
+ database: database.name,
+ }"
+ @update:content="handleStatementChange"
+ />
+ </div>
+ </BBModal>
+
+ <FeatureModal
+ :open="state.showFeatureModal"
+ feature="bb.feature.sql-review"
+ @cancel="state.showFeatureModal = false"
+ />
+</template>
+
+<script setup lang="ts">
+import { useElementSize } from "@vueuse/core";
+import { cloneDeep, head } from "lodash-es";
+import { ExpandIcon } from "lucide-vue-next";
+import { NButton, NTooltip, useDialog } from "naive-ui";
+import { v1 as uuidv1 } from "uuid";
+import { computed, h, reactive, ref, watch } from "vue";
+import { useI18n } from "vue-i18n";
+import { MonacoEditor } from "@/components/MonacoEditor";
+import { extensionNameOfLanguage } from "@/components/MonacoEditor/utils";
+import { ErrorList } from "@/components/Plan/components/common";
+import {
+ getLocalSheetByName,
+ createEmptyLocalSheet,
+ databaseEngineForSpec,
+ databaseForSpec,
+ isDeploymentConfigChangeSpec,
+ isGroupingChangeSpec,
+ sheetNameForSpec,
+} from "@/components/Plan/logic";
+import { usePlanContext } from "@/components/Plan/logic";
+import DownloadSheetButton from "@/components/Sheet/DownloadSheetButton.vue";
+import SQLUploadButton from "@/components/misc/SQLUploadButton.vue";
+import { planServiceClient } from "@/grpcweb";
+import { hasFeature, pushNotification, useSheetV1Store } from "@/store";
+import type { SQLDialect } from "@/types";
+import { EMPTY_ID, dialectOfEngineV1 } from "@/types";
+import type { Plan_Spec } from "@/types/proto/v1/plan_service";
+import { TenantMode } from "@/types/proto/v1/project_service";
+import { Sheet } from "@/types/proto/v1/sheet_service";
+import {
+ defer,
+ getSheetStatement,
+ setSheetStatement,
+ useInstanceV1EditorLanguage,
+ getStatementSize,
+ flattenSpecList,
+} from "@/utils";
+import { useSQLAdviceMarkers } from "../useSQLAdviceMarkers";
+import FormatOnSaveCheckbox from "./FormatOnSaveCheckbox.vue";
+import type { EditState } from "./useTempEditState";
+import { useTempEditState } from "./useTempEditState";
+
+type LocalState = EditState & {
+ showFeatureModal: boolean;
+ showEditorModal: boolean;
+ isUploadingFile: boolean;
+};
+
+const { t } = useI18n();
+const { isCreating, plan, selectedSpec, selectedStep, formatOnSave } =
+ usePlanContext();
+const project = computed(() => plan.value.projectEntity);
+const dialog = useDialog();
+const editorContainerElRef = ref<HTMLElement>();
+const monacoEditorRef = ref<InstanceType<typeof MonacoEditor>>();
+const { height: editorContainerHeight } = useElementSize(editorContainerElRef);
+
+const state = reactive<LocalState>({
+ isEditing: false,
+ statement: "",
+ showFeatureModal: false,
+ showEditorModal: false,
+ isUploadingFile: false,
+});
+
+const database = computed(() => {
+ return databaseForSpec(plan.value, selectedSpec.value);
+});
+
+const language = useInstanceV1EditorLanguage(
+ computed(() => database.value.instanceEntity)
+);
+const filename = computed(() => {
+ const name = uuidv1();
+ const ext = extensionNameOfLanguage(language.value);
+ return `${name}.${ext}`;
+});
+const dialect = computed((): SQLDialect => {
+ const db = database.value;
+ return dialectOfEngineV1(db.instanceEntity.engine);
+});
+const statementTitle = computed(() => {
+ return language.value === "sql" ? t("common.sql") : t("common.statement");
+});
+const { markers } = useSQLAdviceMarkers();
+
+/**
+ * to set the MonacoEditor as readonly
+ * This happens when
+ * - Not in edit mode
+ * - Disallowed to edit statement
+ */
+const isEditorReadonly = computed(() => {
+ if (isCreating.value) {
+ return false;
+ }
+ return !state.isEditing || isSheetOversize.value || false;
+});
+
+const {
+ sheet,
+ sheetName,
+ sheetReady,
+ sheetStatement,
+ reset: resetTempEditState,
+} = useTempEditState(state);
+
+const isSheetOversize = computed(() => {
+ if (isCreating.value) return false;
+ if (state.isEditing) return false;
+ if (!sheetReady.value) return false;
+ if (!sheet.value) return false;
+ return getStatementSize(getSheetStatement(sheet.value)).lt(
+ sheet.value.contentSize
+ );
+});
+
+const denyEditStatementReasons = computed(() => {
+ return [];
+});
+
+const shouldShowEditButton = computed(() => {
+ // Need not to show "Edit" while the plan is still pending create.
+ if (isCreating.value) {
+ return false;
+ }
+ // Will show another button group as [Upload][Cancel][Save]
+ // while editing
+ if (state.isEditing) {
+ return false;
+ }
+ return true;
+});
+
+const allowApplySpecStateToOthers = computed(() => {
+ if (!isCreating.value) {
+ return false;
+ }
+ if (project.value.tenantMode === TenantMode.TENANT_MODE_ENABLED) {
+ return !isDeploymentConfigChangeSpec(selectedSpec.value);
+ }
+
+ return selectedStep.value && selectedStep.value?.specs.length > 1;
+});
+
+const allowSaveSQL = computed((): boolean => {
+ if (state.statement === "") {
+ // Not allowed if the statement is empty.
+ return false;
+ }
+ if (!sheetReady.value) {
+ return false;
+ }
+ if (state.statement === sheetStatement.value) {
+ // Not allowed if the statement is not modified.
+ return false;
+ }
+
+ // Allowed to save otherwise
+ return true;
+});
+
+const beginEdit = () => {
+ state.isEditing = true;
+};
+
+const saveEdit = async () => {
+ try {
+ await updateStatement(state.statement);
+ resetTempEditState();
+ } finally {
+ state.isEditing = false;
+ }
+};
+
+const cancelEdit = () => {
+ state.statement = sheetStatement.value;
+ state.isEditing = false;
+};
+
+const chooseUpdateStatementTarget = () => {
+ type Target = "CANCELED" | "SPEC" | "STEP" | "ALL";
+ const d = defer<{ target: Target; specs: Plan_Spec[] }>();
+
+ const targets: Record<Target, Plan_Spec[]> = {
+ CANCELED: [],
+ SPEC: [selectedSpec.value],
+ STEP:
+ plan.value.steps.find((step) => step.specs.includes(selectedSpec.value))
+ ?.specs || [],
+ ALL: flattenSpecList(plan.value),
+ };
+
+ if (isDeploymentConfigChangeSpec(selectedSpec.value)) {
+ dialog.info({
+ title: t("issue.update-statement.self", { type: statementTitle.value }),
+ content: t(
+ "issue.update-statement.current-change-will-apply-to-all-tasks-in-batch-mode"
+ ),
+ type: "info",
+ autoFocus: false,
+ closable: false,
+ maskClosable: false,
+ closeOnEsc: false,
+ showIcon: false,
+ positiveText: t("common.confirm"),
+ negativeText: t("common.cancel"),
+ onPositiveClick: () => {
+ d.resolve({ target: "ALL", specs: targets.ALL });
+ },
+ onNegativeClick: () => {
+ d.resolve({ target: "CANCELED", specs: [] });
+ },
+ });
+ return d.promise;
+ }
+
+ if (targets.STEP.length === 1 && targets.ALL.length === 1) {
+ d.resolve({ target: "SPEC", specs: targets.SPEC });
+ return d.promise;
+ }
+
+ const $d = dialog.create({
+ title: t("issue.update-statement.self", { type: statementTitle.value }),
+ content: t("issue.update-statement.apply-current-change-to"),
+ type: "info",
+ autoFocus: false,
+ closable: false,
+ maskClosable: false,
+ closeOnEsc: false,
+ showIcon: false,
+ action: () => {
+ const finish = (target: Target) => {
+ d.resolve({ target, specs: targets[target] });
+ $d.destroy();
+ };
+
+ const CANCEL = h(
+ NButton,
+ { size: "small", onClick: () => finish("CANCELED") },
+ {
+ default: () => t("common.cancel"),
+ }
+ );
+
+ const buttons = [CANCEL];
+ // For database group change spec, don't show the option to select the spec.
+ if (!isGroupingChangeSpec(selectedSpec.value)) {
+ const SPEC = h(
+ NButton,
+ { size: "small", onClick: () => finish("SPEC") },
+ {
+ default: () => t("issue.update-statement.target.selected-task"),
+ }
+ );
+ buttons.push(SPEC);
+
+ if (targets.STEP.length > 1) {
+ // More than one editable specs in step
+ // Add "Selected step" option
+ const STEP = h(
+ NButton,
+ { size: "small", onClick: () => finish("STEP") },
+ {
+ default: () => t("issue.update-statement.target.selected-stage"),
+ }
+ );
+ buttons.push(STEP);
+ }
+ }
+ if (
+ isGroupingChangeSpec(selectedSpec.value) ||
+ targets.ALL.length > targets.STEP.length
+ ) {
+ // More editable specs in other steps
+ // Add "All specs" option
+ const ALL = h(
+ NButton,
+ { size: "small", onClick: () => finish("ALL") },
+ {
+ default: () => t("issue.update-statement.target.all-tasks"),
+ }
+ );
+ buttons.push(ALL);
+ }
+
+ return h(
+ "div",
+ { class: "flex items-center justify-end gap-x-2" },
+ buttons
+ );
+ },
+ onClose() {
+ d.resolve({ target: "CANCELED", specs: [] });
+ },
+ });
+
+ return d.promise;
+};
+
+const showOverwriteConfirmDialog = () => {
+ return new Promise((resolve, reject) => {
+ // Show a confirm dialog before replacing if the editing statement is not empty.
+ dialog.create({
+ positiveText: t("common.confirm"),
+ negativeText: t("common.cancel"),
+ title: t("issue.overwrite-current-statement"),
+ autoFocus: false,
+ closable: false,
+ maskClosable: false,
+ closeOnEsc: false,
+ onNegativeClick: () => {
+ reject();
+ },
+ onPositiveClick: () => {
+ resolve(undefined);
+ },
+ });
+ });
+};
+
+const handleUpdateStatementAndOverwrite = async (
+ statement: string,
+ filename: string
+) => {
+ try {
+ await showOverwriteConfirmDialog();
+ } catch (error) {
+ return;
+ }
+
+ state.isEditing = true;
+ state.statement = statement;
+ await handleUpdateStatement(statement, filename);
+};
+
+const handleUpdateStatement = async (statement: string, filename: string) => {
+ try {
+ state.isUploadingFile = true;
+ handleStatementChange(statement);
+ if (sheet.value) {
+ sheet.value.title = filename;
+ }
+ resetTempEditState();
+ } finally {
+ state.isUploadingFile = false;
+ }
+};
+
+const applySpecStateToOthers = async () => {
+ const specList = flattenSpecList(plan.value);
+ for (let i = 0; i < specList.length; i++) {
+ const spec = specList[i];
+ const sheetName = sheetNameForSpec(spec);
+ if (!sheetName) continue;
+ const sheet = getLocalSheetByName(sheetName);
+ setSheetStatement(sheet, state.statement);
+ }
+};
+
+const updateStatement = async (statement: string) => {
+ const planPatch = cloneDeep(plan.value);
+ if (!planPatch) {
+ return;
+ }
+
+ const specsIdList: string[] = [];
+ const { target, specs } = await chooseUpdateStatementTarget();
+ if (target === "CANCELED" || specs.length === 0) {
+ cancelEdit();
+ return;
+ }
+
+ specs.forEach((spec) => {
+ if (spec) {
+ specsIdList.push(spec.id);
+ }
+ });
+
+ const distinctSpecsIds = new Set(
+ specsIdList.filter((id) => id && id !== String(EMPTY_ID))
+ );
+ if (distinctSpecsIds.size === 0) {
+ return;
+ }
+
+ const specsToPatch = planPatch.steps
+ .flatMap((step) => step.specs)
+ .filter((spec) => distinctSpecsIds.has(spec.id));
+ const sheet = Sheet.fromPartial({
+ ...createEmptyLocalSheet(),
+ title: plan.value.title,
+ engine: await databaseEngineForSpec(project.value, head(specsToPatch)),
+ });
+ setSheetStatement(sheet, statement);
+ const createdSheet = await useSheetV1Store().createSheet(
+ plan.value.project,
+ sheet
+ );
+
+ for (let i = 0; i < specsToPatch.length; i++) {
+ const spec = specsToPatch[i];
+ let config = undefined;
+ if (spec.changeDatabaseConfig) {
+ config = spec.changeDatabaseConfig;
+ } else if (spec.exportDataConfig) {
+ config = spec.exportDataConfig;
+ }
+ if (!config) continue;
+ config.sheet = createdSheet.name;
+ }
+
+ const updatedPlan = await planServiceClient.updatePlan({
+ plan: planPatch,
+ updateMask: ["steps"],
+ });
+
+ Object.assign(plan.value, updatedPlan);
+
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.updated"),
+ });
+};
+
+const handleStatementChange = (value: string) => {
+ if (isEditorReadonly.value) {
+ return;
+ }
+
+ state.statement = value;
+ if (isCreating.value) {
+ // When creating an plan, update the local sheet directly.
+ if (!sheet.value) return;
+ setSheetStatement(sheet.value, value);
+ }
+};
+
+watch(
+ sheetStatement,
+ (statement) => {
+ state.statement = statement;
+ },
+ { immediate: true }
+);
+
+watch(isCreating, (curr, prev) => {
+ // Reset the edit state after creating the plan.
+ if (!curr && prev) {
+ state.isEditing = false;
+ }
+});
+
+defineExpose({
+ get editor() {
+ return monacoEditorRef.value;
+ },
+});
+</script>
diff --git a/frontend/src/components/Plan/components/StatementSection/EditorView/FormatOnSaveCheckbox.vue b/frontend/src/components/Plan/components/StatementSection/EditorView/FormatOnSaveCheckbox.vue
new file mode 100644
index 0000000000..93b53a4160
--- /dev/null
+++ b/frontend/src/components/Plan/components/StatementSection/EditorView/FormatOnSaveCheckbox.vue
@@ -0,0 +1,27 @@
+<template>
+ <NCheckbox
+ v-if="allowFormatOnSave"
+ :checked="value"
+ size="small"
+ @update:checked="$emit('update:value', $event)"
+ >
+ {{ $t("issue.format-on-save") }}
+ </NCheckbox>
+</template>
+
+<script setup lang="ts">
+import { NCheckbox } from "naive-ui";
+import { computed } from "vue";
+import type { Language } from "@/types";
+
+const props = defineProps<{
+ language: Language;
+ value: boolean;
+}>();
+
+defineEmits<{
+ (event: "update:value", on: boolean): void;
+}>();
+
+const allowFormatOnSave = computed(() => props.language === "sql");
+</script>
diff --git a/frontend/src/components/Plan/components/StatementSection/EditorView/index.ts b/frontend/src/components/Plan/components/StatementSection/EditorView/index.ts
new file mode 100644
index 0000000000..8a654810d1
--- /dev/null
+++ b/frontend/src/components/Plan/components/StatementSection/EditorView/index.ts
@@ -0,0 +1,3 @@
+import EditorView from "./EditorView.vue";
+
+export default EditorView;
diff --git a/frontend/src/components/Plan/components/StatementSection/EditorView/useTempEditState.ts b/frontend/src/components/Plan/components/StatementSection/EditorView/useTempEditState.ts
new file mode 100644
index 0000000000..4a8b64e5db
--- /dev/null
+++ b/frontend/src/components/Plan/components/StatementSection/EditorView/useTempEditState.ts
@@ -0,0 +1,113 @@
+import { computed, nextTick, ref, watch } from "vue";
+import { UNKNOWN_ID } from "@/types";
+import { usePlanContext } from "../../../logic";
+import { useSpecSheet } from "../useSpecSheet";
+
+export type EditState = {
+ isEditing: boolean;
+ statement: string;
+};
+
+export const useTempEditState = (state: EditState) => {
+ const { isCreating, selectedSpec } = usePlanContext();
+ const { sheet, sheetName, sheetReady, sheetStatement } = useSpecSheet();
+
+ let stopWatching = () => {
+ // noop
+ };
+
+ const startWatching = () => {
+ const tempEditStateMap = new Map<string, EditState>();
+ const isSwitchingSpec = ref(false);
+
+ const selectedSpecId = computed((): string => {
+ if (isCreating.value) return String(UNKNOWN_ID);
+ return selectedSpec.value.id;
+ });
+
+ watch(selectedSpecId, () => {
+ // When switching spec id, set the switch flag to true
+ // to temporarily disable change listeners.
+ isSwitchingSpec.value = true;
+ nextTick(() => {
+ isSwitchingSpec.value = false;
+ });
+ });
+
+ const handleEditChange = () => {
+ // When we are switching between specs, this will also be triggered.
+ // But we shouldn't update the temp store.
+ if (isSwitchingSpec.value) {
+ return;
+ }
+ // Save the temp edit state before switching spec.
+ tempEditStateMap.set(selectedSpecId.value, {
+ isEditing: state.isEditing,
+ statement: state.statement,
+ });
+ };
+
+ const afterSpecIdChange = (id: string) => {
+ // Try to restore the saved temp edit state after switching spec.
+ const storedState = tempEditStateMap.get(id);
+ if (storedState) {
+ // If found the stored temp edit state, restore it.
+ Object.assign(state, storedState);
+ } else {
+ // Restore to the spec's default state otherwise.
+ state.isEditing = false;
+ state.statement = sheetStatement.value;
+ }
+ };
+
+ // Save the temp editing state before switching specs
+ const stopWatchBeforeChange = watch(
+ [() => state.isEditing, () => state.statement],
+ handleEditChange,
+ { immediate: true }
+ );
+ const stopWatchAfterChange = watch(
+ selectedSpecId,
+ afterSpecIdChange,
+ { flush: "post" } // Listen to the event AFTER selectedSpecId changed
+ );
+
+ return () => {
+ tempEditStateMap.clear();
+ stopWatchBeforeChange();
+ stopWatchAfterChange();
+ };
+ };
+
+ watch(
+ isCreating,
+ () => {
+ if (!isCreating.value) {
+ // If we are opening an existed plan, we should listen and store the
+ // temp editing states.
+ stopWatching = startWatching();
+ } else {
+ // If we are creating an plan, we don't need the temp editing state
+ // feature since all specs are still in editing mode.
+ stopWatching && stopWatching();
+ }
+ },
+ { immediate: true }
+ );
+
+ const reset = () => {
+ stopWatching();
+
+ if (!isCreating.value) {
+ stopWatching = startWatching();
+ }
+ };
+
+ return {
+ reset,
+ sheet,
+ sheetName,
+ sheetReady,
+ sheetStatement,
+ };
+};
diff --git a/frontend/src/components/Plan/components/StatementSection/StatementSection.vue b/frontend/src/components/Plan/components/StatementSection/StatementSection.vue
new file mode 100644
index 0000000000..3165d2a6b3
--- /dev/null
+++ b/frontend/src/components/Plan/components/StatementSection/StatementSection.vue
@@ -0,0 +1,47 @@
+<template>
+ <div v-if="viewMode !== 'NONE'" class="px-4 py-2 flex flex-col gap-y-2">
+ <EditorView ref="editorViewRef" />
+ </div>
+</template>
+
+<script setup lang="ts">
+import { computed } from "vue";
+import { ref } from "vue";
+import { nextTick } from "vue";
+import { useRouter } from "vue-router";
+import { EMPTY_ID } from "@/types";
+import { usePlanContext } from "../../logic";
+import EditorView from "./EditorView";
+
+const { selectedSpec } = usePlanContext();
+
+const editorViewRef = ref<InstanceType<typeof EditorView>>();
+const router = useRouter();
+
+type ViewMode = "NONE" | "EDITOR";
+
+const viewMode = computed((): ViewMode => {
+ if (selectedSpec.value.id !== String(EMPTY_ID)) {
+ return "EDITOR";
+ }
+
+ return "NONE";
+});
+
+router.afterEach((to) => {
+ if (to.hash) {
+ scrollToLineByHash(to.hash);
+ }
+});
+
+const scrollToLineByHash = (hash: string) => {
+ const match = hash.match(/^#L(\d+)$/);
+ if (!match) return;
+ const lineNumber = parseInt(match[1], 10);
+ nextTick(() => {
+ editorViewRef.value?.editor?.monacoEditor?.editor?.codeEditor?.revealLineNearTop(
+ lineNumber
+ );
+ });
+};
+</script>
diff --git a/frontend/src/components/Plan/components/StatementSection/index.ts b/frontend/src/components/Plan/components/StatementSection/index.ts
new file mode 100644
index 0000000000..2895e1f4a0
--- /dev/null
+++ b/frontend/src/components/Plan/components/StatementSection/index.ts
@@ -0,0 +1,3 @@
+import StatementSection from "./StatementSection.vue";
+
+export default StatementSection;
diff --git a/frontend/src/components/Plan/components/StatementSection/useSQLAdviceMarkers.ts b/frontend/src/components/Plan/components/StatementSection/useSQLAdviceMarkers.ts
new file mode 100644
index 0000000000..86722934ba
--- /dev/null
+++ b/frontend/src/components/Plan/components/StatementSection/useSQLAdviceMarkers.ts
@@ -0,0 +1,64 @@
+import { maxBy } from "lodash-es";
+import { computed } from "vue";
+import type { AdviceOption } from "@/components/MonacoEditor";
+import {
+ PlanCheckRun,
+ PlanCheckRun_Result_Status,
+ PlanCheckRun_Type,
+} from "@/types/proto/v1/plan_service";
+import { planCheckRunListForSpec, usePlanContext } from "../../logic";
+
+export const useSQLAdviceMarkers = () => {
+ const { isCreating, plan, selectedSpec } = usePlanContext();
+ const markers = computed(() => {
+ if (isCreating.value) return [];
+
+ const planCheckRunList = planCheckRunListForSpec(
+ plan.value,
+ selectedSpec.value
+ );
+ const types: PlanCheckRun_Type[] = [
+ PlanCheckRun_Type.DATABASE_STATEMENT_ADVISE,
+ ];
+ return types.flatMap((type) => {
+ return getLatestAdviceOptions(
+ planCheckRunList.filter((checkRun) => checkRun.type === type)
+ );
+ });
+ });
+ return { markers };
+};
+
+const getLatestAdviceOptions = (planCheckRunList: PlanCheckRun[]) => {
+ const latest = maxBy(planCheckRunList, (checkRun) =>
+ parseInt(checkRun.uid, 10)
+ );
+ if (!latest) {
+ return [];
+ }
+ const resultList = latest.results;
+ return resultList
+ .filter(
+ (result) =>
+ result.status === PlanCheckRun_Result_Status.ERROR ||
+ result.status === PlanCheckRun_Result_Status.WARNING
+ )
+ .filter((result) => result.sqlReviewReport?.line !== undefined)
+ .map<AdviceOption>((result) => {
+ const line = result.sqlReviewReport!.line;
+ const column = result.sqlReviewReport?.column ?? Number.MAX_SAFE_INTEGER;
+ const code = result.sqlReviewReport?.code ?? result.code;
+ return {
+ severity:
+ result.status === PlanCheckRun_Result_Status.ERROR
+ ? "ERROR"
+ : "WARNING",
+ message: result.content,
+ source: `${result.title} (${code}) L${line}:C${column}`,
+ startLineNumber: line,
+ endLineNumber: line,
+ startColumn: column,
+ endColumn: column,
+ };
+ });
+};
diff --git a/frontend/src/components/Plan/components/StatementSection/useSpecSheet.ts b/frontend/src/components/Plan/components/StatementSection/useSpecSheet.ts
new file mode 100644
index 0000000000..167c010369
--- /dev/null
+++ b/frontend/src/components/Plan/components/StatementSection/useSpecSheet.ts
@@ -0,0 +1,55 @@
+import { computedAsync } from "@vueuse/core";
+import { computed, ref } from "vue";
+import { useSheetV1Store } from "@/store";
+import {
+ extractSheetUID,
+ getSheetStatement,
+ setSheetStatement,
+ sheetNameOfSpec,
+} from "@/utils";
+import { getLocalSheetByName, usePlanContext } from "../../logic";
+
+export const useSpecSheet = () => {
+ const sheetStore = useSheetV1Store();
+ const { selectedSpec } = usePlanContext();
+
+ const sheetName = computed(() => {
+ return sheetNameOfSpec(selectedSpec.value);
+ });
+ const isFetchingSheet = ref(false);
+ const sheetReady = computed(() => {
+ return !isFetchingSheet.value;
+ });
+ const sheet = computedAsync(
+ async () => {
+ const name = sheetName.value;
+ const uid = extractSheetUID(name);
+ if (uid.startsWith("-")) {
+ return getLocalSheetByName(name);
+ }
+
+ return sheetStore.getOrFetchSheetByName(name);
+ },
+ undefined,
+ {
+ evaluating: isFetchingSheet,
+ }
+ );
+ const sheetStatement = computed({
+ get() {
+ if (!sheetReady.value || !sheet.value) return "";
+ return getSheetStatement(sheet.value);
+ },
+ set(statement) {
+ if (!sheetReady.value || !sheet.value) return;
+ setSheetStatement(sheet.value, statement);
+ },
+ });
+
+ return {
+ sheet,
+ sheetName,
+ sheetReady,
+ sheetStatement,
+ };
+};
diff --git a/frontend/src/components/Plan/components/StepSection/StepCard.vue b/frontend/src/components/Plan/components/StepSection/StepCard.vue
new file mode 100644
index 0000000000..e23e310521
--- /dev/null
+++ b/frontend/src/components/Plan/components/StepSection/StepCard.vue
@@ -0,0 +1,147 @@
+<template>
+ <div class="step" :class="stepClass">
+ <div class="text" @click="handleClickStep">
+ <div class="text-sm min-w-32 lg:min-w-fit space-x-1 whitespace-nowrap">
+ <heroicons:arrow-small-right
+ v-if="isSelectedStep"
+ class="w-5 h-5 inline-block mb-0.5"
+ />
+ <span>{{ step.title }} {{ $t("common.stage") }}</span>
+ </div>
+ </div>
+
+ <NTooltip
+ v-if="isCreating && stepMissingStatement"
+ trigger="hover"
+ placement="top"
+ >
+ <template #trigger>
+ <heroicons:exclamation-circle-solid
+ class="w-6 h-6 ml-2 text-error hover:text-error-hover"
+ />
+ </template>
+ <span>{{ $t("issue.missing-sql-statement") }}</span>
+ </NTooltip>
+ <NTooltip
+ v-if="
+ !isCreating &&
+ (planCheckStatus === PlanCheckRun_Result_Status.ERROR ||
+ planCheckStatus === PlanCheckRun_Result_Status.WARNING)
+ "
+ trigger="hover"
+ placement="top"
+ >
+ <template #trigger>
+ <heroicons:exclamation-circle-solid
+ class="w-6 h-6 ml-2"
+ :class="[
+ planCheckStatus === PlanCheckRun_Result_Status.ERROR
+ ? 'text-error hover:text-error-hover'
+ : 'text-warning hover:text-warning-hover',
+ ]"
+ />
+ </template>
+ <span>{{
+ $t(
+ "custom-approval.issue-review.disallow-approve-reason.some-task-checks-didnt-pass"
+ )
+ }}</span>
+ </NTooltip>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { head, isEqual, uniqBy } from "lodash-es";
+import { NTooltip } from "naive-ui";
+import { computed } from "vue";
+import { sheetNameForSpec } from "@/components/Plan";
+import {
+ getLocalSheetByName,
+ planCheckRunListForSpec,
+ planCheckRunSummaryForCheckRunList,
+ usePlanContext,
+} from "@/components/Plan/logic";
+import { useSheetV1Store } from "@/store";
+import type { Plan_Step } from "@/types/proto/v1/plan_service";
+import { PlanCheckRun_Result_Status } from "@/types/proto/v1/plan_service";
+import { extractSheetUID, getSheetStatement } from "@/utils";
+
+const props = defineProps<{
+ step: Plan_Step;
+}>();
+
+const { isCreating, plan, selectedStep, events } = usePlanContext();
+
+const isSelectedStep = computed(() => {
+ return isEqual(props.step, selectedStep.value);
+});
+
+const stepClass = computed(() => {
+ const classList: string[] = [];
+ if (isSelectedStep.value) classList.push("selected");
+ return classList;
+});
+
+const stepMissingStatement = computed(() => {
+ for (const spec of props.step.specs) {
+ const sheetName = sheetNameForSpec(spec);
+ const uid = extractSheetUID(sheetName);
+ if (uid.startsWith("-")) {
+ const sheet = getLocalSheetByName(sheetName);
+ if (getSheetStatement(sheet).length === 0) {
+ return true;
+ }
+ } else {
+ const sheet = useSheetV1Store().getSheetByName(sheetName);
+ if (!sheet) {
+ return true;
+ }
+ if (getSheetStatement(sheet).length === 0) {
+ return true;
+ }
+ }
+ }
+ return false;
+});
+
+const planCheckStatus = computed((): PlanCheckRun_Result_Status => {
+ if (isCreating.value) return PlanCheckRun_Result_Status.UNRECOGNIZED;
+ const planCheckList = uniqBy(
+ props.step.specs.flatMap((spec) =>
+ planCheckRunListForSpec(plan.value, spec)
+ ),
+ (checkRun) => checkRun.uid
+ );
+ const summary = planCheckRunSummaryForCheckRunList(planCheckList);
+ if (summary.errorCount > 0) {
+ return PlanCheckRun_Result_Status.ERROR;
+ }
+ if (summary.warnCount > 0) {
+ return PlanCheckRun_Result_Status.WARNING;
+ }
+ return PlanCheckRun_Result_Status.SUCCESS;
+});
+
+const handleClickStep = () => {
+ if (isSelectedStep.value) return;
+
+ const spec = head(props.step.specs);
+ if (!spec) {
+ return;
+ }
+ events.emit("select-spec", { spec });
+};
+</script>
+
+<style scoped lang="postcss">
+.step {
+ @apply cursor-default flex items-center justify-start w-full text-sm relative;
+ @apply lg:flex-1;
+}
+.step .text {
+ @apply cursor-pointer flex-1 flex flex-col text-gray-600 font-normal;
+}
+.step.selected .text {
+ @apply font-bold text-accent underline;
+}
+</style>
diff --git a/frontend/src/components/Plan/components/StepSection/StepSection.vue b/frontend/src/components/Plan/components/StepSection/StepSection.vue
new file mode 100644
index 0000000000..de19f57c01
--- /dev/null
+++ b/frontend/src/components/Plan/components/StepSection/StepSection.vue
@@ -0,0 +1,60 @@
+<template>
+ <div class="w-full flex flex-col divide-y">
+ <template v-if="stepList.length > 0">
+ <div class="px-0">
+ <NScrollbar :x-scrollable="true" class="max-h-[180px] sm:max-h-max">
+ <div
+ class="flex flex-col sm:flex-row justify-between divide-y sm:divide-y-0"
+ >
+ <template
+ v-for="(step, index) in stepList"
+ :key="`${index}-${step - title}`"
+ >
+ <StepCard
+ :step="step"
+ :index="index"
+ class="px-2 sm:px-0 h-10"
+ :class="[
+ index === 0 && 'sm:pl-4',
+ index === stepList.length - 1 && 'sm:pr-4',
+ ]"
+ />
+ <div
+ v-if="index < stepList.length - 1"
+ class="hidden h-10 sm:block w-3.5 mr-2 pointer-events-none shrink-0"
+ aria-hidden="true"
+ >
+ <svg
+ class="h-full w-full text-gray-300"
+ viewBox="0 0 22 80"
+ fill="none"
+ preserveAspectRatio="none"
+ >
+ <path
+ d="M0 -2L20 40L0 82"
+ vector-effect="non-scaling-stroke"
+ stroke="currentcolor"
+ stroke-linejoin="round"
+ />
+ </svg>
+ </div>
+ </template>
+ </div>
+ </NScrollbar>
+ </div>
+ </template>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { NScrollbar } from "naive-ui";
+import { computed } from "vue";
+import { usePlanContext } from "@/components/Plan/logic";
+import StepCard from "./StepCard.vue";
+
+const { plan } = usePlanContext();
+
+const stepList = computed(() => {
+ return plan.value.steps || [];
+});
+</script>
diff --git a/frontend/src/components/Plan/components/StepSection/index.ts b/frontend/src/components/Plan/components/StepSection/index.ts
new file mode 100644
index 0000000000..52c2289789
--- /dev/null
+++ b/frontend/src/components/Plan/components/StepSection/index.ts
@@ -0,0 +1,3 @@
+import StepSection from "./StepSection.vue";
+
+export default StepSection;
diff --git a/frontend/src/components/Plan/components/common/DropdownItemWithErrorList.vue b/frontend/src/components/Plan/components/common/DropdownItemWithErrorList.vue
new file mode 100644
index 0000000000..3de4e2e66e
--- /dev/null
+++ b/frontend/src/components/Plan/components/common/DropdownItemWithErrorList.vue
@@ -0,0 +1,23 @@
+<template>
+ <NTooltip
+ :disabled="errors.length === 0"
+ :keep-alive-on-hover="false"
+ style="width: max-content"
+ >
+ <template #trigger>
+ <slot />
+ </template>
+ <template #default>
+ <ErrorList :errors="errors" />
+ </template>
+ </NTooltip>
+</template>
+
+<script lang="ts" setup>
+import { NTooltip } from "naive-ui";
+import ErrorList from "./ErrorList.vue";
+
+defineProps<{
+ errors: string[];
+}>();
+</script>
diff --git a/frontend/src/components/Plan/components/common/ErrorList.vue b/frontend/src/components/Plan/components/common/ErrorList.vue
new file mode 100644
index 0000000000..da82a653fe
--- /dev/null
+++ b/frontend/src/components/Plan/components/common/ErrorList.vue
@@ -0,0 +1,23 @@
+<template>
+ <ul
+ class="flex flex-col whitespace-nowrap"
+ :class="[errors.length > 1 && bullets && 'list-disc pl-4']"
+ >
+ <li v-for="(error, i) in errors" :key="i">
+ <slot name="prefix" />
+ {{ error }}
+ </li>
+ </ul>
+</template>
+
+<script setup lang="ts">
+withDefaults(
+ defineProps<{
+ errors: string[];
+ bullets?: boolean;
+ }>(),
+ {
+ bullets: true,
+ }
+);
+</script>
diff --git a/frontend/src/components/Plan/components/common/TaskSpinner.vue b/frontend/src/components/Plan/components/common/TaskSpinner.vue
new file mode 100644
index 0000000000..5ce2098fc7
--- /dev/null
+++ b/frontend/src/components/Plan/components/common/TaskSpinner.vue
@@ -0,0 +1,22 @@
+<template>
+ <svg
+ class="animate-spin"
+ xmlns="http://www.w3.org/2000/svg"
+ fill="none"
+ viewBox="0 0 24 24"
+ >
+ <circle
+ class="opacity-25"
+ cx="12"
+ cy="12"
+ r="10"
+ stroke="currentColor"
+ stroke-width="4"
+ />
+ <path
+ class="opacity-75"
+ fill="currentColor"
+ d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
+ />
+ </svg>
+</template>
diff --git a/frontend/src/components/Plan/components/common/index.ts b/frontend/src/components/Plan/components/common/index.ts
new file mode 100644
index 0000000000..0cdc6f3693
--- /dev/null
+++ b/frontend/src/components/Plan/components/common/index.ts
@@ -0,0 +1,5 @@
+import DropdownItemWithErrorList from "./DropdownItemWithErrorList.vue";
+import ErrorList from "./ErrorList.vue";
+import TaskSpinner from "./TaskSpinner.vue";
+
+export { ErrorList, DropdownItemWithErrorList, TaskSpinner };
diff --git a/frontend/src/components/Plan/components/index.ts b/frontend/src/components/Plan/components/index.ts
new file mode 100644
index 0000000000..3ec69243fe
--- /dev/null
+++ b/frontend/src/components/Plan/components/index.ts
@@ -0,0 +1,17 @@
+import DescriptionSection from "./DescriptionSection";
+import HeaderSection from "./HeaderSection";
+import PlanCheckSection from "./PlanCheckSection";
+import SQLCheckSection from "./SQLCheckSection";
+import SpecListSection from "./SpecListSection";
+import StatementSection from "./StatementSection";
+import StepSection from "./StepSection";
+
+export {
+ HeaderSection,
+ StepSection,
+ SpecListSection,
+ PlanCheckSection,
+ StatementSection,
+ DescriptionSection,
+ SQLCheckSection,
+};
diff --git a/frontend/src/components/Plan/index.ts b/frontend/src/components/Plan/index.ts
new file mode 100644
index 0000000000..33745ea948
--- /dev/null
+++ b/frontend/src/components/Plan/index.ts
@@ -0,0 +1,5 @@
+import PlanDetailPage from "./PlanDetailPage.vue";
+
+export * from "./logic";
+
+export { PlanDetailPage };
diff --git a/frontend/src/components/Plan/logic/base.ts b/frontend/src/components/Plan/logic/base.ts
new file mode 100644
index 0000000000..07c716072e
--- /dev/null
+++ b/frontend/src/components/Plan/logic/base.ts
@@ -0,0 +1,71 @@
+import Emittery from "emittery";
+import { first } from "lodash-es";
+import { useDialog } from "naive-ui";
+import { computed } from "vue";
+import { useRoute, useRouter } from "vue-router";
+import { PROJECT_V1_ROUTE_PLAN_DETAIL } from "@/router/dashboard/projectV1";
+import { useUIStateStore } from "@/store";
+import type { Plan_Spec, Plan_Step } from "@/types/proto/v1/plan_service";
+import { emptyPlanSpec, emptyPlanStep } from "@/types/v1/issue/plan";
+import { flattenSpecList } from "@/utils";
+import type { PlanContext, PlanEvents } from "./context";
+import { stepForSpec } from "./utils";
+
+export const useBasePlanContext = (
+ context: Pick<PlanContext, "isCreating" | "ready" | "plan">
+): Partial<PlanContext> => {
+ const { plan } = context;
+ const uiStateStore = useUIStateStore();
+ const route = useRoute();
+ const router = useRouter();
+ const dialog = useDialog();
+
+ const events: PlanEvents = new Emittery();
+
+ const specs = computed(() => flattenSpecList(plan.value));
+
+ const selectedSpec = computed((): Plan_Spec => {
+ // Check if spec is selected from URL.
+ const specId = route.query.spec as string;
+ if (specId) {
+ const specFound = specs.value.find((spec) => spec.id === specId);
+ if (specFound) {
+ return specFound;
+ }
+ }
+
+ // Fallback to first spec.
+ return first(specs.value) || emptyPlanSpec();
+ });
+
+ const selectedStep = computed((): Plan_Step => {
+ return stepForSpec(plan.value, selectedSpec.value) || emptyPlanStep();
+ });
+
+ const formatOnSave = computed({
+ get: () => uiStateStore.editorFormatStatementOnSave,
+ set: (value: boolean) => uiStateStore.setEditorFormatStatementOnSave(value),
+ });
+
+ events.on("select-spec", ({ spec }) => {
+ const step = stepForSpec(plan.value, spec);
+ if (!step) return;
+
+ router.replace({
+ name: PROJECT_V1_ROUTE_PLAN_DETAIL,
+ query: {
+ ...route.query,
+ spec: spec.id,
+ },
+ hash: route.hash,
+ });
+ });
+
+ return {
+ events,
+ selectedSpec,
+ selectedStep,
+ formatOnSave,
+ dialog,
+ };
+};
diff --git a/frontend/src/components/Plan/logic/common.ts b/frontend/src/components/Plan/logic/common.ts
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/frontend/src/components/Plan/logic/context.ts b/frontend/src/components/Plan/logic/context.ts
new file mode 100644
index 0000000000..782031bac3
--- /dev/null
+++ b/frontend/src/components/Plan/logic/context.ts
@@ -0,0 +1,49 @@
+import type Emittery from "emittery";
+import type { useDialog } from "naive-ui";
+import { v4 as uuidv4 } from "uuid";
+import type { InjectionKey, Ref } from "vue";
+import { inject, provide } from "vue";
+import type { Plan_Spec, Plan_Step } from "@/types/proto/v1/plan_service";
+import type { ComposedPlan } from "@/types/v1/issue/plan";
+
+export type PlanEvents = Emittery<{
+ "select-spec": { spec: Plan_Spec };
+}>;
+
+export type PlanContext = {
+ // Basic fields
+ isCreating: Ref<boolean>;
+ ready: Ref<boolean>;
+ plan: Ref<ComposedPlan>;
+
+ selectedStep: Ref<Plan_Step>;
+ selectedSpec: Ref<Plan_Spec>;
+ formatOnSave: Ref<boolean>;
+
+ // UI events
+ events: PlanEvents;
+
+ // misc
+ dialog: ReturnType<typeof useDialog>;
+ reInitialize: (overrides?: Record<string, string>) => Promise<void>;
+};
+
+const KEY = Symbol(`bb.plan.context.${uuidv4()}`) as InjectionKey<PlanContext>;
+
+export const usePlanContext = () => {
+ return inject(KEY)!;
+};
+
+export const providePlanContext = (
+ context: Partial<PlanContext>,
+ root = false
+) => {
+ if (!root) {
+ const parent = usePlanContext();
+ context = {
+ ...parent,
+ ...context,
+ };
+ }
+ provide(KEY, context as PlanContext);
+};
diff --git a/frontend/src/components/Plan/logic/index.ts b/frontend/src/components/Plan/logic/index.ts
new file mode 100644
index 0000000000..c4bac3a552
--- /dev/null
+++ b/frontend/src/components/Plan/logic/index.ts
@@ -0,0 +1,7 @@
+export * from "./context";
+export * from "./base";
+export * from "./plan";
+export * from "./initialize";
+export * from "./sheet";
+export * from "./plan-check";
+export * from "./poll";
diff --git a/frontend/src/components/Plan/logic/initialize/create.ts b/frontend/src/components/Plan/logic/initialize/create.ts
new file mode 100644
index 0000000000..ec0092b1aa
--- /dev/null
+++ b/frontend/src/components/Plan/logic/initialize/create.ts
@@ -0,0 +1,513 @@
+import { cloneDeep, groupBy, isNaN, isNumber, orderBy } from "lodash-es";
+import { v4 as uuidv4 } from "uuid";
+import { useRoute } from "vue-router";
+import type { TemplateType } from "@/plugins";
+import {
+ useBranchStore,
+ useChangelistStore,
+ useDatabaseV1Store,
+ useEnvironmentV1Store,
+ useProjectV1Store,
+ useSheetV1Store,
+} from "@/store";
+import { projectNamePrefix } from "@/store/modules/v1/common";
+import { composePlan } from "@/store/modules/v1/plan";
+import type { ComposedProject } from "@/types";
+import { UNKNOWN_ID } from "@/types";
+import { DatabaseConfig } from "@/types/proto/v1/database_service";
+import {
+ Plan,
+ Plan_ChangeDatabaseConfig,
+ Plan_ChangeDatabaseConfig_Type,
+ Plan_Spec,
+ Plan_Step,
+} from "@/types/proto/v1/plan_service";
+import { Sheet, SheetPayload } from "@/types/proto/v1/sheet_service";
+import {
+ extractSheetUID,
+ generateSQLForChangeToDatabase,
+ getSheetStatement,
+ setSheetStatement,
+} from "@/utils";
+import { databaseEngineForSpec, sheetNameForSpec } from "../plan";
+import { createEmptyLocalSheet, getLocalSheetByName } from "../sheet";
+
+export type InitialSQL = {
+ sqlList?: string[];
+ sql?: string;
+};
+
+type CreatePlanParams = {
+ databaseUIDList: string[];
+ project: ComposedProject;
+ query: Record<string, string>;
+ initialSQL: InitialSQL;
+ branch?: string;
+};
+
+const state = {
+ uid: -101,
+};
+const nextUID = () => {
+ return String(state.uid--);
+};
+
+export const createPlanSkeleton = async (
+ route: ReturnType<typeof useRoute>,
+ query: Record<string, string>
+) => {
+ const projectName = route.params.projectId as string;
+ const project = await useProjectV1Store().getOrFetchProjectByName(
+ `${projectNamePrefix}${projectName}`
+ );
+ const databaseIdList = (query.databaseList ?? "").split(",");
+ const databaseUIDList = await prepareDatabaseUIDList(databaseIdList);
+ await prepareDatabaseList(databaseUIDList, project.uid);
+
+ const params: CreatePlanParams = {
+ databaseUIDList,
+ project,
+ query,
+ initialSQL: extractInitialSQLListFromQuery(query),
+ };
+
+ // Prepare params context for building plan.
+ await prepareParamsContext(params);
+
+ const plan = await buildPlan(params);
+ return plan;
+};
+
+const prepareParamsContext = async (params: CreatePlanParams) => {
+ if (params.branch) {
+ await useBranchStore().fetchBranchByName(params.branch);
+ }
+};
+
+export const buildPlan = async (params: CreatePlanParams) => {
+ const { databaseUIDList, project, query } = params;
+
+ const plan = Plan.fromJSON({
+ uid: nextUID(),
+ });
+ plan.name = `${project.name}/plans/${plan.uid}`;
+ plan.title = query.name;
+ plan.description = query.description;
+ if (query.changelist) {
+ // build plan for changelist
+ plan.steps = await buildStepsViaChangelist(
+ databaseUIDList,
+ query.changelist,
+ params
+ );
+ } else if (query.batch === "1") {
+ // in tenant mode, all specs share a unique sheet
+ const sheetUID = nextUID();
+ // build tenant plan
+ if (databaseUIDList.length === 0) {
+ // evaluate DeploymentConfig and generate steps/specs
+ if (query.databaseGroupName) {
+ plan.steps = await buildStepsForDatabaseGroup(
+ params,
+ query.databaseGroupName
+ );
+ } else {
+ plan.steps = await buildStepsViaDeploymentConfig(params, sheetUID);
+ }
+ } else {
+ plan.steps = await buildSteps(databaseUIDList, params, sheetUID);
+ }
+ } else {
+ // build standard plan
+ plan.steps = await buildSteps(databaseUIDList, params, undefined);
+ }
+ return await composePlan(plan);
+};
+
+export const buildSteps = async (
+ databaseUIDList: string[],
+ params: CreatePlanParams,
+ sheetUID?: string // if specified, all specs will share the same sheet
+) => {
+ const databaseList = databaseUIDList.map((uid) =>
+ useDatabaseV1Store().getDatabaseByUID(uid)
+ );
+
+ const databaseListGroupByEnvironment = groupBy(
+ databaseList,
+ (db) => db.effectiveEnvironment
+ );
+ const stepList = orderBy(
+ Object.keys(databaseListGroupByEnvironment).map((env) => {
+ const environment = useEnvironmentV1Store().getEnvironmentByName(env);
+ const databases = databaseListGroupByEnvironment[env];
+ return {
+ environment,
+ databases,
+ };
+ }),
+ [(step) => step.environment?.order],
+ ["asc"]
+ );
+
+ const steps: Plan_Step[] = [];
+ for (let i = 0; i < stepList.length; i++) {
+ const { environment, databases } = stepList[i];
+ const step = Plan_Step.fromJSON({
+ // Use environment title as step title.
+ title: environment?.title,
+ });
+ for (let j = 0; j < databases.length; j++) {
+ const db = databases[j];
+ const sqlIndex = databaseUIDList.findIndex((uid) => uid === db.uid);
+ const spec = await buildSpecForTarget(db.name, params, sheetUID);
+ step.specs.push(spec);
+ maybeSetInitialSQLForSpec(spec, sqlIndex, params);
+ maybeSetInitialDatabaseConfigForSpec(spec, params);
+ }
+ steps.push(step);
+ }
+ return steps;
+};
+
+export const buildStepsForDatabaseGroup = async (
+ params: CreatePlanParams,
+ databaseGroupName: string
+) => {
+ // Create sheet from SQL template in URL query
+ // The sheet will be used when previewing plan
+ const sql = params.initialSQL.sql ?? "";
+ const sheetCreate = Sheet.fromPartial({
+ ...createEmptyLocalSheet(),
+ engine: await databaseEngineForSpec(params.project, databaseGroupName),
+ });
+ setSheetStatement(sheetCreate, sql);
+ const sheet = await useSheetV1Store().createSheet(
+ params.project.name,
+ sheetCreate
+ );
+
+ const spec = await buildSpecForTarget(
+ databaseGroupName,
+ params,
+ extractSheetUID(sheet.name)
+ );
+ const step = Plan_Step.fromJSON({
+ specs: [spec],
+ });
+ return [step];
+};
+
+export const buildStepsViaDeploymentConfig = async (
+ params: CreatePlanParams,
+ sheetUID: string
+) => {
+ const { project } = params;
+ const spec = await buildSpecForTarget(
+ `${project.name}/deploymentConfigs/default`,
+ params,
+ sheetUID
+ );
+ maybeSetInitialSQLForSpec(spec, 0, params);
+ maybeSetInitialDatabaseConfigForSpec(spec, params);
+ const step = Plan_Step.fromPartial({
+ specs: [spec],
+ });
+ return [step];
+};
+
+export const buildStepsViaChangelist = async (
+ databaseUIDList: string[],
+ changelistResourceName: string,
+ params: CreatePlanParams
+) => {
+ const changelist = await useChangelistStore().getOrFetchChangelistByName(
+ changelistResourceName
+ );
+ const { changes } = changelist;
+
+ const databaseList = databaseUIDList.map((uid) =>
+ useDatabaseV1Store().getDatabaseByUID(uid)
+ );
+
+ const databaseListGroupByEnvironment = groupBy(
+ databaseList,
+ (db) => db.effectiveEnvironment
+ );
+ const stepList = orderBy(
+ Object.keys(databaseListGroupByEnvironment).map((env) => {
+ const environment = useEnvironmentV1Store().getEnvironmentByName(env);
+ const databases = databaseListGroupByEnvironment[env];
+ return {
+ environment,
+ databases,
+ };
+ }),
+ [(step) => step.environment?.order],
+ ["asc"]
+ );
+
+ const steps: Plan_Step[] = [];
+ for (let i = 0; i < stepList.length; i++) {
+ const step = Plan_Step.fromJSON({});
+ const { databases } = stepList[i];
+ for (let j = 0; j < databases.length; j++) {
+ const db = databases[j];
+ for (let k = 0; k < changes.length; k++) {
+ const change = changes[k];
+ const statement = await generateSQLForChangeToDatabase(change, db);
+ const sheetUID = nextUID();
+ const sheetName = `${params.project.name}/sheets/${sheetUID}`;
+ const sheet = getLocalSheetByName(sheetName);
+ setSheetStatement(sheet, statement);
+ const spec = await buildSpecForTarget(
+ db.name,
+ params,
+ sheetUID,
+ change.version
+ );
+ step.specs.push(spec);
+ }
+ }
+ steps.push(step);
+ }
+
+ return steps;
+};
+
+export const buildSpecForTarget = async (
+ target: string,
+ { project, query }: CreatePlanParams,
+ sheetUID?: string,
+ version?: string
+) => {
+ const sheet = `${project.name}/sheets/${sheetUID ?? nextUID()}`;
+ const template = query.template as TemplateType | undefined;
+ const spec = Plan_Spec.fromJSON({
+ id: uuidv4(),
+ });
+ if (template === "bb.issue.database.data.update") {
+ spec.changeDatabaseConfig = Plan_ChangeDatabaseConfig.fromJSON({
+ target,
+ type: Plan_ChangeDatabaseConfig_Type.DATA,
+ });
+ if (query.sheetId) {
+ const sheet = await useSheetV1Store().getOrFetchSheetByUID(
+ query.sheetId,
+ "FULL"
+ );
+ if (sheet) {
+ spec.changeDatabaseConfig.sheet = sheet.name;
+ }
+ }
+ if (!spec.changeDatabaseConfig.sheet) {
+ spec.changeDatabaseConfig.sheet = sheet;
+ }
+ if (version) {
+ spec.changeDatabaseConfig.schemaVersion = version;
+ }
+ }
+ if (template === "bb.issue.database.schema.update") {
+ const type =
+ query.ghost === "1"
+ ? Plan_ChangeDatabaseConfig_Type.MIGRATE_GHOST
+ : Plan_ChangeDatabaseConfig_Type.MIGRATE;
+ spec.changeDatabaseConfig = Plan_ChangeDatabaseConfig.fromJSON({
+ target,
+ type,
+ sheet,
+ });
+
+ if (query.sheetId) {
+ const remoteSheet = await useSheetV1Store().getOrFetchSheetByUID(
+ query.sheetId,
+ "FULL"
+ );
+ if (remoteSheet) {
+ // make a local copy for remote sheet for further editing
+ console.debug(
+ "copy remote sheet to local for further editing",
+ remoteSheet
+ );
+ const localSheet = getLocalSheetByName(sheet);
+ localSheet.payload = cloneDeep(remoteSheet.payload);
+ const statement = getSheetStatement(remoteSheet);
+ setSheetStatement(localSheet, statement);
+ }
+ }
+
+ if (version) {
+ spec.changeDatabaseConfig.schemaVersion = version;
+ }
+ }
+
+ return spec;
+};
+
+const maybeSetInitialSQLForSpec = (
+ spec: Plan_Spec,
+ index: number,
+ params: CreatePlanParams
+) => {
+ const sheet = sheetNameForSpec(spec);
+ if (!sheet) return;
+ const uid = extractSheetUID(sheet);
+ if (!uid.startsWith("-")) {
+ // If the sheet is a remote sheet, ignore initial SQL in URL query
+ return;
+ }
+ // Priority: sqlList[index] -> sql -> nothing
+ const sql = params.initialSQL.sqlList?.[index] ?? params.initialSQL.sql ?? "";
+ if (sql) {
+ const sheetEntity = getLocalSheetByName(sheet);
+ setSheetStatement(sheetEntity, sql);
+ }
+};
+
+const maybeSetInitialDatabaseConfigForSpec = async (
+ spec: Plan_Spec,
+ params: CreatePlanParams
+) => {
+ const branch = params.branch;
+ if (!branch) {
+ return;
+ }
+
+ const sheetName = sheetNameForSpec(spec);
+ if (!sheetName) return;
+ const uid = extractSheetUID(sheetName);
+ if (!uid.startsWith("-")) {
+ // If the sheet is a remote sheet, ignore initial Database configs.
+ return;
+ }
+
+ // TODO(d): double check setting database config.
+ const temp = await useBranchStore().fetchBranchByName(branch);
+ if (temp) {
+ const sheetEntity = getLocalSheetByName(sheetName);
+ if (!sheetEntity.payload) {
+ sheetEntity.payload = SheetPayload.fromPartial({});
+ }
+ sheetEntity.payload.databaseConfig = DatabaseConfig.fromPartial({
+ schemaConfigs: temp.schemaMetadata?.schemaConfigs,
+ });
+ sheetEntity.payload.baselineDatabaseConfig = DatabaseConfig.fromPartial({
+ schemaConfigs: temp.baselineSchemaMetadata?.schemaConfigs,
+ });
+ }
+};
+
+const extractInitialSQLListFromQuery = (
+ query: Record<string, string>
+): {
+ sqlList?: string[];
+ sql?: string;
+} => {
+ const sqlListJSON = query.sqlList;
+ if (sqlListJSON && sqlListJSON.startsWith("[") && sqlListJSON.endsWith("]")) {
+ try {
+ const sqlList = JSON.parse(sqlListJSON) as string[];
+ if (Array.isArray(sqlList)) {
+ if (sqlList.every((maybeSQL) => typeof maybeSQL === "string")) {
+ return {
+ sqlList,
+ };
+ }
+ }
+ } catch {
+ // Nothing
+ }
+ }
+ const sql = query.sql;
+ if (sql && typeof sql === "string") {
+ return {
+ sql,
+ };
+ }
+ return {};
+};
+
+export const prepareDatabaseList = async (
+ databaseUIDList: string[],
+ projectUID: string
+) => {
+ const databaseStore = useDatabaseV1Store();
+ if (projectUID && projectUID !== String(UNKNOWN_ID)) {
+ // For preparing the database if user visits creating plan url directly.
+ // It's horrible to fetchDatabaseByUID one-by-one when query.databaseList
+ // is big (100+ sometimes)
+ // So we are fetching databaseList by project since that's better cached.
+ const project =
+ await useProjectV1Store().getOrFetchProjectByUID(projectUID);
+ await prepareDatabaseListByProject(project.name);
+ } else {
+ // Otherwise, we don't have the projectUID (very rare to see, theoretically)
+ // so we need to fetch the first database in databaseList by id,
+ // and see what project it belongs.
+ if (databaseUIDList.length > 0) {
+ const firstDB = await databaseStore.getOrFetchDatabaseByUID(
+ databaseUIDList[0]
+ );
+ if (databaseUIDList.length > 1) {
+ await prepareDatabaseListByProject(firstDB.project);
+ }
+ }
+ }
+};
+
+const prepareDatabaseListByProject = async (project: string) => {
+ const filters = [`instance = "instances/-"`, `project = "${project}"`];
+ await useDatabaseV1Store().searchDatabases({
+ filter: filters.join(" && "),
+ });
+};
+
+export const isValidSpec = (spec: Plan_Spec): boolean => {
+ if (spec.changeDatabaseConfig || spec.exportDataConfig) {
+ const sheetName = sheetNameForSpec(spec);
+ if (!sheetName) {
+ return false;
+ }
+ const uid = extractSheetUID(sheetName);
+ if (uid.startsWith("-")) {
+ const sheet = getLocalSheetByName(sheetName);
+ if (getSheetStatement(sheet).length === 0) {
+ return false;
+ }
+ } else {
+ const sheet = useSheetV1Store().getSheetByName(sheetName);
+ if (!sheet) {
+ return false;
+ }
+ if (getSheetStatement(sheet).length === 0) {
+ return false;
+ }
+ }
+ }
+ return true;
+};
+
+const prepareDatabaseUIDList = async (
+ // databaseIdList is a list of database identifiers. Including UID and resource id.
+ // e.g. ["103", "205", "instances/mysql/databases/employee"]
+ databaseIdList: string[]
+) => {
+ const databaseStore = useDatabaseV1Store();
+ const databaseUIDList = [];
+ for (const maybeUID of databaseIdList) {
+ if (!maybeUID || maybeUID === String(UNKNOWN_ID)) {
+ continue;
+ }
+ const uid = Number(maybeUID);
+ if (isNumber(uid) && !isNaN(uid)) {
+ databaseUIDList.push(maybeUID);
+ continue;
+ }
+ const database = await databaseStore.getOrFetchDatabaseByName(
+ maybeUID,
+ true // silent
+ );
+ databaseUIDList.push(database.uid);
+ }
+ return databaseUIDList.filter((id) => id && id !== String(UNKNOWN_ID));
+};
diff --git a/frontend/src/components/Plan/logic/initialize/index.ts b/frontend/src/components/Plan/logic/initialize/index.ts
new file mode 100644
index 0000000000..1f0616724c
--- /dev/null
+++ b/frontend/src/components/Plan/logic/initialize/index.ts
@@ -0,0 +1,95 @@
+import type { MaybeRef } from "vue";
+import { computed, ref, unref, watch } from "vue";
+import type { LocationQuery } from "vue-router";
+import { useRoute, useRouter } from "vue-router";
+import { fetchPlanByUID } from "@/store/modules/v1/plan";
+import { EMPTY_ID, UNKNOWN_ID } from "@/types";
+import { emptyPlan, type ComposedPlan } from "@/types/v1/issue/plan";
+import { uidFromSlug } from "@/utils";
+import { createPlanSkeleton } from "./create";
+
+export * from "./create";
+
+export function useInitializePlan(
+ planSlug: MaybeRef<string>,
+ project: MaybeRef<string> = "-",
+ redirectNotFound: boolean = true
+) {
+ const isCreating = computed(() => {
+ return unref(planSlug).toLowerCase() === "create";
+ });
+ const uid = computed(() => {
+ const slug = unref(planSlug);
+ if (slug.toLowerCase() === "create") return String(EMPTY_ID);
+ const uid = Number(uidFromSlug(slug));
+ if (uid > 0) return String(uid);
+ return String(UNKNOWN_ID);
+ });
+ const route = useRoute();
+ const router = useRouter();
+ const isInitializing = ref(false);
+
+ const plan = ref<ComposedPlan>(emptyPlan());
+
+ const runner = async (uid: string, project: string, url: string) => {
+ const plan =
+ uid === String(EMPTY_ID)
+ ? await createPlanSkeleton(
+ route,
+ convertRouterQuery(router.resolve(url).query)
+ )
+ : await fetchPlanByUID(uid, project);
+ return {
+ plan,
+ url,
+ };
+ };
+
+ watch(
+ [uid, () => unref(project)],
+ ([uid, project]) => {
+ if (uid === String(UNKNOWN_ID) && redirectNotFound) {
+ router.push({ name: "error.404" });
+ return;
+ }
+ const url = route.fullPath;
+ isInitializing.value = true;
+ runner(uid, project, url).then((result) => {
+ if (result.url !== route.fullPath) {
+ // the url changed, drop the outdated result
+ return;
+ }
+ plan.value = result.plan;
+ isInitializing.value = false;
+ });
+ },
+ { immediate: true }
+ );
+
+ const reInitialize = async (overrides: Record<string, string> = {}) => {
+ const url = route.fullPath;
+ const query = convertRouterQuery(router.resolve(url).query);
+ try {
+ const updated = await createPlanSkeleton(route, {
+ ...query,
+ ...overrides,
+ });
+ plan.value = updated;
+ } catch {
+ // Nothing
+ }
+ };
+
+ return { isCreating, plan, isInitializing, reInitialize };
+}
+
+export const convertRouterQuery = (query: LocationQuery) => {
+ const kv: Record<string, string> = {};
+ for (const key in query) {
+ const value = query[key];
+ if (typeof value === "string") {
+ kv[key] = value;
+ }
+ }
+ return kv;
+};
diff --git a/frontend/src/components/Plan/logic/plan-check.ts b/frontend/src/components/Plan/logic/plan-check.ts
new file mode 100644
index 0000000000..888064f4d0
--- /dev/null
+++ b/frontend/src/components/Plan/logic/plan-check.ts
@@ -0,0 +1,126 @@
+import { maxBy } from "lodash-es";
+import type { PlanCheckRun, Plan_Spec } from "@/types/proto/v1/plan_service";
+import {
+ PlanCheckRun_Result_Status,
+ PlanCheckRun_Status,
+ PlanCheckRun_Type,
+} from "@/types/proto/v1/plan_service";
+import type { ComposedPlan } from "@/types/v1/issue/plan";
+import { sheetNameForSpec, databaseForSpec } from ".";
+
+export const planSpecHasPlanChecks = (spec: Plan_Spec) => {
+ if (spec.createDatabaseConfig) {
+ return false;
+ }
+ if (spec.changeDatabaseConfig !== undefined) {
+ return true;
+ }
+ if (spec.exportDataConfig !== undefined) {
+ return true;
+ }
+ return false;
+};
+
+export const planCheckRunListForSpec = (
+ plan: ComposedPlan,
+ spec: Plan_Spec
+) => {
+ const target = databaseForSpec(plan, spec).name;
+ const sheet = spec ? sheetNameForSpec(spec) : "";
+ return plan.planCheckRunList.filter((check) => {
+ if (sheet && check.sheet) {
+ return check.sheet === sheet && check.target === target;
+ }
+ // Otherwise filter by target only
+ return check.target === target;
+ });
+};
+
+export const HiddenPlanCheckTypes = new Set<PlanCheckRun_Type>([
+ PlanCheckRun_Type.DATABASE_STATEMENT_SUMMARY_REPORT,
+]);
+
+export const planCheckRunResultStatus = (checkRun: PlanCheckRun) => {
+ let status = PlanCheckRun_Result_Status.SUCCESS;
+
+ for (const result of checkRun.results) {
+ if (result.status === PlanCheckRun_Result_Status.ERROR) {
+ return PlanCheckRun_Result_Status.ERROR;
+ }
+ if (result.status === PlanCheckRun_Result_Status.WARNING) {
+ status = PlanCheckRun_Result_Status.WARNING;
+ }
+ }
+ return status;
+};
+
+export type PlanCheckRunSummary = {
+ runningCount: number;
+ successCount: number;
+ warnCount: number;
+ errorCount: number;
+};
+
+export const planCheckRunSummaryForCheckRunList = (
+ planCheckRunList: PlanCheckRun[]
+) => {
+ const summary: PlanCheckRunSummary = {
+ runningCount: 0,
+ successCount: 0,
+ warnCount: 0,
+ errorCount: 0,
+ };
+
+ planCheckRunList = planCheckRunList.filter(
+ (check) => !HiddenPlanCheckTypes.has(check.type)
+ );
+
+ const listGroupByTypeTargetSheet = planCheckRunList.reduce(
+ (acc, checkRun) => {
+ const key = `${checkRun.type}-${checkRun.target}-${checkRun.sheet}`;
+ if (!acc[key]) {
+ acc[key] = [];
+ }
+ acc[key].push(checkRun);
+ return acc;
+ },
+ {} as { [key: string]: PlanCheckRun[] }
+ );
+
+ const latestCheckRunOfEachTypeTargetSheet = Object.keys(
+ listGroupByTypeTargetSheet
+ ).map((k) => {
+ const listOfTypeTargetSheet = listGroupByTypeTargetSheet[k];
+ const latest = maxBy(listOfTypeTargetSheet, (checkRun) =>
+ Number(checkRun.uid)
+ )!;
+ return latest;
+ });
+
+ for (const checkRun of latestCheckRunOfEachTypeTargetSheet) {
+ switch (checkRun.status) {
+ case PlanCheckRun_Status.CANCELED:
+ // nothing todo
+ break;
+ case PlanCheckRun_Status.FAILED:
+ summary.errorCount++;
+ break;
+ case PlanCheckRun_Status.RUNNING:
+ summary.runningCount++;
+ break;
+ case PlanCheckRun_Status.DONE:
+ switch (planCheckRunResultStatus(checkRun)) {
+ case PlanCheckRun_Result_Status.SUCCESS:
+ summary.successCount++;
+ break;
+ case PlanCheckRun_Result_Status.WARNING:
+ summary.warnCount++;
+ break;
+ case PlanCheckRun_Result_Status.ERROR:
+ summary.errorCount++;
+ }
+ }
+ }
+
+ return summary;
+};
diff --git a/frontend/src/components/Plan/logic/plan.ts b/frontend/src/components/Plan/logic/plan.ts
new file mode 100644
index 0000000000..e1fd5a6b6e
--- /dev/null
+++ b/frontend/src/components/Plan/logic/plan.ts
@@ -0,0 +1,156 @@
+import { head } from "lodash-es";
+import {
+ useDatabaseV1Store,
+ useDBGroupStore,
+ useDeploymentConfigV1Store,
+ useInstanceV1Store,
+} from "@/store";
+import { type ComposedProject, UNKNOWN_ID, unknownDatabase } from "@/types";
+import { Engine, State } from "@/types/proto/v1/common";
+import { InstanceResource } from "@/types/proto/v1/instance_service";
+import type { Plan_Spec } from "@/types/proto/v1/plan_service";
+import type { ComposedPlan } from "@/types/v1/issue/plan";
+import {
+ extractDatabaseResourceName,
+ extractDatabaseGroupName,
+ extractDeploymentConfigName,
+ getPipelineFromDeploymentScheduleV1,
+} from "@/utils";
+
+export const databaseForSpec = (plan: ComposedPlan, spec: Plan_Spec) => {
+ const { createDatabaseConfig, changeDatabaseConfig, exportDataConfig } = spec;
+ if (createDatabaseConfig !== undefined) {
+ const instance = createDatabaseConfig.target;
+ const databaseName = createDatabaseConfig.database;
+ const instanceEntity = useInstanceV1Store().getInstanceByName(instance);
+ return {
+ ...unknownDatabase(),
+ name: `${instance}/databases/${databaseName}`,
+ uid: String(UNKNOWN_ID),
+ databaseName,
+ instance,
+ instanceEntity,
+ project: plan.project,
+ projectEntity: plan.projectEntity,
+ effectiveEnvironment: instanceEntity.environment,
+ effectiveEnvironmentEntity: instanceEntity.environmentEntity,
+ };
+ } else if (
+ changeDatabaseConfig !== undefined ||
+ exportDataConfig !== undefined
+ ) {
+ // TODO(steven): handle db group and deployment config.
+ const target = (changeDatabaseConfig?.target ??
+ exportDataConfig?.target) as string;
+ const db = useDatabaseV1Store().getDatabaseByName(target);
+ if (db.uid === String(UNKNOWN_ID)) {
+ // Database not found, it's probably NOT_FOUND (maybe dropped actually)
+ // Mock a database using all known resources
+ db.project = plan.project;
+ db.projectEntity = plan.projectEntity;
+ db.name = target;
+ const { instance, databaseName } = extractDatabaseResourceName(db.name);
+ db.databaseName = databaseName;
+ db.instance = instance;
+ const instanceEntity = useInstanceV1Store().getInstanceByName(
+ db.instance
+ );
+ db.instanceEntity = instanceEntity;
+ db.instanceResource = InstanceResource.fromJSON(instanceEntity);
+ db.environment = instanceEntity.environment;
+ db.effectiveEnvironment = instanceEntity.environment;
+ db.effectiveEnvironmentEntity = instanceEntity.environmentEntity;
+ db.syncState = State.DELETED;
+ }
+ return db;
+ }
+ return unknownDatabase();
+};
+
+/**
+ *
+ * @returns empty string if no sheet found
+ */
+export const sheetNameForSpec = (spec: Plan_Spec): string => {
+ return spec.changeDatabaseConfig?.sheet ?? spec.exportDataConfig?.sheet ?? "";
+};
+
+export const databaseEngineForSpec = async (
+ project: ComposedProject,
+ specOrTarget?: Plan_Spec | string
+) => {
+ if (!specOrTarget) return Engine.ENGINE_UNSPECIFIED;
+
+ const getTarget = (specOrTarget: Plan_Spec | string) => {
+ if (typeof specOrTarget === "string") {
+ return specOrTarget;
+ }
+ const config =
+ specOrTarget.changeDatabaseConfig || specOrTarget.exportDataConfig;
+ if (!config) {
+ return Engine.ENGINE_UNSPECIFIED;
+ }
+ return config.target;
+ };
+ const target = getTarget(specOrTarget);
+
+ if (extractDatabaseResourceName(target).databaseName !== String(UNKNOWN_ID)) {
+ const db = await useDatabaseV1Store().getOrFetchDatabaseByName(
+ target,
+ /* silent */ true
+ );
+ if (db && db.uid !== String(UNKNOWN_ID)) {
+ return db.instanceEntity.engine;
+ }
+ }
+ if (extractDatabaseGroupName(target)) {
+ const dbGroup = await useDBGroupStore().getOrFetchDBGroupByName(target);
+ // Might be flaky: use the first database in the db group
+ const dbName = head(dbGroup.matchedDatabases)?.name;
+ if (dbName) {
+ const db = await useDatabaseV1Store().getOrFetchDatabaseByName(
+ dbName,
+ /* silent */ true
+ );
+ if (db && db.uid !== String(UNKNOWN_ID)) {
+ return db.instanceEntity.engine;
+ }
+ }
+ }
+ if (extractDeploymentConfigName(target)) {
+ const deploymentConfig =
+ await useDeploymentConfigV1Store().fetchDeploymentConfigByProjectName(
+ project.name
+ );
+ if (deploymentConfig) {
+ const databaseList = useDatabaseV1Store().databaseListByProject(
+ project.name
+ );
+ const pipeline = getPipelineFromDeploymentScheduleV1(
+ databaseList,
+ deploymentConfig.schedule
+ );
+ const db = head(head(pipeline));
+ if (db && db.uid !== String(UNKNOWN_ID)) {
+ return db.instanceEntity.engine;
+ }
+ }
+ }
+ return Engine.ENGINE_UNSPECIFIED;
+};
+
+export const isDeploymentConfigChangeSpec = (spec?: Plan_Spec) => {
+ if (!spec) return false;
+ const deploymentConfig = extractDeploymentConfigName(
+ spec.changeDatabaseConfig?.target ?? ""
+ );
+ return deploymentConfig !== "";
+};
+
+export const isGroupingChangeSpec = (spec?: Plan_Spec) => {
+ if (!spec) return false;
+ const databaseGroup = extractDatabaseGroupName(
+ spec.changeDatabaseConfig?.target ?? ""
+ );
+ return databaseGroup !== "";
+};
diff --git a/frontend/src/components/Plan/logic/poll.ts b/frontend/src/components/Plan/logic/poll.ts
new file mode 100644
index 0000000000..039ff3eef2
--- /dev/null
+++ b/frontend/src/components/Plan/logic/poll.ts
@@ -0,0 +1,45 @@
+import { computed, watch } from "vue";
+import { useProgressivePoll } from "@/composables/useProgressivePoll";
+import { fetchPlanByUID } from "@/store/modules/v1/plan";
+import { extractProjectResourceName } from "@/utils";
+import { usePlanContext } from "./context";
+
+export const usePollPlan = () => {
+ const { isCreating, ready, plan } = usePlanContext();
+
+ const shouldPollPlan = computed(() => {
+ return !isCreating.value && ready.value;
+ });
+
+ const refreshPlan = () => {
+ if (!shouldPollPlan.value) return;
+
+ fetchPlanByUID(
+ plan.value.uid,
+ extractProjectResourceName(plan.value.name)
+ ).then((updatedPlan) => (plan.value = updatedPlan));
+ };
+
+ const poller = useProgressivePoll(refreshPlan, {
+ interval: {
+ min: 500,
+ max: 10000,
+ growth: 2,
+ jitter: 500,
+ },
+ });
+
+ watch(
+ shouldPollPlan,
+ () => {
+ if (shouldPollPlan.value) {
+ poller.start();
+ } else {
+ poller.stop();
+ }
+ },
+ {
+ immediate: true,
+ }
+ );
+};
diff --git a/frontend/src/components/Plan/logic/sheet.ts b/frontend/src/components/Plan/logic/sheet.ts
new file mode 100644
index 0000000000..ad6a875b7b
--- /dev/null
+++ b/frontend/src/components/Plan/logic/sheet.ts
@@ -0,0 +1,21 @@
+import { reactive } from "vue";
+import { Sheet } from "@/types/proto/v1/sheet_service";
+
+const sheetsByName = reactive(new Map<string, Sheet>());
+
+export const createEmptyLocalSheet = () => {
+ return reactive(Sheet.fromJSON({}));
+};
+
+export const getLocalSheetByName = (name: string) => {
+ const existed = sheetsByName.get(name);
+ if (existed) {
+ return existed;
+ }
+ const sheet = reactive({
+ ...createEmptyLocalSheet(),
+ name,
+ });
+ sheetsByName.set(name, sheet);
+ return sheet;
+};
diff --git a/frontend/src/components/Plan/logic/utils.ts b/frontend/src/components/Plan/logic/utils.ts
new file mode 100644
index 0000000000..194cdf6e9f
--- /dev/null
+++ b/frontend/src/components/Plan/logic/utils.ts
@@ -0,0 +1,6 @@
+import type { Plan_Spec } from "@/types/proto/v1/plan_service";
+import type { ComposedPlan } from "@/types/v1/issue/plan";
+
+export const stepForSpec = (plan: ComposedPlan, spec: Plan_Spec) => {
+ return plan.steps.find((step) => step.specs.find((s) => s.id === spec.id));
+};
diff --git a/frontend/src/router/dashboard/projectV1.ts b/frontend/src/router/dashboard/projectV1.ts
index 32ce6fadc7..4fc83d26b2 100644
--- a/frontend/src/router/dashboard/projectV1.ts
+++ b/frontend/src/router/dashboard/projectV1.ts
@@ -18,6 +18,7 @@ export const PROJECT_V1_ROUTE_BRANCH_MERGE = `${PROJECT_V1_ROUTE_DASHBOARD}.bran
export const PROJECT_V1_ROUTE_BRANCH_REBASE = `${PROJECT_V1_ROUTE_DASHBOARD}.branch.rebase`;
export const PROJECT_V1_ROUTE_ISSUES = `${PROJECT_V1_ROUTE_DASHBOARD}.issue`;
export const PROJECT_V1_ROUTE_ISSUE_DETAIL = `${PROJECT_V1_ROUTE_DASHBOARD}.issue.detail`;
+export const PROJECT_V1_ROUTE_PLAN_DETAIL = `${PROJECT_V1_ROUTE_DASHBOARD}.plan.detail`;
export const PROJECT_V1_ROUTE_CHANGE_HISTORIES = `${PROJECT_V1_ROUTE_DASHBOARD}.change-histories`;
export const PROJECT_V1_ROUTE_CHANGELISTS = `${PROJECT_V1_ROUTE_DASHBOARD}.changelist`;
export const PROJECT_V1_ROUTE_CHANGELIST_DETAIL = `${PROJECT_V1_ROUTE_DASHBOARD}.changelist.detail`;
@@ -221,6 +222,16 @@ const projectV1Routes: RouteRecordRaw[] = [
component: () => import("@/views/project/ProjectIssueDetail.vue"),
props: true,
},
+ {
+ path: "plans/:planSlug",
+ name: PROJECT_V1_ROUTE_PLAN_DETAIL,
+ meta: {
+ overrideTitle: true,
+ requiredProjectPermissionList: () => ["bb.projects.get"],
+ },
+ component: () => import("@/views/project/ProjectPlanDetail.vue"),
+ props: true,
+ },
{
path: "changelists",
meta: {
diff --git a/frontend/src/store/modules/uistate.ts b/frontend/src/store/modules/uistate.ts
index 0dd7ba81db..170ff19aea 100644
--- a/frontend/src/store/modules/uistate.ts
+++ b/frontend/src/store/modules/uistate.ts
@@ -6,8 +6,8 @@ const COLLAPSE_MODULE = "ui.list.collapse";
const INTRO_MODULE = "ui.intro";
// default to false
-const issueFormatStatementOnSave = useLocalStorage(
- "ui.state.issue.format-statement-on-save",
+const editorFormatStatementOnSave = useLocalStorage(
+ "ui.state.editor.format-statement-on-save",
false
);
@@ -22,8 +22,8 @@ export const useUIStateStore = defineStore("uistate", {
introStateByKey: new Map(),
}),
getters: {
- issueFormatStatementOnSave: () => {
- return issueFormatStatementOnSave.value;
+ editorFormatStatementOnSave: () => {
+ return editorFormatStatementOnSave.value;
},
},
actions: {
@@ -59,8 +59,8 @@ export const useUIStateStore = defineStore("uistate", {
setIntroStateByKey({ key, newState }: { key: string; newState: boolean }) {
this.introStateByKey.set(key, newState);
},
- setIssueFormatStatementOnSave(value: boolean) {
- issueFormatStatementOnSave.value = value;
+ setEditorFormatStatementOnSave(value: boolean) {
+ editorFormatStatementOnSave.value = value;
},
async restoreState() {
const storedCollapseState = localStorage.getItem(COLLAPSE_MODULE);
diff --git a/frontend/src/store/modules/v1/plan.ts b/frontend/src/store/modules/v1/plan.ts
new file mode 100644
index 0000000000..4c63d3b030
--- /dev/null
+++ b/frontend/src/store/modules/v1/plan.ts
@@ -0,0 +1,52 @@
+import { planServiceClient } from "@/grpcweb";
+import { EMPTY_ID, UNKNOWN_ID } from "@/types";
+import type { Plan } from "@/types/proto/v1/plan_service";
+import {
+ emptyPlan,
+ unknownPlan,
+ type ComposedPlan,
+} from "@/types/v1/issue/plan";
+import { extractProjectResourceName, hasProjectPermissionV2 } from "@/utils";
+import { useCurrentUserV1 } from "../auth";
+import { useProjectV1Store } from "./project";
+
+export const composePlan = async (rawPlan: Plan): Promise<ComposedPlan> => {
+ const me = useCurrentUserV1();
+ const project = `projects/${extractProjectResourceName(rawPlan.name)}`;
+ const projectEntity =
+ await useProjectV1Store().getOrFetchProjectByName(project);
+
+ const plan: ComposedPlan = {
+ ...rawPlan,
+ planCheckRunList: [],
+ project,
+ projectEntity,
+ };
+
+ if (
+ hasProjectPermissionV2(projectEntity, me.value, "bb.planCheckRuns.list")
+ ) {
+ const { planCheckRuns } = await planServiceClient.listPlanCheckRuns({
+ parent: rawPlan.name,
+ });
+ plan.planCheckRunList = planCheckRuns;
+ }
+
+ return plan;
+};
+
+export const fetchPlanByUID = async (uid: string, project = "-") => {
+ if (uid === "undefined") {
+ console.warn("undefined plan uid");
+ return unknownPlan();
+ }
+
+ if (uid === String(EMPTY_ID)) return emptyPlan();
+ if (uid === String(UNKNOWN_ID)) return unknownPlan();
+
+ const rawPlan = await planServiceClient.getPlan({
+ name: `projects/${project}/plans/${uid}`,
+ });
+
+ return composePlan(rawPlan);
+};
diff --git a/frontend/src/types/v1/issue/plan.ts b/frontend/src/types/v1/issue/plan.ts
index c2391812a0..130d97944e 100644
--- a/frontend/src/types/v1/issue/plan.ts
+++ b/frontend/src/types/v1/issue/plan.ts
@@ -1,18 +1,52 @@
import { EMPTY_ID, UNKNOWN_ID } from "@/types/const";
-import { Plan, Plan_Spec } from "@/types/proto/v1/plan_service";
+import {
+ Plan,
+ PlanCheckRun,
+ Plan_Spec,
+ Plan_Step,
+} from "@/types/proto/v1/plan_service";
+import {
+ EMPTY_PROJECT_NAME,
+ UNKNOWN_PROJECT_NAME,
+ emptyProject,
+ unknownProject,
+ type ComposedProject,
+} from "../project";
+
+export interface ComposedPlan extends Plan {
+ planCheckRunList: PlanCheckRun[];
+ project: string;
+ projectEntity: ComposedProject;
+}
export const EMPTY_PLAN_NAME = `projects/${EMPTY_ID}/plans/${EMPTY_ID}`;
export const UNKNOWN_PLAN_NAME = `projects/${UNKNOWN_ID}/plans/${UNKNOWN_ID}`;
export const emptyPlan = () => {
- return Plan.fromJSON({
- name: EMPTY_PLAN_NAME,
- uid: String(EMPTY_ID),
- });
+ return {
+ ...Plan.fromJSON({
+ name: EMPTY_PLAN_NAME,
+ uid: String(EMPTY_ID),
+ }),
+ planCheckRunList: [],
+ project: EMPTY_PROJECT_NAME,
+ projectEntity: emptyProject(),
+ };
};
export const unknownPlan = () => {
- return Plan.fromJSON({
- name: UNKNOWN_PLAN_NAME,
- uid: String(UNKNOWN_ID),
+ return {
+ ...Plan.fromJSON({
+ name: UNKNOWN_PLAN_NAME,
+ uid: String(UNKNOWN_ID),
+ }),
+ planCheckRunList: [],
+ project: UNKNOWN_PROJECT_NAME,
+ projectEntity: unknownProject(),
+ };
+};
+
+export const emptyPlanStep = () => {
+ return Plan_Step.fromJSON({
+ specs: [],
});
};
diff --git a/frontend/src/utils/slug.ts b/frontend/src/utils/slug.ts
index 401e838b5a..63d3116405 100644
--- a/frontend/src/utils/slug.ts
+++ b/frontend/src/utils/slug.ts
@@ -48,6 +48,10 @@ export function issueSlug(issueName: string, issueId: IssueId): string {
return [slug(issueName), issueId].join("-");
}
+export function planSlug(planName: string, planId: IssueId): string {
+ return [slug(planName), planId].join("-");
+}
+
export function stageSlug(stageName: string, stageIndex: number): string {
return [slug(stageName), stageIndex + 1].join("-");
}
diff --git a/frontend/src/views/project/ProjectPlanDetail.vue b/frontend/src/views/project/ProjectPlanDetail.vue
new file mode 100644
index 0000000000..08559be015
--- /dev/null
+++ b/frontend/src/views/project/ProjectPlanDetail.vue
@@ -0,0 +1,88 @@
+<template>
+ <div class="-mx-4 h-full relative overflow-x-hidden">
+ <template v-if="ready">
+ <PlanDetailPage />
+ </template>
+ <div v-else class="w-full h-full flex flex-col items-center justify-center">
+ <NSpin />
+ </div>
+ </div>
+ <FeatureModal
+ :open="state.showFeatureModal"
+ feature="bb.feature.multi-tenancy"
+ @cancel="state.showFeatureModal = false"
+ />
+</template>
+
+<script lang="ts" setup>
+import { useTitle } from "@vueuse/core";
+import { NSpin } from "naive-ui";
+import { computed, reactive, toRef } from "vue";
+import { useI18n } from "vue-i18n";
+import {
+ providePlanContext,
+ useBasePlanContext,
+ useInitializePlan,
+} from "@/components/Plan";
+import PlanDetailPage from "@/components/Plan/PlanDetailPage.vue";
+import { useBodyLayoutContext } from "@/layouts/common";
+import { UNKNOWN_ID } from "@/types";
+
+interface LocalState {
+ showFeatureModal: boolean;
+}
+
+defineOptions({
+ inheritAttrs: false,
+});
+
+const props = defineProps<{
+ projectId: string;
+ planSlug: string;
+}>();
+
+const { t } = useI18n();
+
+const state = reactive<LocalState>({
+ showFeatureModal: false,
+});
+
+const { isCreating, plan, isInitializing, reInitialize } = useInitializePlan(
+ toRef(props, "planSlug"),
+ toRef(props, "projectId")
+);
+const ready = computed(() => {
+ return !isInitializing.value && !!plan.value;
+});
+
+providePlanContext(
+ {
+ isCreating,
+ plan,
+ ready,
+ reInitialize,
+ ...useBasePlanContext({
+ isCreating,
+ ready,
+ plan,
+ }),
+ },
+ true /* root */
+);
+
+const { overrideMainContainerClass } = useBodyLayoutContext();
+
+overrideMainContainerClass("!py-0");
+
+const documentTitle = computed(() => {
+ if (isCreating.value) {
+ return t("issue.new-issue");
+ } else {
+ if (ready.value && plan.value.uid !== String(UNKNOWN_ID)) {
+ return plan.value.title;
+ }
+ }
+ return t("common.loading");
+});
+useTitle(documentTitle);
+</script>