Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(cicd): online migration improvements (#9050)
Liu Jief122bebeeb3
diff --git a/frontend/src/components/AlterSchemaPrepForm/AlterSchemaPrepForm.vue b/frontend/src/components/AlterSchemaPrepForm/AlterSchemaPrepForm.vueindex ce16e0280d..ab66443dbf 100644--- a/frontend/src/components/AlterSchemaPrepForm/AlterSchemaPrepForm.vue+++ b/frontend/src/components/AlterSchemaPrepForm/AlterSchemaPrepForm.vue@@ -363,8 +363,6 @@@cancel="featureModalContext.feature = undefined"/>- <GhostDialog ref="ghostDialog" />-<SchemaEditorModalv-if="state.showSchemaEditorModal":database-id-list="schemaEditorContext.databaseIdList"@@ -411,7 +409,6 @@ import {import { State } from "@/types/proto/v1/common";import { Project, TenantMode } from "@/types/proto/v1/project_service";import {- allowGhostMigrationV1,allowUsingSchemaEditorV1,instanceV1HasAlterSchema,filterDatabaseV1ByKeyword,@@ -427,7 +424,6 @@ import {ProjectSelect,} from "../v2";import DatabaseGroupPrevEditorModal from "./DatabaseGroupPrevEditorModal.vue";-import GhostDialog from "./GhostDialog.vue";import ProjectStandardView, {ProjectStandardViewState,} from "./ProjectStandardView.vue";@@ -476,7 +472,6 @@ const featureModalContext = ref<{feature?: FeatureType;}>({});-const ghostDialog = ref<InstanceType<typeof GhostDialog>>();const schemaEditorContext = ref<{databaseIdList: string[];}>({@@ -658,38 +653,6 @@ const allowGenerateMultiDb = computed(() => {}});-// 'normal' -> normal migration-// 'online' -> online migration-// false -> user clicked cancel button-const isUsingGhostMigration = async (databaseList: ComposedDatabase[]) => {- // Gh-ost is not available for tenant mode yet.- if (- databaseList.some(- (db) => db.projectEntity.tenantMode === TenantMode.TENANT_MODE_ENABLED- )- ) {- return "normal";- }-- // never available for "bb.issue.database.data.update"- if (props.type === "bb.issue.database.data.update") {- return "normal";- }-- // check if all selected databases supports gh-ost- if (allowGhostMigrationV1(databaseList)) {- // open the dialog to ask the user- const { result, mode } = await ghostDialog.value!.open();- if (!result) {- return false; // return false when user clicked the cancel button- }- return mode;- }-- // fallback to normal- return "normal";-};-// Also works when single db selected.const generateMultiDb = async () => {if (@@ -715,11 +678,6 @@ const generateMultiDb = async () => {return;}- const mode = await isUsingGhostMigration(selectedDatabaseList);- if (mode === false) {- return;- }-if (flattenSelectedProjectSet.value.size !== 1) {return;}@@ -728,17 +686,13 @@ const generateMultiDb = async () => {template: props.type,name: generateIssueName(props.type,- selectedDatabaseList.map((db) => db.databaseName),- mode === "online"+ selectedDatabaseList.map((db) => db.databaseName)),project: [...flattenSelectedProjectSet.value][0],// The server-side will sort the databases by environment.// So we need not to sort them here.databaseList: flattenSelectedDatabaseUidList.value.join(","),};- if (mode === "online") {- query.ghost = "1";- }router.push({name: "workspace.issue.detail",params: {@@ -924,25 +878,14 @@ const selectDatabase = async (database: ComposedDatabase) => {return;}- const mode = await isUsingGhostMigration([database]);- if (mode === false) {- return;- }emit("dismiss");const query: Record<string, any> = {template: props.type,- name: generateIssueName(- props.type,- [database.databaseName],- mode === "online"- ),+ name: generateIssueName(props.type, [database.databaseName]),project: database.projectEntity.uid,databaseList: database.uid,};- if (mode === "online") {- query.ghost = "1";- }router.push({name: "workspace.issue.detail",params: {diff --git a/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vue b/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vueindex 9f30558c95..c9fb91e6d4 100644--- a/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vue+++ b/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vue@@ -121,9 +121,6 @@</div></BBModal>- <!-- Select DDL mode for MySQL -->- <GhostDialog ref="ghostDialog" />-<!-- Close modal confirm dialog --><ActionConfirmModalv-if="state.showActionConfirmModal"@@ -137,7 +134,7 @@<script lang="ts" setup>import dayjs from "dayjs";import { cloneDeep, head, isEqual, uniq } from "lodash-es";-import { computed, onMounted, PropType, reactive, ref } from "vue";+import { computed, onMounted, PropType, reactive } from "vue";import { useI18n } from "vue-i18n";import { useRouter } from "vue-router";import ActionConfirmModal from "@/components/SchemaEditorV1/Modals/ActionConfirmModal.vue";@@ -151,7 +148,6 @@ import {useSchemaEditorV1Store,} from "@/store";import {- ComposedDatabase,dialectOfEngineV1,UNKNOWN_PROJECT_NAME,unknownProject,@@ -159,7 +155,6 @@ import {import { Engine } from "@/types/proto/v1/common";import { DatabaseMetadata } from "@/types/proto/v1/database_service";import { TenantMode } from "@/types/proto/v1/project_service";-import { allowGhostMigrationV1 } from "@/utils";import MonacoEditor from "../MonacoEditor";import { provideSQLCheckContext } from "../SQLCheck";import {@@ -167,7 +162,6 @@ import {mergeSchemaEditToMetadata,validateDatabaseMetadata,} from "../SchemaEditorV1/utils";-import GhostDialog from "./GhostDialog.vue";import SchemaEditorSQLCheckButton from "./SchemaEditorSQLCheckButton/SchemaEditorSQLCheckButton.vue";const MAX_UPLOAD_FILE_SIZE_MB = 1;@@ -210,7 +204,6 @@ const schemaEditorV1Store = useSchemaEditorV1Store();const databaseV1Store = useDatabaseV1Store();const dbSchemaV1Store = useDBSchemaV1Store();const notificationStore = useNotificationStore();-const ghostDialog = ref<InstanceType<typeof GhostDialog>>();const { runSQLCheck } = provideSQLCheckContext();const allowPreviewIssue = computed(() => {@@ -283,24 +276,6 @@ const dismissModal = () => {}};-// 'normal' -> normal migration-// 'online' -> online migration-// false -> user clicked cancel button-const isUsingGhostMigration = async (databaseList: ComposedDatabase[]) => {- // check if all selected databases supports gh-ost- if (allowGhostMigrationV1(databaseList)) {- // open the dialog to ask the user- const { result, mode } = await ghostDialog.value!.open();- if (!result) {- return false; // return false when user clicked the cancel button- }- return mode;- }-- // fallback to normal- return "normal";-};-const handleSyncSQLFromSchemaEditor = async () => {const statementMap = await fetchStatementMapWithSchemaEditor();if (!statementMap) {@@ -460,32 +435,14 @@ const handlePreviewIssue = async () => {if (state.selectedTab === "raw-sql") {query.sql = state.editStatement;- // We should show select ghost mode dialog only for altering table statement not create/drop table.- // TODO(steven): parse the sql check if there only alter table statement.- const actionResult = await isUsingGhostMigration(databaseList.value);- if (actionResult === false) {- return;- }- if (actionResult === "online") {- query.ghost = 1;- }query.name = generateIssueName(databaseList.value.map((db) => db.databaseName),- !!query.ghost+ false /* !onlineMode */);} else {- // We should show select ghost mode dialog only for altering table statement not create/drop table.- // TODO(steven): parse the sql check if there only alter table statement.- const actionResult = await isUsingGhostMigration(databaseList.value);- if (actionResult === false) {- return;- }- if (actionResult === "online") {- query.ghost = 1;- }query.name = generateIssueName(databaseList.value.map((db) => db.databaseName),- !!query.ghost+ false /* !onlineMode */);const statementMap = await fetchStatementMapWithSchemaEditor();diff --git a/frontend/src/components/AlterSchemaPrepForm/index.ts b/frontend/src/components/AlterSchemaPrepForm/index.tsindex 596a620ea8..c7794601d7 100644--- a/frontend/src/components/AlterSchemaPrepForm/index.ts+++ b/frontend/src/components/AlterSchemaPrepForm/index.ts@@ -1,6 +1,3 @@import AlterSchemaPrepForm from "./AlterSchemaPrepForm.vue";-import GhostDialog from "./GhostDialog.vue";export default AlterSchemaPrepForm;--export { GhostDialog };diff --git a/frontend/src/components/InstanceForm/DataSourceSection/DataSourceForm.vue b/frontend/src/components/InstanceForm/DataSourceSection/DataSourceForm.vueindex f5f29574d9..5a96f9ca13 100644--- a/frontend/src/components/InstanceForm/DataSourceSection/DataSourceForm.vue+++ b/frontend/src/components/InstanceForm/DataSourceSection/DataSourceForm.vue@@ -216,13 +216,13 @@ import { NButton, NCheckbox, NInput } from "naive-ui";import { DataSourceOptions } from "@/types";import { Engine } from "@/types/proto/v1/common";import { DataSource, DataSourceType } from "@/types/proto/v1/instance_service";+import { onlyAllowNumber } from "@/utils";import { EditDataSource } from "../common";import { useInstanceFormContext } from "../context";import { useInstanceSpecs } from "../specs";import SpannerCredentialInput from "./SpannerCredentialInput.vue";import SshConnectionForm from "./SshConnectionForm.vue";import SslCertificateForm from "./SslCertificateForm.vue";-import { onlyAllowNumber } from "./common";const props = defineProps<{dataSource: EditDataSource;diff --git a/frontend/src/components/InstanceForm/DataSourceSection/SshConnectionForm.vue b/frontend/src/components/InstanceForm/DataSourceSection/SshConnectionForm.vueindex 928e356bd3..a5a1e6f770 100644--- a/frontend/src/components/InstanceForm/DataSourceSection/SshConnectionForm.vue+++ b/frontend/src/components/InstanceForm/DataSourceSection/SshConnectionForm.vue@@ -96,7 +96,7 @@ import { useI18n } from "vue-i18n";import DroppableTextarea from "@/components/misc/DroppableTextarea.vue";import { useSubscriptionV1Store } from "@/store";import { Instance } from "@/types/proto/v1/instance_service";-import { onlyAllowNumber } from "./common";+import { onlyAllowNumber } from "@/utils";const SshTypes = ["NONE", "TUNNEL", "TUNNEL+PK"] as const;diff --git a/frontend/src/components/InstanceForm/DataSourceSection/common.ts b/frontend/src/components/InstanceForm/DataSourceSection/common.tsdeleted file mode 100644index 2c38558612..0000000000--- a/frontend/src/components/InstanceForm/DataSourceSection/common.ts+++ /dev/null@@ -1,3 +0,0 @@-export const onlyAllowNumber = (value: string) => {- return value === "" || /^\d+$/.test(value);-};diff --git a/frontend/src/components/InstanceForm/InstanceForm.vue b/frontend/src/components/InstanceForm/InstanceForm.vueindex dda37a9951..d81591c624 100644--- a/frontend/src/components/InstanceForm/InstanceForm.vue+++ b/frontend/src/components/InstanceForm/InstanceForm.vue@@ -395,15 +395,18 @@ import {extractInstanceResourceName,instanceV1Slug,calcUpdateMask,+ onlyAllowNumber,} from "@/utils";import { extractGrpcErrorMessage, getErrorCode } from "@/utils/grpcweb";import DataSourceSection from "./DataSourceSection/DataSourceSection.vue";-import { onlyAllowNumber } from "./DataSourceSection/common";import OracleSyncModeInput from "./OracleSyncModeInput.vue";import ScanIntervalInput from "./ScanIntervalInput.vue";import SpannerHostInput from "./SpannerHostInput.vue";-import { EditDataSource, extractDataSourceEditState } from "./common";-import { extractBasicInfo } from "./common";+import {+ EditDataSource,+ extractBasicInfo,+ extractDataSourceEditState,+} from "./common";import {MongoDBConnectionStringSchemaList,SnowflakeExtraLinkPlaceHolder,diff --git a/frontend/src/components/IssueV1/components/IssueTableV1.vue b/frontend/src/components/IssueV1/components/IssueTableV1.vueindex f3bc491626..6cbc330865 100644--- a/frontend/src/components/IssueV1/components/IssueTableV1.vue+++ b/frontend/src/components/IssueV1/components/IssueTableV1.vue@@ -95,7 +95,9 @@</div></div><div v-if="showExtendedColumns" class="bb-grid-cell">- {{ humanizeTs((issue.updateTime?.getTime() ?? 0) / 1000) }}+ <EllipsisText>+ {{ humanizeTs((issue.updateTime?.getTime() ?? 0) / 1000) }}+ </EllipsisText></div><div v-if="showExtendedColumns" class="bb-grid-cell !py-0.5"><CurrentApproverV1 :issue="issue" />@@ -153,6 +155,7 @@ import { reactive, computed, watch, ref } from "vue";import { useI18n } from "vue-i18n";import { useRouter } from "vue-router";import { BBGridColumn } from "@/bbkit";+import EllipsisText from "@/components/EllipsisText.vue";import BatchIssueActionsV1 from "@/components/IssueV1/components/BatchIssueActionsV1.vue";import CurrentApproverV1 from "@/components/IssueV1/components/CurrentApproverV1.vue";import IssueStatusIcon from "@/components/IssueV1/components/IssueStatusIcon.vue";@@ -188,7 +191,7 @@ const columnList = computed((): BBGridColumn[] => {columns.push({title: t("issue.table.updated"),- width: "minmax(auto, 5rem)",+ width: "minmax(auto, 7rem)",},{title: t("issue.table.approver"),diff --git a/frontend/src/components/IssueV1/components/StageSection/Actions/Actions.vue b/frontend/src/components/IssueV1/components/StageSection/Actions/Actions.vueindex 9443f0cd1e..d8db2bcb3e 100644--- a/frontend/src/components/IssueV1/components/StageSection/Actions/Actions.vue+++ b/frontend/src/components/IssueV1/components/StageSection/Actions/Actions.vue@@ -3,10 +3,13 @@<EarliestAllowedTime /><RollbackSection />++ <GhostSection /></div></template><script setup lang="ts">import EarliestAllowedTime from "./EarliestAllowedTime.vue";+import GhostSection from "./GhostSection";import RollbackSection from "./RollbackSection";</script>diff --git a/frontend/src/components/IssueV1/components/StageSection/Actions/GhostSection/FlagsForm/DefaultParams.vue b/frontend/src/components/IssueV1/components/StageSection/Actions/GhostSection/FlagsForm/DefaultParams.vuenew file mode 100644index 0000000000..4ebb49f0ed--- /dev/null+++ b/frontend/src/components/IssueV1/components/StageSection/Actions/GhostSection/FlagsForm/DefaultParams.vue@@ -0,0 +1,43 @@+<template>+ <div class="flex items-center">+ <NButton size="small" @click="expanded = !expanded">+ <template v-if="expanded">+ {{ $t("task.online-migration.hide-default-parameters") }}+ </template>+ <template v-else>+ {{ $t("task.online-migration.show-default-parameters") }}+ </template>+ </NButton>+ </div>+ <div+ v-if="expanded"+ class="grid gap-y-4 gap-x-4 items-center text-sm"+ style="grid-template-columns: auto 1fr"+ >+ <div+ v-for="param in DefaultGhostParameters"+ :key="param.key"+ class="contents"+ >+ <div class="font-medium text-control">{{ param.key }}</div>+ <div class="textinfolabel break-all">+ <NCheckbox+ v-if="param.type === 'bool'"+ :checked="param.value === 'true'"+ :disabled="true"+ />+ <span v-else>+ {{ param.value }}+ </span>+ </div>+ </div>+ </div>+</template>++<script lang="ts" setup>+import { NCheckbox } from "naive-ui";+import { ref } from "vue";+import { DefaultGhostParameters } from "./constants";++const expanded = ref(false);+</script>diff --git a/frontend/src/components/IssueV1/components/StageSection/Actions/GhostSection/FlagsForm/FlagsForm.vue b/frontend/src/components/IssueV1/components/StageSection/Actions/GhostSection/FlagsForm/FlagsForm.vuenew file mode 100644index 0000000000..875c313258--- /dev/null+++ b/frontend/src/components/IssueV1/components/StageSection/Actions/GhostSection/FlagsForm/FlagsForm.vue@@ -0,0 +1,93 @@+<template>+ <div+ class="grid gap-y-4 gap-x-4 items-center text-sm"+ style="grid-template-columns: auto 1fr"+ >+ <div+ v-for="param in SupportedGhostParameters"+ :key="param.key"+ class="contents"+ >+ <div class="font-medium text-control">{{ param.key }}</div>+ <div class="textinfolabel break-all">+ <NInput+ v-if="param.type === 'int'"+ size="small"+ :value="getIntValue(param.key)"+ :allow-input="onlyAllowNumber"+ :disabled="readonly"+ @update:value="setIntValue(param.key, parseInt($event, 10))"+ />+ <NCheckbox+ v-if="param.type === 'bool'"+ :checked="getBoolValue(param.key)"+ :disabled="readonly"+ @update:checked="setBoolValue(param.key, $event)"+ />+ <NInput+ v-if="param.type === 'string'"+ size="small"+ :value="getStringValue(param.key)"+ :disabled="readonly"+ @update:value="setStringValue(param.key, $event)"+ />+ </div>+ </div>+ </div>+</template>++<script lang="ts" setup>+import { NCheckbox, NInput } from "naive-ui";+import { onlyAllowNumber } from "@/utils";+import { SupportedGhostParameters } from "./constants";++const props = defineProps<{+ flags: Record<string, string>;+ readonly: boolean;+}>();+const emit = defineEmits<{+ (event: "update:flags", flags: Record<string, string>): void;+}>();++const getBoolValue = (key: string) => {+ return props.flags[key] === "true";+};+const getStringValue = (key: string) => {+ return props.flags[key] ?? "";+};+const getIntValue = (key: string) => {+ const intVal = parseInt(props.flags[key], 10);+ if (Number.isNaN(intVal)) return undefined;+ return String(intVal);+};++const setBoolValue = (key: string, value: boolean) => {+ const updated = { ...props.flags };+ if (value) {+ updated[key] = "true";+ } else {+ delete updated[key];+ }+ emit("update:flags", updated);+};+const setStringValue = (key: string, value: string) => {+ const updated = { ...props.flags };+ value = value.trim();+ if (value) {+ updated[key] = value;+ } else {+ delete updated[key];+ }+ emit("update:flags", updated);+};+const setIntValue = (key: string, value: number) => {+ const updated = { ...props.flags };++ if (!Number.isNaN(value)) {+ updated[key] = value.toString();+ } else {+ delete updated[key];+ }+ emit("update:flags", updated);+};+</script>diff --git a/frontend/src/components/IssueV1/components/StageSection/Actions/GhostSection/FlagsForm/constants.ts b/frontend/src/components/IssueV1/components/StageSection/Actions/GhostSection/FlagsForm/constants.tsnew file mode 100644index 0000000000..e8c2f3f273--- /dev/null+++ b/frontend/src/components/IssueV1/components/StageSection/Actions/GhostSection/FlagsForm/constants.ts@@ -0,0 +1,106 @@+export type GhostParameterType = "bool" | "int" | "float" | "string";++export type GhostParameter<T extends GhostParameterType = any> = {+ key: string;+ type: T;+};++export type GhostParameterWithValue<T extends GhostParameterType = any> =+ GhostParameter<T> & {+ value: string;+ };++export const SupportedGhostParameters: GhostParameter[] = [+ { key: "max-load", type: "string" },+ { key: "chunk-size", type: "int" },+ { key: "initially-drop-ghost-table", type: "bool" },+ { key: "max-lag-millis", type: "int" },+ { key: "allow-on-master", type: "bool" },+ { key: "switch-to-rbr", type: "bool" },+];++export const DefaultGhostParameters: GhostParameterWithValue[] = [+ {+ key: "allow-on-master",+ type: "bool",+ value: "true",+ },+ {+ key: "concurrent-rowcount",+ type: "bool",+ value: "true",+ },+ {+ key: "hooks-status-interval",+ type: "int",+ value: "60",+ },+ {+ key: "heartbeat-interval-millis",+ type: "int",+ value: "100",+ },+ {+ key: "nice-ratio",+ type: "float",+ value: "0",+ },+ {+ key: "chunk-size",+ type: "int",+ value: "1000",+ },+ {+ key: "dml-batch-size",+ type: "int",+ value: "10",+ },+ {+ key: "max-lag-millis",+ type: "int",+ value: "1500",+ },+ {+ key: "default-retries",+ type: "int",+ value: "60",+ },+ {+ key: "cut-over-lock-timeout-seconds",+ type: "int",+ value: "60",+ },+ {+ key: "exponential-backoff-max-interval",+ type: "int",+ value: "64",+ },+ {+ key: "throttle-http-interval-millis",+ type: "int",+ value: "100",+ },+ {+ key: "throttle-http-timeout-millis",+ type: "int",+ value: "1000",+ },+];++export const isBoolParameter = (+ param: GhostParameter+): param is GhostParameter<"bool"> => {+ return param.type === "bool";+};++export const isIntParameter = (+ param: GhostParameter+): param is GhostParameter<"int"> => {+ return param.type === "int";+};++export const isStringParameter = (+ param: GhostParameter+): param is GhostParameter<"string"> => {+ return param.type === "string";+};diff --git a/frontend/src/components/IssueV1/components/StageSection/Actions/GhostSection/FlagsForm/index.ts b/frontend/src/components/IssueV1/components/StageSection/Actions/GhostSection/FlagsForm/index.tsnew file mode 100644index 0000000000..9d6f915b7b--- /dev/null+++ b/frontend/src/components/IssueV1/components/StageSection/Actions/GhostSection/FlagsForm/index.ts@@ -0,0 +1,5 @@+import DefaultParams from "./DefaultParams.vue";+import FlagsForm from "./FlagsForm.vue";++export default FlagsForm;+export { FlagsForm, DefaultParams };diff --git a/frontend/src/components/IssueV1/components/StageSection/Actions/GhostSection/GhostConfigButton.vue b/frontend/src/components/IssueV1/components/StageSection/Actions/GhostSection/GhostConfigButton.vuenew file mode 100644index 0000000000..0a2bf0e0db--- /dev/null+++ b/frontend/src/components/IssueV1/components/StageSection/Actions/GhostSection/GhostConfigButton.vue@@ -0,0 +1,24 @@+<template>+ <NButton+ tag="div"+ quaternary+ size="small"+ style="--n-padding: 0 5px"+ @click="showFlagsPanel = true"+ >+ <template #icon>+ <Wrench class="w-4 h-4" />+ </template>+ <template #default>+ {{ $t("task.online-migration.configure") }}+ </template>+ </NButton>+</template>++<script setup lang="ts">+import { Wrench } from "lucide-vue-next";+import { NButton } from "naive-ui";+import { useIssueGhostContext } from "./common";++const { showFlagsPanel } = useIssueGhostContext();+</script>diff --git a/frontend/src/components/IssueV1/components/StageSection/Actions/GhostSection/GhostFlagsPanel.vue b/frontend/src/components/IssueV1/components/StageSection/Actions/GhostSection/GhostFlagsPanel.vuenew file mode 100644index 0000000000..5cfeb7ced0--- /dev/null+++ b/frontend/src/components/IssueV1/components/StageSection/Actions/GhostSection/GhostFlagsPanel.vue@@ -0,0 +1,231 @@+<template>+ <Drawer v-model:show="showFlagsPanel">+ <DrawerContent+ :title="title"+ class="w-[100vw] md:max-w-[calc(100vw-8rem)] md:w-[40vw]"+ >+ <template #default>+ <div class="flex flex-col gap-y-4">+ <div+ class="grid gap-y-4 gap-x-4 items-center text-sm"+ style="grid-template-columns: auto 1fr"+ >+ <div v-if="stage" class="contents">+ <label class="font-medium text-control">+ {{ $t("common.stage") }}+ </label>+ <div class="textinfolabel break-all">+ {{ stage.title }}+ </div>+ </div>+ <div class="contents">+ <label class="font-medium text-control">+ {{ $t("common.task") }}+ </label>+ <div class="textinfolabel break-all">+ {{ task.title }}+ </div>+ </div>+ <div class="contents">+ <label class="font-medium text-control">+ {{ $t("common.database") }}+ </label>+ <div class="textinfolabel break-all">+ <RichDatabaseName :database="database" />+ </div>+ </div>+ </div>++ <p class="font-medium text-control">+ {{ $t("task.online-migration.ghost-parameters") }}+ </p>+ <FlagsForm v-model:flags="flags" :readonly="readonly" />+ <DefaultParams />+ </div>+ </template>+ <template #footer>+ <div class="flex flex-row justify-end gap-x-3">+ <NButton @click="close">{{ $t("common.cancel") }}</NButton>++ <NTooltip :disabled="errors.length === 0">+ <template #trigger>+ <NButton+ type="primary"+ :disabled="!isDirty"+ :loading="isUpdating"+ @click="trySave"+ >+ {{ $t("common.save") }}+ </NButton>+ </template>+ <template #default>+ <ErrorList :errors="errors" />+ </template>+ </NTooltip>+ </div>+ </template>+ </DrawerContent>+ </Drawer>+</template>++<script setup lang="ts">+import { cloneDeep, isEqual, uniqBy } from "lodash-es";+import { NButton, NTooltip } from "naive-ui";+import { computed, ref, watch } from "vue";+import { useI18n } from "vue-i18n";+import {+ chooseUpdateTarget,+ databaseForTask,+ notifyNotEditableLegacyIssue,+ specForTask,+ stageForTask,+ useIssueContext,+} from "@/components/IssueV1/logic";+import ErrorList from "@/components/misc/ErrorList.vue";+import { Drawer, DrawerContent, RichDatabaseName } from "@/components/v2";+import { rolloutServiceClient } from "@/grpcweb";+import { pushNotification } from "@/store";+import { Plan_Spec, Task_Type } from "@/types/proto/v1/rollout_service";+import { FlagsForm, DefaultParams } from "./FlagsForm";+import { allowChangeTaskGhostFlags, useIssueGhostContext } from "./common";++const { t } = useI18n();+const { showFlagsPanel, denyEditGhostFlagsReasons } = useIssueGhostContext();+const {+ isCreating,+ issue,+ selectedTask: task,+ dialog,+ events,+} = useIssueContext();+const isUpdating = ref(false);++const stage = computed(() => {+ return stageForTask(issue.value, task.value);+});+const database = computed(() => {+ return databaseForTask(issue.value, task.value);+});+const title = computed(() => {+ return t("task.online-migration.configure-ghost-parameters");+});+const spec = computed(() => {+ return specForTask(issue.value.planEntity, task.value);+});+const config = computed(() => {+ return spec.value?.changeDatabaseConfig;+});+const flags = ref<Record<string, string>>({});++const isDirty = computed(() => {+ return !isEqual(config.value?.ghostFlags ?? {}, flags.value);+});+const errors = computed(() => {+ if (denyEditGhostFlagsReasons.value.length > 0) {+ return denyEditGhostFlagsReasons.value;+ }+ const errors: string[] = [];+ if (!isDirty.value) {+ errors.push(t("task.online-migration.error.nothing-changed"));+ }+ return errors;+});++const readonly = computed(() => {+ if (isCreating.value) return false;+ return denyEditGhostFlagsReasons.value.length > 0;+});++const isDeploymentConfig = computed(() => {+ return !!spec.value?.changeDatabaseConfig?.target?.match(+ /\/deploymentConfigs\/[^/]+/+ );+});++const chooseUpdateSpecs = async () => {+ const { tasks } = await chooseUpdateTarget(+ issue.value,+ task.value,+ (task) =>+ task.type === Task_Type.DATABASE_SCHEMA_UPDATE_GHOST_SYNC &&+ allowChangeTaskGhostFlags(issue.value, task),+ dialog,+ t("task.online-migration.ghost-parameters"),+ isDeploymentConfig.value+ );++ const specs = tasks+ .map((task) => specForTask(issue.value.planEntity, task))+ .filter((spec) => !!spec) as Plan_Spec[];++ return uniqBy(specs, (spec) => spec.id);+};++const close = () => {+ flags.value = cloneDeep(config.value?.ghostFlags ?? {});+ showFlagsPanel.value = false;+};++const trySave = async () => {+ const specs = await chooseUpdateSpecs();+ if (specs.length === 0) return;++ if (isCreating.value) {+ specs.forEach((spec) => {+ const config = spec.changeDatabaseConfig;+ if (!config) return;+ config.ghostFlags = cloneDeep(flags.value);+ });+ close();+ } else {+ isUpdating.value = true;+ try {+ const planPatch = cloneDeep(issue.value.planEntity);+ if (!planPatch) {+ notifyNotEditableLegacyIssue();+ return;+ }++ const distinctSpecIds = new Set(specs.map((spec) => spec.id));+ const specsToPatch = planPatch.steps+ .flatMap((step) => step.specs)+ .filter((spec) => distinctSpecIds.has(spec.id));++ for (let i = 0; i < specsToPatch.length; i++) {+ const spec = specsToPatch[i];+ const config = spec.changeDatabaseConfig;+ if (!config) continue;+ config.ghostFlags = cloneDeep(flags.value);+ }++ const updatedPlan = await rolloutServiceClient.updatePlan({+ plan: planPatch,+ updateMask: ["steps"],+ });++ issue.value.planEntity = updatedPlan;++ events.emit("status-changed", { eager: true });+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("common.updated"),+ });+ close();+ } finally {+ isUpdating.value = false;+ }+ }+};++watch(+ () => config.value?.ghostFlags,+ (newFlags, oldFlags) => {+ if (isEqual(newFlags, oldFlags)) {+ return;+ }+ flags.value = cloneDeep(newFlags ?? {});+ },+ { immediate: true, deep: true }+);+</script>diff --git a/frontend/src/components/IssueV1/components/StageSection/Actions/GhostSection/GhostSection.vue b/frontend/src/components/IssueV1/components/StageSection/Actions/GhostSection/GhostSection.vuenew file mode 100644index 0000000000..6333771193--- /dev/null+++ b/frontend/src/components/IssueV1/components/StageSection/Actions/GhostSection/GhostSection.vue@@ -0,0 +1,68 @@+<template>+ <div+ v-if="shouldShowGhostSection"+ class="flex items-center gap-x-3 min-h-[34px]"+ >+ <NTooltip>+ <template #trigger>+ <div class="textlabel flex items-center">+ {{ $t("task.online-migration.self") }}+ </div>+ </template>+ <template #default>+ <i18n-t+ tag="p"+ keypath="issue.migration-mode.online.description"+ class="whitespace-pre-line max-w-[20rem]"+ >+ <template #link>+ <LearnMoreLink+ url="https://www.bytebase.com/docs/change-database/online-schema-migration-for-mysql"+ color="light"+ />+ </template>+ </i18n-t>+ </template>+ </NTooltip>+ <div class="w-[12rem] flex items-center gap-x-2">+ <GhostSwitch v-if="isCreating" />+ <GhostConfigButton v-if="viewType === 'ON'" />+ </div>++ <GhostFlagsPanel />+ </div>+</template>++<script lang="ts" setup>+import { computed } from "vue";+import { useIssueContext } from "@/components/IssueV1/logic";+import { flattenTaskV1List } from "@/utils";+import GhostConfigButton from "./GhostConfigButton.vue";+import GhostFlagsPanel from "./GhostFlagsPanel.vue";+import GhostSwitch from "./GhostSwitch.vue";+import {+ allowGhostForTask,+ ghostViewTypeForTask,+ provideIssueGhostContext,+} from "./common";++const { isCreating, issue } = useIssueContext();++const { viewType } = provideIssueGhostContext();++const shouldShowGhostSection = computed(() => {+ // We need all tasks and specs to be gh-ost-able to enable gh-ost mode.+ const tasks = flattenTaskV1List(issue.value.rolloutEntity);+ if (isCreating.value) {+ // When an issue is pending create, we should show the gh-ost section+ // whenever gh-ost is on or off.+ return tasks.every(+ (task) =>+ allowGhostForTask(issue.value, task) &&+ ghostViewTypeForTask(issue.value, task) !== "NONE"+ );+ } else {+ return viewType.value === "ON";+ }+});+</script>diff --git a/frontend/src/components/IssueV1/components/StageSection/Actions/GhostSection/GhostSwitch.vue b/frontend/src/components/IssueV1/components/StageSection/Actions/GhostSection/GhostSwitch.vuenew file mode 100644index 0000000000..4b7e7eab98--- /dev/null+++ b/frontend/src/components/IssueV1/components/StageSection/Actions/GhostSection/GhostSwitch.vue@@ -0,0 +1,64 @@+<template>+ <NSwitch+ :value="checked"+ :disabled="!allowChange"+ :loading="isUpdating"+ class="bb-ghost-switch"+ @update:value="toggleChecked"+ >+ <template #checked>+ <span style="font-size: 10px">{{ $t("common.on") }}</span>+ </template>+ <template #unchecked>+ <span style="font-size: 10px">{{ $t("common.off") }}</span>+ </template>+ </NSwitch>+</template>++<script setup lang="ts">+import { NSwitch } from "naive-ui";+import { computed, ref } from "vue";+import { specForTask, useIssueContext } from "@/components/IssueV1/logic";+import { provideIssueGhostContext } from "./common";++const { isCreating, issue, selectedTask: task } = useIssueContext();+const { viewType, toggleGhost } = provideIssueGhostContext();+const isUpdating = ref(false);++const allowChange = computed(() => {+ return isCreating.value;+});++const checked = computed(() => {+ return viewType.value === "ON";+});++const toggleChecked = async (on: boolean) => {+ const spec = specForTask(issue.value.planEntity, task.value);+ if (!spec) return;+ isUpdating.value = true;+ try {+ await toggleGhost(spec, on);+ } finally {+ isUpdating.value = false;+ }+};+</script>++<style lang="postcss" scoped>+.bb-ghost-switch {+ --n-width: max(+ var(--n-rail-width),+ calc(var(--n-rail-width) + var(--n-button-width) - var(--n-rail-height))+ ) !important;+}+.bb-ghost-switch :deep(.n-switch__checked) {+ padding-right: calc(var(--n-rail-height) - var(--n-offset) + 1px);+}+.bb-ghost-switch :deep(.n-switch__unchecked) {+ padding-left: calc(var(--n-rail-height) - var(--n-offset) + 1px);+}+.bb-ghost-switch :deep(.n-switch__button-placeholder) {+ width: calc(1.25 * var(--n-rail-height));+}+</style>diff --git a/frontend/src/components/IssueV1/components/StageSection/Actions/GhostSection/common.ts b/frontend/src/components/IssueV1/components/StageSection/Actions/GhostSection/common.tsnew file mode 100644index 0000000000..1ea583a37e--- /dev/null+++ b/frontend/src/components/IssueV1/components/StageSection/Actions/GhostSection/common.ts@@ -0,0 +1,214 @@+import { InjectionKey, Ref, computed, inject, provide, ref } from "vue";+import { useI18n } from "vue-i18n";+import {+ databaseForTask,+ getLocalSheetByName,+ isGroupingChangeTaskV1,+ sheetNameForSpec,+ specForTask,+ useIssueContext,+} from "@/components/IssueV1/logic";+import { useCurrentUserV1 } from "@/store";+import { ComposedDatabase, ComposedIssue } from "@/types";+import { Engine } from "@/types/proto/v1/common";+import { IssueStatus } from "@/types/proto/v1/issue_service";+import {+ Plan_ChangeDatabaseConfig_Type,+ Plan_Spec,+ Task,+ Task_Status,+ Task_Type,+ task_StatusToJSON,+} from "@/types/proto/v1/rollout_service";+import {+ MIN_GHOST_SUPPORT_MYSQL_VERSION,+ extractUserResourceName,+ flattenTaskV1List,+ getSheetStatement,+ hasWorkspacePermissionV1,+ semverCompare,+} from "@/utils";++export type GhostUIViewType = "NONE" | "OFF" | "ON";++export type IssueGhostContext = {+ viewType: Ref<GhostUIViewType>;+ showFlagsPanel: Ref<boolean>;+ denyEditGhostFlagsReasons: Ref<string[]>;+ toggleGhost: (spec: Plan_Spec, on: boolean) => Promise<void>;+};++export const KEY = Symbol(+ "bb.issue.context.ghost"+) as InjectionKey<IssueGhostContext>;++export const useIssueGhostContext = () => {+ return inject(KEY)!;+};++export const provideIssueGhostContext = () => {+ const { t } = useI18n();+ const me = useCurrentUserV1();+ const {+ isCreating,+ issue,+ selectedTask: task,+ reInitialize,+ } = useIssueContext();++ const viewType = computed((): GhostUIViewType => {+ return ghostViewTypeForTask(issue.value, task.value);+ });+ const showFlagsPanel = ref(false);+ const isDeploymentConfig = computed(() => {+ const spec = specForTask(issue.value.planEntity, task.value);+ return !!spec?.changeDatabaseConfig?.target?.match(+ /\/deploymentConfigs\/[^/]+/+ );+ });++ const denyEditGhostFlagsReasons = computed(() => {+ if (isCreating.value) {+ return [];+ }++ if (issue.value.status !== IssueStatus.OPEN) {+ return [t("issue.error.issue-is-not-open")];+ }++ const errors: string[] = [];++ if (extractUserResourceName(issue.value.creator) !== me.value.email) {+ if (+ !hasWorkspacePermissionV1(+ "bb.permission.workspace.manage-issue",+ me.value.userRole+ )+ ) {+ return [t("issue.error.you-don-have-privilege-to-edit-this-issue")];+ }+ }++ if (isDeploymentConfig.value) {+ // If a task is created by deploymentConfig. It is editable only when all+ // its "brothers" (created by the same deploymentConfig) are editable.+ // By which "editable" means a task's status meets the requirements.+ const ghostSyncTasks = flattenTaskV1List(+ issue.value.rolloutEntity+ ).filter(+ (task) => task.type === Task_Type.DATABASE_SCHEMA_UPDATE_GHOST_SYNC+ );+ if (+ ghostSyncTasks.some(+ (task) => !allowChangeTaskGhostFlags(issue.value, task)+ )+ ) {+ errors.push(+ t(+ "task.online-migration.error.some-tasks-are-not-editable-in-batch-mode"+ )+ );+ }+ } else {+ if (!allowChangeTaskGhostFlags(issue.value, task.value)) {+ errors.push(+ t("task.online-migration.error.x-status-task-is-not-editable", {+ status: task_StatusToJSON(task.value.status),+ })+ );+ }+ }+ return errors;+ });++ const toggleGhost = async (spec: Plan_Spec, on: boolean) => {+ const overrides: Record<string, string> = {};+ if (on) {+ overrides["ghost"] = "1";+ }++ // Backup editing statements to `overrides.sqlList`+ const flattenSpecs = (issue.value.planEntity?.steps ?? []).flatMap(+ (step) => step.specs+ );+ const sqlList: string[] = [];+ flattenSpecs.forEach((spec, i) => {+ const sheetName = sheetNameForSpec(spec);+ const sheet = getLocalSheetByName(sheetName);+ sqlList[i] = getSheetStatement(sheet);+ });+ overrides["sqlList"] = JSON.stringify(sqlList);++ await reInitialize(overrides);+ };++ const context: IssueGhostContext = {+ viewType,+ showFlagsPanel,+ denyEditGhostFlagsReasons,+ toggleGhost,+ };++ provide(KEY, context);++ return context;+};++export const allowChangeTaskGhostFlags = (issue: ComposedIssue, task: Task) => {+ return [+ Task_Status.STATUS_UNSPECIFIED, // Pending create+ Task_Status.NOT_STARTED,+ Task_Status.FAILED,+ Task_Status.CANCELED,+ ].includes(task.status);+};++export const allowGhostForDatabase = (database: ComposedDatabase) => {+ return (+ database.instanceEntity.engine === Engine.MYSQL &&+ semverCompare(+ database.instanceEntity.engineVersion,+ MIN_GHOST_SUPPORT_MYSQL_VERSION,+ "gte"+ )+ );+};++export const allowGhostForSpec = (spec: Plan_Spec | undefined) => {+ const config = spec?.changeDatabaseConfig;+ if (!config) return false;++ return [+ Plan_ChangeDatabaseConfig_Type.MIGRATE,+ Plan_ChangeDatabaseConfig_Type.MIGRATE_GHOST,+ ].includes(config.type);+};++export const allowGhostForTask = (issue: ComposedIssue, task: Task) => {+ return (+ allowGhostForSpec(specForTask(issue.planEntity, task)) &&+ allowGhostForDatabase(databaseForTask(issue, task))+ );+};++export const ghostViewTypeForTask = (+ issue: ComposedIssue,+ task: Task+): GhostUIViewType => {+ if (isGroupingChangeTaskV1(issue, task)) {+ return "NONE";+ }++ const spec = specForTask(issue.planEntity, task);+ const config = spec?.changeDatabaseConfig;+ if (!config) {+ return "NONE";+ }+ if (config.type === Plan_ChangeDatabaseConfig_Type.MIGRATE) {+ return "OFF";+ }+ if (config.type === Plan_ChangeDatabaseConfig_Type.MIGRATE_GHOST) {+ return "ON";+ }+ return "NONE";+};diff --git a/frontend/src/components/IssueV1/components/StageSection/Actions/GhostSection/index.ts b/frontend/src/components/IssueV1/components/StageSection/Actions/GhostSection/index.tsnew file mode 100644index 0000000000..e8bc849440--- /dev/null+++ b/frontend/src/components/IssueV1/components/StageSection/Actions/GhostSection/index.ts@@ -0,0 +1,3 @@+import GhostSection from "./GhostSection.vue";++export default GhostSection;diff --git a/frontend/src/components/IssueV1/logic/base.ts b/frontend/src/components/IssueV1/logic/base.tsindex 943e7ea993..85784ee59d 100644--- a/frontend/src/components/IssueV1/logic/base.ts+++ b/frontend/src/components/IssueV1/logic/base.ts@@ -1,6 +1,7 @@import { asyncComputed } from "@vueuse/core";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 { useUIStateStore } from "@/store";@@ -36,6 +37,7 @@ export const useBaseIssueContext = (const uiStateStore = useUIStateStore();const route = useRoute();const router = useRouter();+ const dialog = useDialog();const events: IssueEvents = new Emittery();@@ -198,5 +200,6 @@ export const useBaseIssueContext = (selectedStage,selectedTask,formatOnSave,+ dialog,};};diff --git a/frontend/src/components/IssueV1/logic/context.ts b/frontend/src/components/IssueV1/logic/context.tsindex d2f1a6e1fe..61a8895bea 100644--- a/frontend/src/components/IssueV1/logic/context.ts+++ b/frontend/src/components/IssueV1/logic/context.ts@@ -65,6 +65,7 @@ export type IssueContext = {// miscdialog: ReturnType<typeof useDialog>;+ reInitialize: (overrides?: Record<string, string>) => Promise<void>;};const KEY = Symbol("bb.issue.context") as InjectionKey<IssueContext>;diff --git a/frontend/src/components/IssueV1/logic/initialize/create.ts b/frontend/src/components/IssueV1/logic/initialize/create.tsindex c60773a16d..e0f87cddb5 100644--- a/frontend/src/components/IssueV1/logic/initialize/create.ts+++ b/frontend/src/components/IssueV1/logic/initialize/create.ts@@ -1,7 +1,6 @@import { groupBy, orderBy } from "lodash-es";import { v4 as uuidv4 } from "uuid";import { reactive } from "vue";-import { type _RouteLocationBase } from "vue-router";import { rolloutServiceClient } from "@/grpcweb";import { TemplateType } from "@/plugins";import {@@ -43,45 +42,47 @@ import { sheetNameForSpec } from "../plan";import { createEmptyLocalSheet, getLocalSheetByName } from "../sheet";import { trySetDefaultAssignee } from "./assignee";+export type InitialSQL = {+ sqlList?: string[];+ sql?: string;+};+type CreateIssueParams = {databaseUIDList: string[];project: ComposedProject;- route: _RouteLocationBase;- initialSQL: {- sqlList?: string[];- sql?: string;- };+ query: Record<string, string>;+ initialSQL: InitialSQL;branch?: string;};-export const createIssueSkeleton = async (route: _RouteLocationBase) => {+export const createIssueSkeleton = async (query: Record<string, string>) => {const issue = emptyIssue();const me = useCurrentUserV1();issue.creator = `users/${me.value.email}`;issue.creatorEntity = me.value;const project = await useProjectV1Store().getOrFetchProjectByUID(- route.query.project as string+ query.project);issue.project = project.name;issue.projectEntity = project;issue.uid = nextUID();issue.name = `${project.name}/issues/${issue.uid}`;- issue.title = route.query.name as string;+ issue.title = query.name;issue.type = Issue_Type.DATABASE_CHANGE;issue.status = IssueStatus.OPEN;- const databaseUIDList = ((route.query.databaseList as string) || "")+ const databaseUIDList = (query.databaseList ?? "").split(",").filter((uid) => uid && uid !== String(UNKNOWN_ID));await prepareDatabaseList(databaseUIDList, project.uid);- const branch = (route.query.branch as string) || undefined;+ const branch = query.branch || undefined;const params: CreateIssueParams = {databaseUIDList,project,- route,- initialSQL: extractInitialSQLListFromQuery(route),+ query,+ initialSQL: extractInitialSQLListFromQuery(query),branch,};@@ -98,7 +99,7 @@ export const createIssueSkeleton = async (route: _RouteLocationBase) => {await trySetDefaultAssignee(issue);- const description = route.query.description as string;+ const description = query.description;if (description) {issue.description = description;}@@ -114,32 +115,29 @@ const prepareParamsContext = async (params: CreateIssueParams) => {};export const buildPlan = async (params: CreateIssueParams) => {- const { databaseUIDList, project, route } = params;+ const { databaseUIDList, project, query } = params;const plan = Plan.fromJSON({uid: nextUID(),});plan.name = `${project.name}/plans/${plan.uid}`;- if (route.query.changelist) {+ if (query.changelist) {// build plan for changelistplan.steps = await buildStepsViaChangelist(databaseUIDList,- route.query.changelist as string,+ query.changelist,params);- } else if (route.query.mode === "tenant") {+ } else if (query.mode === "tenant") {// in tenant mode, all specs share a unique sheetconst sheetUID = nextUID();// build tenant planif (databaseUIDList.length === 0) {// evaluate DeploymentConfig and generate steps/specs- if (- route.query.databaseGroupName &&- typeof route.query.databaseGroupName === "string"- ) {+ if (query.databaseGroupName) {plan.steps = await buildStepsForDatabaseGroup(params,- route.query.databaseGroupName as string+ query.databaseGroupName);} else {plan.steps = await buildStepsViaDeploymentConfig(params, sheetUID);@@ -298,11 +296,11 @@ export const buildStepsViaChangelist = async (export const buildSpecForTarget = async (target: string,- { project, route }: CreateIssueParams,+ { project, query }: CreateIssueParams,sheetUID?: string) => {const sheet = `${project.name}/sheets/${sheetUID ?? nextUID()}`;- const template = route.query.template as TemplateType;+ const template = query.template as TemplateType | undefined;const spec = Plan_Spec.fromJSON({id: uuidv4(),});@@ -311,10 +309,8 @@ export const buildSpecForTarget = async (target,type: Plan_ChangeDatabaseConfig_Type.DATA,});- if (route.query.sheetId) {- const sheet = await useSheetV1Store().getOrFetchSheetByUID(- route.query.sheetId as string- );+ if (query.sheetId) {+ const sheet = await useSheetV1Store().getOrFetchSheetByUID(query.sheetId);if (sheet) {spec.changeDatabaseConfig.sheet = sheet.name;}@@ -325,7 +321,7 @@ export const buildSpecForTarget = async (}if (template === "bb.issue.database.schema.update") {const type =- route.query.ghost === "1"+ query.ghost === "1"? Plan_ChangeDatabaseConfig_Type.MIGRATE_GHOST: Plan_ChangeDatabaseConfig_Type.MIGRATE;spec.changeDatabaseConfig = Plan_ChangeDatabaseConfig.fromJSON({@@ -372,11 +368,8 @@ const maybeWrapStatementsAsSheets = (rollout: Rollout,params: CreateIssueParams) => {- const { route } = params;- if (- !route.query.databaseGroupName ||- typeof route.query.databaseGroupName !== "string"- ) {+ const { query } = params;+ if (!query.databaseGroupName) {return;}const { stages } = rollout;@@ -446,12 +439,12 @@ const maybeSetInitialDatabaseConfigForSpec = (};const extractInitialSQLListFromQuery = (- route: _RouteLocationBase+ query: Record<string, string>): {sqlList?: string[];sql?: string;} => {- const sqlListJSON = route.query.sqlList as string;+ const sqlListJSON = query.sqlList;if (sqlListJSON && sqlListJSON.startsWith("[") && sqlListJSON.endsWith("]")) {try {const sqlList = JSON.parse(sqlListJSON) as string[];@@ -466,7 +459,7 @@ const extractInitialSQLListFromQuery = (// Nothing}}- const sql = route.query.sql;+ const sql = query.sql;if (sql && typeof sql === "string") {return {sql,diff --git a/frontend/src/components/IssueV1/logic/initialize/index.ts b/frontend/src/components/IssueV1/logic/initialize/index.tsindex fd3320f42b..6f82caa65e 100644--- a/frontend/src/components/IssueV1/logic/initialize/index.ts+++ b/frontend/src/components/IssueV1/logic/initialize/index.ts@@ -1,5 +1,10 @@import { computed, ref, Ref, watch } from "vue";-import { useRoute, useRouter, _RouteLocationBase } from "vue-router";+import {+ useRoute,+ useRouter,+ _RouteLocationBase,+ LocationQuery,+} from "vue-router";import { experimentalFetchIssueByUID } from "@/store";import { ComposedIssue, emptyIssue, EMPTY_ID, UNKNOWN_ID } from "@/types";import { idFromSlug } from "@/utils";@@ -25,7 +30,9 @@ export function useInitializeIssue(issueSlug: Ref<string>) {const runner = async (uid: string, url: string) => {const issue =uid === String(EMPTY_ID)- ? await createIssueSkeleton(router.resolve(url))+ ? await createIssueSkeleton(+ convertRouterQuery(router.resolve(url).query)+ ): await experimentalFetchIssueByUID(uid);return {issue,@@ -54,5 +61,27 @@ export function useInitializeIssue(issueSlug: Ref<string>) {{ immediate: true });- return { isCreating, issue, isInitializing };+ const reInitialize = async (overrides: Record<string, string> = {}) => {+ const url = route.fullPath;+ const query = convertRouterQuery(router.resolve(url).query);+ try {+ const updated = await createIssueSkeleton({ ...query, ...overrides });+ issue.value = updated;+ } catch {+ // Nothing+ }+ };++ return { isCreating, issue, 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/IssueV1/logic/utils.ts b/frontend/src/components/IssueV1/logic/utils.tsindex d714450cd0..ec194f2027 100644--- a/frontend/src/components/IssueV1/logic/utils.ts+++ b/frontend/src/components/IssueV1/logic/utils.ts@@ -1,3 +1,5 @@+import { NButton } from "naive-ui";+import { h } from "vue";import { t } from "@/plugins/i18n";import {pushNotification,@@ -11,7 +13,13 @@ import {UNKNOWN_ID,} from "@/types";import { Plan, Task, Task_Type } from "@/types/proto/v1/rollout_service";-import { extractDatabaseResourceName, flattenSpecList } from "@/utils";+import {+ defer,+ extractDatabaseResourceName,+ flattenSpecList,+ flattenTaskV1List,+} from "@/utils";+import { IssueContext } from "./context";export const databaseForTask = (issue: ComposedIssue, task: Task) => {if (@@ -107,3 +115,119 @@ export const notifyNotEditableLegacyIssue = () => {title: t("issue.not-editable-legacy-issue"),});};++export const chooseUpdateTarget = (+ issue: ComposedIssue,+ selectedTask: Task,+ filter: (task: Task) => boolean,+ dialog: IssueContext["dialog"],+ updateType: string,+ isBatchMode: boolean+) => {+ type Target = "CANCELED" | "TASK" | "STAGE" | "ALL";+ const d = defer<{ target: Target; tasks: Task[] }>();++ const targets: Record<Target, Task[]> = {+ CANCELED: [],+ TASK: [selectedTask],+ STAGE: (stageForTask(issue, selectedTask)?.tasks ?? []).filter(filter),+ ALL: flattenTaskV1List(issue.rolloutEntity).filter(filter),+ };++ if (isBatchMode) {+ dialog.info({+ title: t("issue.update-statement.self", { type: updateType }),+ 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", tasks: targets.ALL });+ },+ onNegativeClick: () => {+ d.resolve({ target: "CANCELED", tasks: [] });+ },+ });+ return d.promise;+ }++ if (targets.STAGE.length === 1 && targets.ALL.length === 1) {+ d.resolve({ target: "TASK", tasks: targets.TASK });+ return d.promise;+ }++ const $d = dialog.create({+ title: t("issue.update-statement.self", { type: updateType }),+ 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, tasks: targets[target] });+ $d.destroy();+ };++ const CANCEL = h(+ NButton,+ { size: "small", onClick: () => finish("CANCELED") },+ {+ default: () => t("common.cancel"),+ }+ );+ const TASK = h(+ NButton,+ { size: "small", onClick: () => finish("TASK") },+ {+ default: () => t("issue.update-statement.target.selected-task"),+ }+ );+ const buttons = [CANCEL, TASK];+ if (targets.STAGE.length > 1) {+ // More than one editable tasks in stage+ // Add "Selected stage" option+ const STAGE = h(+ NButton,+ { size: "small", onClick: () => finish("STAGE") },+ {+ default: () => t("issue.update-statement.target.selected-stage"),+ }+ );+ buttons.push(STAGE);+ }+ if (targets.ALL.length > targets.STAGE.length) {+ // More editable tasks in other stages+ // Add "All tasks" 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", tasks: [] });+ },+ });++ return d.promise;+};diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 30f54ef230..25a66505f1 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -380,7 +380,22 @@"action-failed-in-current-stage": "{action} failed tasks in current stage","action-all-tasks-in-current-stage": "{action} all tasks in current stage","cancel-task": "Cancel task | Cancel tasks",- "created": "Created"+ "created": "Created",+ "online-migration": {+ "self": "Online migration",+ "configure-ghost-parameters-for-db": "Configure gh-ost parameters for database '{db}'",+ "configure-ghost-parameters": "Configure gh-ost parameters",+ "ghost-parameters": "gh-ost parameters",+ "configure": "Configure",+ "error": {+ "some-tasks-are-not-editable-in-batch-mode": "Some tasks are not editable in batch mode",+ "task-is-not-editable": "This task is not editable",+ "x-status-task-is-not-editable": "{status} task is not editable",+ "nothing-changed": "Nothing changed"+ },+ "show-default-parameters": "Show default parameters",+ "hide-default-parameters": "Hide default parameters"+ }},"task-run": {"status": {@@ -1030,7 +1045,11 @@"sql-review-violations": "SQL Review Violations"},"no-assignee-candidates": "There is no valid assignee candidates in this project. Please contact the project owner.",- "allow-any-following-roles-to-be-assignee": "Allow any following roles to be assignee"+ "allow-any-following-roles-to-be-assignee": "Allow any following roles to be assignee",+ "error": {+ "issue-is-not-open": "The issue is not open",+ "you-don-have-privilege-to-edit-this-issue": "You don't have privilege to edit this issue"+ }},"alter-schema": {"vcs-enabled": "This project has enabled VCS based version control and selecting database below will navigate you to the corresponding Git repository to initiate the change process.",diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex 7bf25e4669..53927b9a24 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -380,7 +380,22 @@"action-failed-in-current-stage": "{action} tareas fallidas en la etapa actual","action-all-tasks-in-current-stage": "{action} todas las tareas en la etapa actual","cancel-task": "Cancelar tarea | Cancelar tareas",- "created": "Creado"+ "created": "Creado",+ "online-migration": {+ "self": "Migración en línea",+ "configure-ghost-parameters-for-db": "Configurar los parámetros de gh-ost para la base de datos '{db}'",+ "configure-ghost-parameters": "Configurar los parámetros de gh-ost",+ "ghost-parameters": "parámetros de gh-ost",+ "configure": "Configurar",+ "error": {+ "some-tasks-are-not-editable-in-batch-mode": "Algunas tareas no se pueden editar en modo por lotes",+ "task-is-not-editable": "Esta tarea no es editable",+ "x-status-task-is-not-editable": "La tarea {status} no es editable",+ "nothing-changed": "nada ha cambiado"+ },+ "show-default-parameters": "Mostrar parámetros predeterminados",+ "hide-default-parameters": "Ocultar parámetros predeterminados"+ }},"task-run": {"status": {@@ -1029,7 +1044,11 @@"sql-review-violations": "Infracciones de revisión de SQL"},"no-assignee-candidates": "No hay candidatos asignados válidos en este proyecto. \nPor favor contacte al propietario del proyecto.",- "allow-any-following-roles-to-be-assignee": "Permitir que se asignen los siguientes roles"+ "allow-any-following-roles-to-be-assignee": "Permitir que se asignen los siguientes roles",+ "error": {+ "issue-is-not-open": "El tema no está abierto.",+ "you-don-have-privilege-to-edit-this-issue": "No tienes privilegios para editar este número."+ }},"alter-schema": {"vcs-enabled": "Este proyecto ha habilitado el control de versiones basado en VCS y seleccionar la base de datos a continuación lo llevará al repositorio Git correspondiente para iniciar el proceso de cambio.",diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 98abf896bc..a8401820c4 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -378,7 +378,22 @@"action-failed-in-current-stage": "{action}当前阶段失败的任务","action-all-tasks-in-current-stage": "{action}当前阶段的所有任务","cancel-task": "取消任务",- "created": "创建于"+ "created": "创建于",+ "online-migration": {+ "self": "在线迁移",+ "configure-ghost-parameters-for-db": "为数据库「{db}」配置 gh-ost 参数",+ "configure-ghost-parameters": "配置 gh-ost 参数",+ "ghost-parameters": "gh-ost 参数",+ "configure": "配置",+ "error": {+ "some-tasks-are-not-editable-in-batch-mode": "某些任务在批量模式下不可编辑",+ "task-is-not-editable": "该任务不可编辑",+ "x-status-task-is-not-editable": "{status} 的任务不可编辑",+ "nothing-changed": "无任何改变"+ },+ "show-default-parameters": "显示默认参数",+ "hide-default-parameters": "隐藏默认参数"+ }},"task-run": {"status": {@@ -1027,7 +1042,11 @@"sql-review-violations": "违反的 SQL 审核规则"},"no-assignee-candidates": "该项目中没有有效的发布人候选人。\n请联系项目所有者。",- "allow-any-following-roles-to-be-assignee": "允许以下任何角色作为发布人"+ "allow-any-following-roles-to-be-assignee": "允许以下任何角色作为发布人",+ "error": {+ "issue-is-not-open": "工单不是开启状态",+ "you-don-have-privilege-to-edit-this-issue": "您没有权限编辑此工单"+ }},"alter-schema": {"vcs-enabled": "该项目开启了基于 VCS 的版本管理,选择下面的数据库会将您导航到相应的 Git 仓库以发起变更流程。",diff --git a/frontend/src/utils/dom.ts b/frontend/src/utils/dom.tsindex e6a5f09a4d..271bf75819 100644--- a/frontend/src/utils/dom.ts+++ b/frontend/src/utils/dom.ts@@ -89,3 +89,17 @@ export const readFileAsync = (cleanup();});};++export const getScrollParent = (+ element: HTMLElement | null | undefined+): HTMLElement => {+ if (!element) {+ return document.body;+ }++ if (element.scrollHeight > element.clientHeight) {+ return element;+ } else {+ return getScrollParent(element.parentElement);+ }+};diff --git a/frontend/src/utils/issue/index.ts b/frontend/src/utils/issue/index.tsindex 74b06d3fd5..c4d3d19ceb 100644--- a/frontend/src/utils/issue/index.ts+++ b/frontend/src/utils/issue/index.ts@@ -30,7 +30,7 @@ export function isDatabaseRelatedIssueType(issueType: IssueType): boolean {export const generateIssueName = (type: "bb.issue.database.schema.update" | "bb.issue.database.data.update",databaseNameList: string[],- isOnlineMode: boolean+ isOnlineMode = false) => {// Create a user friendly default issue nameconst issueNameParts: string[] = [];diff --git a/frontend/src/utils/util.ts b/frontend/src/utils/util.tsindex d77697023d..c90a899228 100644--- a/frontend/src/utils/util.ts+++ b/frontend/src/utils/util.ts@@ -302,16 +302,6 @@ export const isNullOrUndefined = (value: any) => {return value === null || value === undefined;};-export const getScrollParent = (- element: HTMLElement | null | undefined-): HTMLElement => {- if (!element) {- return document.body;- }-- if (element.scrollHeight > element.clientHeight) {- return element;- } else {- return getScrollParent(element.parentElement);- }+export const onlyAllowNumber = (value: string) => {+ return value === "" || /^\d+$/.test(value);};diff --git a/frontend/src/utils/v1/database.ts b/frontend/src/utils/v1/database.tsindex 628f5a3eee..739b720f16 100644--- a/frontend/src/utils/v1/database.ts+++ b/frontend/src/utils/v1/database.ts@@ -312,7 +312,7 @@ export function filterDatabaseV1ByKeyword(return false;}-const MIN_GHOST_SUPPORT_MYSQL_VERSION = "5.7.0";+export const MIN_GHOST_SUPPORT_MYSQL_VERSION = "5.7.0";export function allowGhostMigrationV1(databaseList: ComposedDatabase[]diff --git a/frontend/src/views/DatabaseDetail.vue b/frontend/src/views/DatabaseDetail.vueindex df1b983999..ace9e8f2f7 100644--- a/frontend/src/views/DatabaseDetail.vue+++ b/frontend/src/views/DatabaseDetail.vue@@ -202,8 +202,6 @@</BBModal></div>- <GhostDialog ref="ghostDialog" />-<BBModalv-if="state.showSchemaDiagram":title="$t('schema-diagram.self')"@@ -232,12 +230,11 @@import dayjs from "dayjs";import { startCase } from "lodash-es";import { ClientError } from "nice-grpc-web";-import { computed, onMounted, reactive, watch, ref } from "vue";+import { computed, onMounted, reactive, watch } from "vue";import { useI18n } from "vue-i18n";import { useRouter } from "vue-router";import { useRoute } from "vue-router";import { BBTabFilterItem } from "@/bbkit/types";-import { GhostDialog } from "@/components/AlterSchemaPrepForm";import DatabaseBackupPanel from "@/components/DatabaseBackupPanel.vue";import DatabaseChangeHistoryPanel from "@/components/DatabaseChangeHistoryPanel.vue";import {@@ -265,15 +262,12 @@ import {import {UNKNOWN_ID,DEFAULT_PROJECT_V1_NAME,- ComposedDatabase,unknownEnvironment,} from "@/types";import { State } from "@/types/proto/v1/common";-import { TenantMode } from "@/types/proto/v1/project_service";import {idFromSlug,hasWorkspacePermissionV1,- allowGhostMigrationV1,isPITRDatabaseV1,isArchivedDatabaseV1,instanceV1HasBackupRestore,@@ -310,7 +304,6 @@ const { t } = useI18n();const router = useRouter();const databaseV1Store = useDatabaseV1Store();const dbSchemaStore = useDBSchemaV1Store();-const ghostDialog = ref<InstanceType<typeof GhostDialog>>();const databaseTabItemList = computed((): DatabaseTabItem[] => {if (!allowToChangeDatabase.value) {@@ -498,34 +491,9 @@ const tryTransferProject = () => {state.showTransferDatabaseModal = true;};-// 'normal' -> normal migration-// 'online' -> online migration-// false -> user clicked cancel button-const isUsingGhostMigration = async (databaseList: ComposedDatabase[]) => {- if (project.value.tenantMode === TenantMode.TENANT_MODE_ENABLED) {- // Not available for tenant mode now.- return "normal";- }-- // check if all selected databases supports gh-ost- if (allowGhostMigrationV1(databaseList)) {- // open the dialog to ask the user- const { result, mode } = await ghostDialog.value!.open();- if (!result) {- return false; // return false when user clicked the cancel button- }- return mode;- }-- // fallback to normal- return "normal";-};-const createMigration = async (type: "bb.issue.database.schema.update" | "bb.issue.database.data.update") => {- type AlterMode = "online" | "normal" | false;- let mode: AlterMode = "normal";if (type === "bb.issue.database.schema.update") {if (database.value.syncState === State.ACTIVE &&@@ -534,24 +502,14 @@ const createMigration = async (state.showSchemaEditorModal = true;return;}-- // Check and show a normal/online selection modal dialog if needed.- mode = await isUsingGhostMigration([database.value]);}- if (mode === false) return;// Create a user friendly default issue nameconst issueNameParts: string[] = [];issueNameParts.push(`[${database.value.databaseName}]`);- if (mode === "online") {- issueNameParts.push("Online schema change");- } else {- issueNameParts.push(- type === "bb.issue.database.schema.update"- ? `Alter schema`- : `Change data`- );- }+ issueNameParts.push(+ type === "bb.issue.database.schema.update" ? `Alter schema` : `Change data`+ );const datetime = dayjs().format("@MM-DD HH:mm");const tz = "UTC" + dayjs().format("ZZ");issueNameParts.push(`${datetime} ${tz}`);@@ -562,9 +520,6 @@ const createMigration = async (project: project.value.uid,databaseList: database.value.uid,};- if (mode === "online") {- query.ghost = "1";- }router.push({name: "workspace.issue.detail",diff --git a/frontend/src/views/IssueDetailV1.vue b/frontend/src/views/IssueDetailV1.vueindex e1eb73bf72..d447605ca6 100644--- a/frontend/src/views/IssueDetailV1.vue+++ b/frontend/src/views/IssueDetailV1.vue@@ -50,7 +50,8 @@ const state = reactive<LocalState>({const issueSlug = computed(() => props.issueSlug);-const { isCreating, issue, isInitializing } = useInitializeIssue(issueSlug);+const { isCreating, issue, isInitializing, reInitialize } =+ useInitializeIssue(issueSlug);const ready = computed(() => {return !isInitializing.value && !!issue.value;});@@ -61,6 +62,7 @@ provideIssueContext(isCreating,issue,ready,+ reInitialize,...useBaseIssueContext({isCreating,ready,