Skip to content

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

chore: changelog in sync schema (#14795)

boojackd3e18b9655b5
diff --git a/frontend/src/App.vue b/frontend/src/App.vue
index 16534900fc..a8d2f59f66 100644
--- a/frontend/src/App.vue
+++ b/frontend/src/App.vue
@@ -111,11 +111,19 @@ onMounted(async () => {
watchEffect(async () => {
// Override app profile
overrideAppProfile();
+});
- if (authStore.currentUserId) {
- await workspaceStore.fetchIamPolicy();
+watch(
+ () => authStore.currentUserId,
+ async (currentUserId) => {
+ if (currentUserId) {
+ await workspaceStore.fetchIamPolicy();
+ }
+ },
+ {
+ immediate: true,
}
-});
+);
onErrorCaptured((error: any /* , _, info */) => {
// Handle grpc request error.
diff --git a/frontend/src/components/Branch/BranchDetailView.vue b/frontend/src/components/Branch/BranchDetailView.vue
index dd6c0aee5c..52b36e0fd3 100644
--- a/frontend/src/components/Branch/BranchDetailView.vue
+++ b/frontend/src/components/Branch/BranchDetailView.vue
@@ -126,7 +126,7 @@ import { useRouter } from "vue-router";
import { BBButtonConfirm } from "@/bbkit";
import DatabaseInfo from "@/components/DatabaseInfo.vue";
import { validateDatabaseMetadata } from "@/components/SchemaEditorLite";
-import TargetDatabasesSelectPanel from "@/components/SyncDatabaseSchema/TargetDatabasesSelectPanel.vue";
+import TargetDatabasesSelectPanel from "@/components/SyncDatabaseSchemaV1/TargetDatabasesSelectPanel.vue";
import {
PROJECT_V1_ROUTE_BRANCHES,
PROJECT_V1_ROUTE_BRANCH_DETAIL,
diff --git a/frontend/src/components/Changelog/ChangelogDetail.vue b/frontend/src/components/Changelog/ChangelogDetail.vue
index 868f0f2eeb..c9c9625fe3 100644
--- a/frontend/src/components/Changelog/ChangelogDetail.vue
+++ b/frontend/src/components/Changelog/ChangelogDetail.vue
@@ -1,6 +1,12 @@
<template>
<div class="focus:outline-none" tabindex="0" v-bind="$attrs">
<NoPermissionPlaceholder v-if="!hasPermission" />
+ <div
+ v-if="state.loading"
+ class="flex items-center justify-center py-2 text-gray-400 text-sm"
+ >
+ <BBSpin />
+ </div>
<main v-else-if="changelog" class="flex flex-col relative gap-y-6">
<!-- Highlight Panel -->
<div
@@ -10,12 +16,12 @@
<!-- Summary -->
<div class="flex items-center space-x-2">
<ChangelogStatusIcon :status="changelog.status" />
- <h1 class="text-xl font-bold leading-6 text-main truncate">
- {{ $t("common.version") }} {{ changelog.version }}
- </h1>
<NTag round>
{{ changelog_TypeToJSON(changelog.type) }}
</NTag>
+ <NTag v-if="changelog.version" round>
+ {{ $t("common.version") }} {{ changelog.version }}
+ </NTag>
</div>
<dl
class="flex flex-col space-y-1 md:space-y-0 md:flex-row md:flex-wrap"
@@ -52,27 +58,25 @@
</div>
</div>
- <div v-if="affectedTables.length > 0">
- <span class="flex items-center text-lg text-main capitalize">
- {{ $t("change-history.affected-tables") }}
- </span>
- <div>
- <span
- v-for="(affectedTable, i) in affectedTables"
- :key="`${i}.${affectedTable.schema}.${affectedTable.table}`"
- :class="[
- 'mr-3 mb-2',
- !affectedTable.dropped
- ? 'text-blue-600 cursor-pointer hover:opacity-80'
- : 'mb-2 text-gray-400 italic',
- ]"
- @click="handleAffectedTableClick(affectedTable)"
- >{{ getAffectedTableDisplayName(affectedTable) }}</span
- >
- </div>
- </div>
-
<div class="flex flex-col gap-y-6">
+ <div v-if="affectedTables.length > 0">
+ <span class="flex items-center text-lg text-main capitalize">
+ {{ $t("change-history.affected-tables") }}
+ </span>
+ <div class="flex flex-wrap gap-x-3 gap-y-2">
+ <span
+ v-for="(affectedTable, i) in affectedTables"
+ :key="`${i}.${affectedTable.schema}.${affectedTable.table}`"
+ :class="[
+ !affectedTable.dropped
+ ? 'text-blue-600 cursor-pointer'
+ : 'mb-2 text-gray-400 italic',
+ ]"
+ >
+ {{ getAffectedTableDisplayName(affectedTable) }}
+ </span>
+ </div>
+ </div>
<div class="flex flex-col gap-y-2">
<a
id="statement"
@@ -85,7 +89,7 @@
class="btn-icon ml-1"
@click.prevent="copyStatement"
>
- <heroicons-outline:clipboard class="w-6 h-6" />
+ <ClipboardIcon class="w-5 h-5" />
</button>
</a>
<MonacoEditor
@@ -94,20 +98,6 @@
:readonly="true"
:auto-height="{ min: 120, max: 480 }"
/>
- <div v-if="guessedIsBasicView">
- <NButton
- quaternary
- size="small"
- :disabled="state.loading"
- @click="fetchFullChangelogs"
- >
- <template #icon>
- <BBSpin v-if="state.loading" />
- <ChevronDownIcon v-else class="w-5" />
- </template>
- {{ $t("change-history.view-full") }}
- </NButton>
- </div>
</div>
<div v-if="showSchemaSnapshot" class="flex flex-col gap-y-2">
<a
@@ -121,58 +111,24 @@
class="btn-icon ml-1"
@click.prevent="copySchema"
>
- <heroicons-outline:clipboard class="w-6 h-6" />
+ <ClipboardIcon class="w-5 h-5" />
</button>
</a>
- <div v-if="hasDrift" class="flex items-center gap-x-2">
- <div class="flex items-center text-sm font-normal">
- <heroicons-outline:exclamation-circle
- class="w-5 h-5 mr-0.5 text-error"
- />
- <span>{{ $t("change-history.schema-drift-detected") }}</span>
- </div>
- <div
- class="normal-link text-sm"
- data-label="bb-changelog-view-drift-button"
- @click="state.viewDrift = true"
- >
- {{ $t("change-history.view-drift") }}
- </div>
- </div>
-
<div class="flex flex-row items-center gap-x-2">
<div v-if="allowShowDiff" class="flex space-x-1 items-center">
<NSwitch
:value="state.showDiff"
size="small"
- :disabled="state.loading"
data-label="bb-changelog-diff-switch"
- @update:value="switchShowDiff"
+ @update:value="state.showDiff = $event"
/>
<span class="text-sm font-semibold">
{{ $t("change-history.show-diff") }}
</span>
</div>
<div class="textinfolabel">
- <i18n-t
- v-if="state.showDiff"
- tag="span"
- keypath="change-history.left-vs-right"
- >
- <template #prevLink>
- <router-link
- v-if="previousChangelog"
- class="normal-link"
- :to="previousChangelogLink"
- >
- ({{ previousChangelog.version }})
- </router-link>
- </template>
- </i18n-t>
- <template v-else>
- {{ $t("change-history.schema-snapshot-after-change") }}
- </template>
+ {{ $t("change-history.schema-snapshot-after-change") }}
</div>
<div v-if="!allowShowDiff" class="text-sm font-normal text-accent">
({{ $t("change-history.no-schema-change") }})
@@ -187,107 +143,39 @@
:readonly="true"
:auto-height="{ min: 120, max: 600 }"
/>
- <template v-else>
- <div v-if="changelog.schema" class="space-y-2">
- <MonacoEditor
- class="h-auto max-h-[600px] min-h-[120px] border rounded-md text-sm overflow-clip relative"
- :content="changelogSchema"
- :readonly="true"
- :auto-height="{ min: 120, max: 600 }"
- />
- <div
- v-if="
- getStatementSize(changelog.schema).ne(changelog.schemaSize)
- "
- >
- <NButton
- quaternary
- size="small"
- :disabled="state.loading"
- @click="fetchFullChangelogs"
- >
- <template #icon>
- <BBSpin v-if="state.loading" />
- <ChevronDownIcon v-else class="w-5" />
- </template>
- {{ $t("change-history.view-full") }}
- </NButton>
- </div>
- </div>
- <div v-else>
- {{ $t("change-history.current-schema-empty") }}
- </div>
- </template>
+ <MonacoEditor
+ v-else-if="changelog.schema"
+ class="h-auto max-h-[600px] min-h-[120px] border rounded-md text-sm overflow-clip relative"
+ :content="changelogSchema"
+ :readonly="true"
+ :auto-height="{ min: 120, max: 600 }"
+ />
+ <div v-else>
+ {{ $t("change-history.current-schema-empty") }}
+ </div>
</div>
</div>
</main>
-
- <BBModal
- v-if="changelog && previousChangelog && state.viewDrift"
- @close="state.viewDrift = false"
- >
- <template #title>
- <span>{{ $t("change-history.schema-drift") }}</span>
- <span class="mx-2">-</span>
- <i18n-t tag="span" keypath="change-history.left-vs-right">
- <template #prevLink>
- <router-link class="normal-link" :to="previousChangelogLink">
- ({{ previousChangelog.version }})
- </router-link>
- </template>
- </i18n-t>
- </template>
-
- <div
- class="space-y-4 flex flex-col overflow-hidden"
- style="width: calc(100vw - 10rem); height: calc(100vh - 12rem)"
- >
- <DiffEditor
- class="flex-1 w-full border rounded-md overflow-clip"
- :original="previousChangelog.schema"
- :modified="changelog.schema"
- :readonly="true"
- />
- <div class="flex justify-end">
- <NButton type="primary" @click.prevent="state.viewDrift = false">
- {{ $t("common.close") }}
- </NButton>
- </div>
- </div>
- </BBModal>
</div>
-
- <TableDetailDrawer
- :show="!!selectedAffectedTable"
- :database-name="database.name"
- :schema-name="selectedAffectedTable?.schema ?? ''"
- :table-name="selectedAffectedTable?.table ?? ''"
- :classification-config="classificationConfig"
- @dismiss="selectedAffectedTable = undefined"
- />
</template>
<script lang="ts" setup>
-import { useTitle } from "@vueuse/core";
-import { ChevronDownIcon } from "lucide-vue-next";
-import { NButton, NSwitch, NTag } from "naive-ui";
-import { computed, reactive, watch, ref, unref } from "vue";
-import { BBModal, BBSpin } from "@/bbkit";
+import { ClipboardIcon } from "lucide-vue-next";
+import { NSwitch, NTag } from "naive-ui";
+import { computed, reactive, watch, unref } from "vue";
+import { BBSpin } from "@/bbkit";
import { DiffEditor, MonacoEditor } from "@/components/MonacoEditor";
-import TableDetailDrawer from "@/components/TableDetailDrawer.vue";
import {
pushNotification,
useChangelogStore,
useDBSchemaV1Store,
useUserStore,
- useSettingV1Store,
useDatabaseV1ByName,
} from "@/store";
-import { getDateForPbTimestamp, type AffectedTable } from "@/types";
+import { getDateForPbTimestamp } from "@/types";
import { Engine } from "@/types/proto/v1/common";
import type { Changelog } from "@/types/proto/v1/database_service";
import {
- Changelog_Type,
changelog_TypeToJSON,
ChangelogView,
} from "@/types/proto/v1/database_service";
@@ -300,17 +188,15 @@ import {
getAffectedTableDisplayName,
} from "@/utils";
import {
- changelogLink,
- extractChangelogUID,
getAffectedTablesOfChangelog,
+ getChangelogChangeType,
} from "@/utils/v1/changelog";
import NoPermissionPlaceholder from "../misc/NoPermissionPlaceholder.vue";
import ChangelogStatusIcon from "./ChangelogStatusIcon.vue";
interface LocalState {
- showDiff: boolean;
- viewDrift: boolean;
loading: boolean;
+ showDiff: boolean;
}
const props = defineProps<{
@@ -319,103 +205,42 @@ const props = defineProps<{
changelogId: string;
}>();
+const dbSchemaStore = useDBSchemaV1Store();
+const changelogStore = useChangelogStore();
const state = reactive<LocalState>({
- showDiff: false,
- viewDrift: false,
loading: false,
+ showDiff: false,
});
-const dbSchemaStore = useDBSchemaV1Store();
-const settingStore = useSettingV1Store();
-const changelogStore = useChangelogStore();
-const selectedAffectedTable = ref<AffectedTable | undefined>();
-
const { database } = useDatabaseV1ByName(props.database);
const hasPermission = computed(() =>
+ // TODO: update permissions.
hasProjectPermissionV2(database.value.projectEntity, "bb.changeHistories.get")
);
-const classificationConfig = computed(() => {
- return settingStore.getProjectClassification(
- database.value.projectEntity.dataClassificationConfigId
- );
-});
-
const changelogName = computed(() => {
return `${props.database}/changelogs/${props.changelogId}`;
});
-const affectedTables = computed(() => {
- if (changelog.value === undefined) {
- return [];
- }
- return getAffectedTablesOfChangelog(changelog.value);
-});
-
-const showSchemaSnapshot = computed(() => {
- return database.value.instanceResource.engine !== Engine.RISINGWAVE;
+const changelog = computed((): Changelog | undefined => {
+ return changelogStore.getChangelogByName(changelogName.value);
});
-watch(
- [database.value.name, changelogName],
- async ([_, name]) => {
- await Promise.all([
- dbSchemaStore.getOrFetchDatabaseMetadata({
- database: database.value.name,
- skipCache: false,
- }),
- changelogStore.getOrFetchChangelogByName(
- unref(name),
- ChangelogView.CHANGELOG_VIEW_FULL
- ),
- ]);
- },
- { immediate: true }
-);
-
-const switchShowDiff = async (showDiff: boolean) => {
- await fetchFullChangelogs();
- state.showDiff = showDiff;
-};
-
-const handleAffectedTableClick = (affectedTable: AffectedTable): void => {
- if (affectedTable.dropped) {
- return;
+const creator = computed(() => {
+ if (!changelog.value) {
+ return undefined;
}
- selectedAffectedTable.value = affectedTable;
-};
-
-// get all change histories before (include) the one of given id, ordered by descending version.
-const prevChangelogList = computed(() => {
- const changelogList = changelogStore.changelogListByDatabase(
- database.value.name
- );
-
- // The returned changelog list has been ordered by `id` DESC or (`namespace` ASC, `sequence` DESC) .
- // We can obtain prevChangelogList by cutting up the array by the `changeHistoryId`.
- const idx = changelogList.findIndex(
- (changelog) => extractChangelogUID(changelog.name) === props.changelogId
+ return useUserStore().getUserByEmail(
+ extractUserResourceName(changelog.value.creator)
);
- if (idx === -1) {
- return [];
- }
- return changelogList.slice(idx);
-});
-
-const changelog = computed((): Changelog | undefined => {
- return changelogStore.getChangelogByName(changelogName.value);
});
const changelogSchema = computed(() => {
if (!changelog.value) {
return "";
}
- let schema = changelog.value.schema;
- if (guessedIsBasicView.value) {
- schema = `${schema}${schema.endsWith("\n") ? "" : "\n"}...`;
- }
- return schema;
+ return changelog.value.schema;
});
const changelogStatement = computed(() => {
@@ -433,46 +258,15 @@ const changelogStatement = computed(() => {
return statement;
});
-// previousChangelog is the last changelog before the one of given id.
-// Only referenced if hasDrift is true.
-const previousChangelog = computed((): Changelog | undefined => {
- const prev = prevChangelogList.value[1];
- if (!prev) return undefined;
- return changelogStore.getChangelogByName(prev.name) ?? prev;
-});
-
-const fetchFullPreviousChangelog = async () => {
- const prev = previousChangelog.value;
- if (!prev) return;
- await changelogStore.getOrFetchChangelogByName(
- prev.name,
- ChangelogView.CHANGELOG_VIEW_FULL
- );
-};
-
-const fetchFullChangelogs = async () => {
- if (state.loading) {
- return;
- }
- state.loading = true;
- try {
- await Promise.all([
- changelogStore.getOrFetchChangelogByName(
- changelogName.value,
- ChangelogView.CHANGELOG_VIEW_FULL
- ),
- fetchFullPreviousChangelog(),
- ]);
- } finally {
- state.loading = false;
+const affectedTables = computed(() => {
+ if (changelog.value === undefined) {
+ return [];
}
-};
+ return getAffectedTablesOfChangelog(changelog.value);
+});
-const guessedIsBasicView = computed(() => {
- if (!changelog.value) return true;
- return getStatementSize(changelog.value.statement).ne(
- changelog.value.statementSize
- );
+const showSchemaSnapshot = computed(() => {
+ return database.value.instanceResource.engine !== Engine.RISINGWAVE;
});
// "Show diff" feature is enabled when current migration has changed the schema.
@@ -480,45 +274,10 @@ const allowShowDiff = computed((): boolean => {
if (!changelog.value) {
return false;
}
- return true;
-});
-
-// A schema drift is detected when the schema AFTER previousChangelog has been
-// changed unexpectedly BEFORE current changelog.
-const hasDrift = computed((): boolean => {
- if (!changelog.value) {
- return false;
- }
- if (changelog.value.type === Changelog_Type.BASELINE) {
- return false;
- }
- if (guessedIsBasicView.value) {
- return false;
- }
-
- return (
- prevChangelogList.value.length > 1 && // no drift if no previous changelog
- previousChangelog.value?.schema !== changelog.value.prevSchema
- );
-});
-
-const creator = computed(() => {
- if (!changelog.value) {
- return undefined;
- }
- const email = extractUserResourceName(changelog.value.creator);
- return useUserStore().getUserByEmail(email);
-});
-
-const previousChangelogLink = computed(() => {
- const previous = previousChangelog.value;
- if (!previous) return "";
- return changelogLink(previous);
+ return getChangelogChangeType(changelog.value.type) === "DDL";
});
const copyStatement = async () => {
- await fetchFullChangelogs();
-
if (!changelogStatement.value) {
return false;
}
@@ -532,8 +291,6 @@ const copyStatement = async () => {
};
const copySchema = async () => {
- await fetchFullChangelogs();
-
if (!changelogSchema.value) {
return false;
}
@@ -547,16 +304,21 @@ const copySchema = async () => {
};
watch(
- guessedIsBasicView,
- (basic) => {
- if (!basic) {
- fetchFullPreviousChangelog();
- }
+ [database.value.name, changelogName],
+ async ([_, name]) => {
+ state.loading = true;
+ await Promise.all([
+ dbSchemaStore.getOrFetchDatabaseMetadata({
+ database: database.value.name,
+ skipCache: false,
+ }),
+ changelogStore.getOrFetchChangelogByName(
+ unref(name),
+ ChangelogView.CHANGELOG_VIEW_FULL
+ ),
+ ]);
+ state.loading = false;
},
- {
- immediate: true,
- }
+ { immediate: true }
);
-
-useTitle(changelog.value?.version || "Changelog");
</script>
diff --git a/frontend/src/components/Changelog/PagedChangelogTable.vue b/frontend/src/components/Changelog/PagedChangelogTable.vue
index 2e71380154..9749bb6df0 100644
--- a/frontend/src/components/Changelog/PagedChangelogTable.vue
+++ b/frontend/src/components/Changelog/PagedChangelogTable.vue
@@ -30,8 +30,7 @@ import { stringify } from "qs";
import type { PropType } from "vue";
import { computed, reactive, watch } from "vue";
import { BBSpin } from "@/bbkit";
-import { databaseServiceClient } from "@/grpcweb";
-import { useIsLoggedIn } from "@/store";
+import { useChangelogStore, useIsLoggedIn } from "@/store";
import type { ComposedDatabase, SearchChangeLogParams } from "@/types";
import type { Changelog } from "@/types/proto/v1/database_service";
@@ -84,6 +83,7 @@ const state = reactive<LocalState>({
changelogList: [],
paginationToken: "",
});
+const changelogStore = useChangelogStore();
const sessionState = useSessionStorage<SessionState>(props.sessionKey, {
page: 1,
@@ -132,7 +132,7 @@ const fetchData = async (refresh = false) => {
try {
const { nextPageToken, changelogs } =
- await databaseServiceClient.listChangelogs({
+ await changelogStore.fetchChangelogList({
parent: props.database.name,
filter: buildFilter(props.searchChangelogs),
pageSize: expectedRowCount,
diff --git a/frontend/src/components/Database/DatabaseChangelogPanel.vue b/frontend/src/components/Database/DatabaseChangelogPanel.vue
index 339828551c..c1787a8c59 100644
--- a/frontend/src/components/Database/DatabaseChangelogPanel.vue
+++ b/frontend/src/components/Database/DatabaseChangelogPanel.vue
@@ -9,10 +9,7 @@
/>
</div>
<div class="w-40">
- <ChangeTypeSelect
- v-model:change-type="state.selectedChangeType"
- :changelogs="changelogs"
- />
+ <ChangeTypeSelect v-model:change-type="state.selectedChangeType" />
</div>
</div>
<div class="flex flex-row justify-end items-center grow space-x-2">
@@ -122,7 +119,7 @@
import dayjs from "dayjs";
import saveAs from "file-saver";
import JSZip from "jszip";
-import { computed, onBeforeMount, reactive } from "vue";
+import { computed, reactive } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import { BBAlert, BBSpin } from "@/bbkit";
@@ -138,8 +135,7 @@ import {
PROJECT_V1_ROUTE_ISSUE_DETAIL,
PROJECT_V1_ROUTE_SYNC_SCHEMA,
} from "@/router/dashboard/projectV1";
-import { useChangelogStore, useDBSchemaV1Store } from "@/store";
-import { DEFAULT_PAGE_SIZE } from "@/store/modules/common";
+import { useChangelogStore } from "@/store";
import type { ComposedDatabase, Table } from "@/types";
import { DEFAULT_PROJECT_NAME } from "@/types";
import {
@@ -177,22 +173,6 @@ const state = reactive<LocalState>({
const { allowAlterSchema } = useDatabaseDetailContext();
-const prepareChangelogList = async () => {
- state.loading = true;
- await changelogStore.fetchChangelogList({
- parent: props.database.name,
- pageSize: DEFAULT_PAGE_SIZE,
- });
- // prepare database metadata for getting affected tables.
- await useDBSchemaV1Store().getOrFetchDatabaseMetadata({
- database: props.database.name,
- skipCache: true, // Skip cache to get the latest metadata.
- });
- state.loading = false;
-};
-
-onBeforeMount(prepareChangelogList);
-
const allowExportChangelog = computed(() => {
return state.selectedChangelogNames.length > 0;
});
@@ -201,10 +181,6 @@ const allowEstablishBaseline = computed(() => {
return allowAlterSchema.value;
});
-const changelogs = computed(() => {
- return changelogStore.changelogListByDatabase(props.database.name);
-});
-
const selectedChangelogForRollback = computed(() => {
if (state.selectedChangelogNames.length !== 1) {
return;
@@ -223,7 +199,7 @@ const rollback = () => {
projectId: extractProjectResourceName(props.database.project),
},
query: {
- version: selectedChangelogForRollback.value.name,
+ changelog: selectedChangelogForRollback.value.name,
target: props.database.name,
},
});
diff --git a/frontend/src/components/SyncDatabaseSchema/DatabaseSchemaSelector.vue b/frontend/src/components/SyncDatabaseSchema/DatabaseSchemaSelector.vue
deleted file mode 100644
index 7213c83168..0000000000
--- a/frontend/src/components/SyncDatabaseSchema/DatabaseSchemaSelector.vue
+++ /dev/null
@@ -1,501 +0,0 @@
-<template>
- <div
- class="w-full mx-auto flex flex-col justify-start items-start space-y-3 mb-6"
- >
- <div
- v-if="!disableProjectSelect"
- class="w-full flex flex-col gap-y-2 lg:flex-row justify-start items-start lg:items-center"
- >
- <span class="flex w-40 items-center shrink-0 text-sm">
- {{ $t("common.project") }}
- </span>
- <ProjectSelect
- class="!w-60 shrink-0"
- :project-name="state.projectName"
- @update:project-name="handleProjectSelect"
- />
- </div>
- <div
- class="w-full flex flex-col gap-y-2 lg:flex-row justify-start items-start lg:items-center"
- >
- <span class="flex w-40 items-center shrink-0 text-sm">
- {{ $t("common.database") }}
- </span>
- <EnvironmentSelect
- class="!w-60 mr-3 shrink-0"
- name="environment"
- :environment-name="state.environmentName"
- @update:environment-name="handleEnvironmentSelect"
- />
- <DatabaseSelect
- class="!w-128 max-w-full"
- :database-name="state.databaseName"
- :environment-name="state.environmentName"
- :project-name="state.projectName"
- :placeholder="$t('db.select')"
- :allowed-engine-type-list="allowedEngineTypeList"
- :fallback-option="false"
- @update:database-name="handleDatabaseSelect"
- />
- </div>
- <div
- class="w-full flex flex-col gap-y-2 lg:flex-row justify-start items-start lg:items-center"
- >
- <span class="flex w-40 items-center shrink-0 text-sm">
- {{ $t("database.sync-schema.schema-version.self") }}
- </span>
- <div
- class="w-192 max-w-full flex flex-row justify-start items-center relative"
- >
- <NSelect
- :loading="isPreparingSchemaVersionOptions"
- :value="state.changeHistoryName"
- :options="schemaVersionOptions"
- :placeholder="$t('change-history.select')"
- :disabled="
- !isValidProjectName(state.projectName) ||
- schemaVersionOptions.length === 0
- "
- :render-label="renderSchemaVersionLabel"
- :fallback-option="
- isMockLatestSchemaChangeHistorySelected
- ? fallbackSchemaVersionOption
- : false
- "
- @update:value="handleSchemaVersionSelect"
- />
- </div>
- </div>
- </div>
-
- <FeatureModal
- feature="bb.feature.sync-schema-all-versions"
- :open="state.showFeatureModal"
- :instance="database?.instanceResource"
- @cancel="state.showFeatureModal = false"
- />
-</template>
-
-<script lang="tsx" setup>
-import { computedAsync } from "@vueuse/core";
-import { head } from "lodash-es";
-import type { SelectOption } from "naive-ui";
-import { NEllipsis, NSelect, NTag } from "naive-ui";
-import { computed, reactive, ref, watch } from "vue";
-import type { VNodeArrayChildren } from "vue";
-import { useI18n } from "vue-i18n";
-import {
- EnvironmentSelect,
- ProjectSelect,
- DatabaseSelect,
-} from "@/components/v2";
-import {
- useChangeHistoryStore,
- useDatabaseV1Store,
- useSubscriptionV1Store,
- useDBSchemaV1Store,
-} from "@/store";
-import {
- UNKNOWN_ID,
- getDateForPbTimestamp,
- isValidDatabaseName,
- isValidProjectName,
-} from "@/types";
-import { Engine } from "@/types/proto/v1/common";
-import type { ChangeHistory } from "@/types/proto/v1/database_service";
-import {
- ChangeHistoryView,
- ChangeHistory_Type,
- DatabaseMetadataView,
- changeHistory_TypeToJSON,
-} from "@/types/proto/v1/database_service";
-import {
- extractChangeHistoryUID,
- instanceV1SupportsConciseSchema,
- mockLatestSchemaChangeHistory,
-} from "@/utils";
-import { FeatureModal } from "../FeatureGuard";
-import FeatureBadge from "../FeatureGuard/FeatureBadge.vue";
-import HumanizeDate from "../misc/HumanizeDate.vue";
-import type { ChangeHistorySourceSchema } from "./types";
-
-const props = defineProps<{
- selectState?: ChangeHistorySourceSchema;
- disableProjectSelect?: boolean;
-}>();
-
-const emit = defineEmits<{
- (event: "update", state: ChangeHistorySourceSchema): void;
-}>();
-
-interface LocalState {
- showFeatureModal: boolean;
- projectName?: string;
- environmentName?: string;
- databaseName?: string;
- changeHistoryName?: string;
-}
-
-const state = reactive<LocalState>({
- showFeatureModal: false,
- projectName: props.selectState?.projectName,
- environmentName: props.selectState?.environmentName,
- databaseName: props.selectState?.databaseName,
- changeHistoryName: props.selectState?.changeHistory?.name,
-});
-const { t } = useI18n();
-const databaseStore = useDatabaseV1Store();
-const dbSchemaStore = useDBSchemaV1Store();
-const changeHistoryStore = useChangeHistoryStore();
-
-const database = computed(() => {
- return isValidDatabaseName(state.databaseName)
- ? databaseStore.getDatabaseByName(state.databaseName)
- : undefined;
-});
-
-const isPreparingSchemaVersionOptions = ref(false);
-const isFetchingChangeHistorySourceSchema = ref(false);
-
-const hasSyncSchemaFeature = computed(() => {
- return useSubscriptionV1Store().hasInstanceFeature(
- "bb.feature.sync-schema-all-versions",
- database.value?.instanceResource
- );
-});
-
-const allowedMigrationTypeList: ChangeHistory_Type[] = [
- ChangeHistory_Type.BASELINE,
- ChangeHistory_Type.MIGRATE,
-];
-
-const allowedEngineTypeList: Engine[] = [
- Engine.MYSQL,
- Engine.POSTGRES,
- Engine.TIDB,
- Engine.ORACLE,
- Engine.MSSQL,
-];
-
-const handleProjectSelect = async (name: string | undefined) => {
- if (name !== state.projectName) {
- state.databaseName = undefined;
- }
- state.projectName = name;
-};
-
-const handleEnvironmentSelect = async (name: string | undefined) => {
- if (name !== state.environmentName) {
- state.databaseName = undefined;
- }
- state.environmentName = name;
-};
-
-const handleDatabaseSelect = async (name: string | undefined) => {
- if (isValidDatabaseName(name)) {
- const database = databaseStore.getDatabaseByName(name);
- if (!database) {
- return;
- }
- state.projectName = database.project;
- state.environmentName = database.effectiveEnvironment;
- state.databaseName = name;
- dbSchemaStore.getOrFetchDatabaseMetadata({
- database: database.name,
- view: DatabaseMetadataView.DATABASE_METADATA_VIEW_FULL,
- });
- }
-};
-
-const databaseChangeHistoryList = (databaseName: string) => {
- const database = databaseStore.getDatabaseByName(databaseName);
- const list = changeHistoryStore
- .changeHistoryListByDatabase(database.name)
- .filter((changeHistory) =>
- allowedMigrationTypeList.includes(changeHistory.type)
- );
-
- return list;
-};
-
-const schemaVersionOptions = computed(() => {
- const { databaseName } = state;
- if (!isValidDatabaseName(databaseName)) {
- return [];
- }
- const changeHistories = databaseChangeHistoryList(databaseName);
- if (changeHistories.length === 0) return [];
- const options: SelectOption[] = [
- {
- value: "PLACEHOLDER",
- label: t("change-history.select"),
- disabled: true,
- style: "cursor: default",
- },
- ];
- options.push(
- ...changeHistories.map<SelectOption>((changeHistory, index) => {
- return {
- changeHistory,
- index,
- value: changeHistory.name,
- label: changeHistory.name,
- class: "bb-schema-version-select-option",
- };
- })
- );
- return options;
-});
-const renderSchemaVersionLabel = (option: SelectOption) => {
- if (
- option.value === "PLACEHOLDER" ||
- option.disabled ||
- !option.changeHistory
- ) {
- return option.label as string;
- }
- const changeHistory = option.changeHistory as ChangeHistory;
- const index = option.index as number;
- const children: VNodeArrayChildren = [];
- if (index > 0) {
- children.push(
- <FeatureBadge
- feature="bb.feature.sync-schema-all-versions"
- customClass="mr-1"
- instance={database.value?.instanceResource}
- />
- );
- }
- if (changeHistory.type !== ChangeHistory_Type.TYPE_UNSPECIFIED) {
- children.push(
- <NTag class="mr-1" round size="small">
- {changeHistory_TypeToJSON(changeHistory.type)}
- </NTag>
- );
- }
- children.push(
- <NEllipsis class="flex-1 pr-2" tooltip={false}>
- {changeHistory.version}
- </NEllipsis>
- );
- if (changeHistory.createTime) {
- children.push(
- <HumanizeDate
- class="text-control-light"
- date={getDateForPbTimestamp(changeHistory.createTime)}
- />
- );
- }
- return <div class="w-full flex justify-between">{...children}</div>;
-};
-const isMockLatestSchemaChangeHistorySelected = computed(() => {
- if (!state.changeHistoryName) return false;
- return (
- extractChangeHistoryUID(state.changeHistoryName) === String(UNKNOWN_ID)
- );
-});
-const fallbackSchemaVersionOption = (value: string): SelectOption => {
- if (extractChangeHistoryUID(value) === String(UNKNOWN_ID)) {
- const { databaseName } = state;
- if (isValidDatabaseName(databaseName)) {
- const db = databaseStore.getDatabaseByName(databaseName);
- const changeHistory = mockLatestSchemaChangeHistory(db);
- return {
- changeHistory,
- index: 0,
- value: changeHistory.name,
- label: changeHistory.name,
- };
- }
- }
- return {
- value: "PLACEHOLDER",
- disabled: true,
- label: t("change-history.select"),
- style: "cursor: default",
- };
-};
-
-const handleSchemaVersionSelect = async (
- name: string,
- option: SelectOption
-) => {
- const changeHistory = option.changeHistory as ChangeHistory;
- const index = databaseChangeHistoryList(
- state.databaseName as string
- ).findIndex((history) => history.name === changeHistory.name);
- if (index > 0 && !hasSyncSchemaFeature.value) {
- state.showFeatureModal = true;
- return;
- }
- state.changeHistoryName = changeHistory.name;
-};
-
-const mergedChangeHistorySourceSchema = computedAsync(
- async (): Promise<
- | Pick<ChangeHistorySourceSchema, "changeHistory" | "conciseHistory">
- | undefined
- > => {
- const { databaseName, changeHistoryName } = state;
- if (!isValidDatabaseName(databaseName)) {
- return undefined;
- }
- if (!changeHistoryName) {
- return undefined;
- }
-
- const database = databaseStore.getDatabaseByName(databaseName);
- if (database) {
- if (isMockLatestSchemaChangeHistorySelected.value) {
- // If database has no migration history, we will use its latest schema.
- const schema = await databaseStore.fetchDatabaseSchema(
- `${database.name}/schema`
- );
- const changeHistory = mockLatestSchemaChangeHistory(database, schema);
- if (instanceV1SupportsConciseSchema(database.instanceResource)) {
- const conciseSchema = await databaseStore.fetchDatabaseSchema(
- `${database.name}/schema`,
- /* sdlFormat */ false,
- /* concise */ instanceV1SupportsConciseSchema(
- database.instanceResource
- )
- );
- const conciseHistory = conciseSchema.schema;
- return {
- changeHistory,
- conciseHistory,
- };
- } else {
- return {
- changeHistory,
- };
- }
- } else {
- // Fetch the FULL view of changeHistory
- const changeHistory = await changeHistoryStore.fetchChangeHistory({
- name: changeHistoryName,
- view: ChangeHistoryView.CHANGE_HISTORY_VIEW_FULL,
- });
-
- if (instanceV1SupportsConciseSchema(database.instanceResource)) {
- const conciseHistory = await changeHistoryStore.fetchChangeHistory({
- name: changeHistoryName,
- view: ChangeHistoryView.CHANGE_HISTORY_VIEW_FULL,
- concise: true,
- });
- return {
- changeHistory,
- conciseHistory: conciseHistory.schema,
- };
- } else {
- return {
- changeHistory,
- };
- }
- }
- } else {
- return undefined;
- }
- },
- undefined,
- { evaluating: isFetchingChangeHistorySourceSchema }
-);
-
-watch(
- () => state.databaseName,
- async (databaseName) => {
- if (!isValidDatabaseName(databaseName)) {
- state.changeHistoryName = undefined;
- return;
- }
-
- const database = databaseStore.getDatabaseByName(databaseName);
- if (database) {
- try {
- isPreparingSchemaVersionOptions.value = true;
- const changeHistoryList = (
- await changeHistoryStore.getOrFetchChangeHistoryListOfDatabase(
- database.name
- )
- ).filter((changeHistory) =>
- allowedMigrationTypeList.includes(changeHistory.type)
- );
-
- if (!state.changeHistoryName) {
- if (changeHistoryList.length > 0) {
- // Default select the first migration history.
- state.changeHistoryName = head(changeHistoryList)?.name;
- } else {
- // If database has no migration history, we will use its latest schema.
- state.changeHistoryName = mockLatestSchemaChangeHistory(
- database,
- undefined
- ).name;
- }
- }
- } finally {
- isPreparingSchemaVersionOptions.value = false;
- }
- } else {
- state.changeHistoryName = undefined;
- }
- },
- { immediate: true }
-);
-
-watch(
- [
- () => state.projectName,
- () => state.environmentName,
- () => state.databaseName,
- mergedChangeHistorySourceSchema,
- isFetchingChangeHistorySourceSchema,
- ],
- ([projectName, environmentName, databaseName, source, isFetching]) => {
- const params: ChangeHistorySourceSchema = {
- projectName,
- environmentName,
- databaseName,
- changeHistory: source?.changeHistory,
- conciseHistory: source?.conciseHistory,
- isFetching,
- };
- emit("update", params);
- },
- {
- immediate: false,
- }
-);
-
-watch(
- [
- () => props.selectState?.projectName,
- () => props.selectState?.environmentName,
- () => props.selectState?.databaseName,
- () => props.selectState?.changeHistory?.name,
- () => props.selectState?.isFetching,
- ],
- ([
- projectName,
- environmentName,
- databaseName,
- changeHistoryName,
- isFetching,
- ]) => {
- if (isFetching) return;
- state.projectName = projectName;
- state.environmentName = environmentName;
- state.databaseName = databaseName;
- state.changeHistoryName = changeHistoryName;
- },
- {
- immediate: false,
- }
-);
-</script>
-
-<style lang="postcss">
-.bb-schema-version-select-option .n-base-select-option__content {
- @apply w-full;
-}
-</style>
diff --git a/frontend/src/components/SyncDatabaseSchema/RawSQLEditor.vue b/frontend/src/components/SyncDatabaseSchema/RawSQLEditor.vue
deleted file mode 100644
index 2846f6fc74..0000000000
--- a/frontend/src/components/SyncDatabaseSchema/RawSQLEditor.vue
+++ /dev/null
@@ -1,218 +0,0 @@
-<template>
- <div class="w-full h-auto flex flex-col justify-start items-start">
- <div class="w-full h-auto shrink-0 flex flex-row justify-between items-end">
- <div class="flex flex-col justify-start items-start gap-y-2">
- <div
- v-if="!disableProjectSelect"
- class="flex flex-row justify-start items-center"
- >
- <span class="mr-2 w-20 shrink-0 text-sm">{{
- $t("common.project")
- }}</span>
- <ProjectSelect
- :project-name="state.projectName"
- :disabled="viewMode"
- @update:project-name="handleProjectSelect"
- />
- </div>
- <div class="flex flex-row justify-start items-center">
- <span class="mr-2 w-20 shrink-0 text-sm">{{
- $t("database.engine")
- }}</span>
- <NSelect
- v-model:value="state.engine"
- :disabled="viewMode"
- :consistent-menu-width="false"
- :options="engineSelectorOptions"
- @update:value="handleEngineChange"
- />
- </div>
- </div>
- <div
- v-if="!viewMode"
- class="flex flex-row justify-end items-center space-x-3"
- >
- <SQLUploadButton
- :loading="state.isUploadingFile"
- @update:sql="handleSQLUpload"
- >
- {{ $t("issue.upload-sql") }}
- </SQLUploadButton>
- </div>
- </div>
- <BBAttention
- v-if="isSheetOversized && !viewMode"
- class="my-2"
- type="warning"
- :title="$t('issue.statement-from-sheet-warning')"
- >
- <template v-if="sheet?.name" #action>
- <DownloadSheetButton :sheet="sheet.name" size="small" />
- </template>
- </BBAttention>
- <div class="mt-4 w-full h-96 overflow-hidden">
- <MonacoEditor
- class="w-full h-full border"
- :content="state.editStatement"
- :auto-focus="true"
- :readonly="viewMode"
- :dialect="dialectOfEngineV1(state.engine)"
- @update:content="handleStatementChange"
- />
- </div>
- </div>
-</template>
-
-<script lang="ts" setup>
-import { useDebounceFn } from "@vueuse/core";
-import { NSelect } from "naive-ui";
-import { computed, onMounted, nextTick, reactive } from "vue";
-import { BBAttention } from "@/bbkit";
-import { MonacoEditor } from "@/components/MonacoEditor";
-import DownloadSheetButton from "@/components/Sheet/DownloadSheetButton.vue";
-import SQLUploadButton from "@/components/misc/SQLUploadButton.vue";
-import { ProjectSelect } from "@/components/v2";
-import { useSheetV1Store } from "@/store";
-import {
- DEFAULT_PROJECT_NAME,
- UNKNOWN_ID,
- dialectOfEngineV1,
- isValidProjectName,
-} from "@/types";
-import { Engine } from "@/types/proto/v1/common";
-import {
- engineNameV1,
- extractSheetUID,
- getStatementSize,
- getSheetStatement,
-} from "@/utils";
-import type { RawSQLState } from "./types";
-
-interface LocalState {
- projectName?: string;
- engine: Engine;
- editStatement: string;
- isUploadingFile: boolean;
-}
-
-const props = defineProps<{
- projectName?: string;
- engine: Engine;
- statement?: string;
- sheetId?: number;
- viewMode?: boolean;
- disableProjectSelect?: boolean;
-}>();
-
-const emit = defineEmits<{
- (event: "update", rawSQLState: RawSQLState): void;
-}>();
-
-const sheetStore = useSheetV1Store();
-const state = reactive<LocalState>({
- projectName: props.projectName,
- engine: props.engine || Engine.MYSQL,
- editStatement: props.statement || "",
- isUploadingFile: false,
-});
-
-const availableEngines = computed(() => {
- return [Engine.MYSQL, Engine.POSTGRES];
-});
-
-const engineSelectorOptions = computed(() => {
- return availableEngines.value.map((engine) => {
- return {
- label: engineNameV1(engine),
- value: engine,
- };
- });
-});
-
-const sheet = computed(() => {
- return sheetStore.getSheetByUID(String(props.sheetId || UNKNOWN_ID), "FULL");
-});
-
-const isSheetOversized = computed(() => {
- if (!sheet.value) {
- return false;
- }
- return getStatementSize(getSheetStatement(sheet.value)).lt(
- sheet.value.contentSize
- );
-});
-
-onMounted(async () => {
- if (props.sheetId) {
- const sheet = await sheetStore.getOrFetchSheetByUID(
- String(props.sheetId),
- "FULL"
- );
- if (sheet) {
- const statement = new TextDecoder().decode(sheet.content);
- state.editStatement = statement;
- }
- }
-});
-
-const handleProjectSelect = (name: string | undefined) => {
- if (!isValidProjectName(name)) return;
- state.projectName = name;
- update();
-};
-
-const handleEngineChange = () => {
- nextTick(() => {
- update();
- });
-};
-
-const handleSQLUpload = async (statement: string, filename: string) => {
- if (state.isUploadingFile) {
- return;
- }
-
- state.isUploadingFile = true;
- try {
- const sheet = await sheetStore.createSheet(DEFAULT_PROJECT_NAME, {
- title: filename,
- engine: state.engine,
- content: new TextEncoder().encode(statement),
- });
- const sheetId = Number(extractSheetUID(sheet.name));
- await handleStatementChange(statement);
- update(sheetId);
- } finally {
- state.isUploadingFile = false;
- }
-};
-
-const handleStatementChange = (statement: string) => {
- state.editStatement = statement;
- handleUpdateSheet(statement);
- update();
-};
-
-const handleUpdateSheet = useDebounceFn(async (statement: string) => {
- if (!sheet.value) {
- return;
- }
-
- await sheetStore.patchSheetContent({
- name: sheet.value.name,
- content: new TextEncoder().encode(statement),
- });
-}, 1000);
-
-const update = (sheetId?: number) => {
- if (sheet.value) {
- sheetId = Number(extractSheetUID(sheet.value.name));
- }
- emit("update", {
- projectName: state.projectName,
- engine: state.engine,
- statement: state.editStatement,
- sheetId: sheetId,
- });
-};
-</script>
diff --git a/frontend/src/components/SyncDatabaseSchema/RawSQLEditorPanel.vue b/frontend/src/components/SyncDatabaseSchema/RawSQLEditorPanel.vue
deleted file mode 100644
index bfda1e78d3..0000000000
--- a/frontend/src/components/SyncDatabaseSchema/RawSQLEditorPanel.vue
+++ /dev/null
@@ -1,48 +0,0 @@
-<template>
- <Drawer
- :show="true"
- width="auto"
- @update:show="(show: boolean) => !show && emit('dismiss')"
- >
- <DrawerContent
- :title="$t('schema-designer.quick-action')"
- :closable="true"
- class="w-192"
- >
- <RawSQLEditor
- :view-mode="true"
- :project-name="rawSqlState.projectName"
- :engine="rawSqlState.engine"
- :statement="rawSqlState.statement"
- :sheet-id="rawSqlState.sheetId"
- />
-
- <template #footer>
- <div class="flex-1 flex items-center justify-between">
- <div></div>
-
- <div class="flex items-center justify-end gap-x-3">
- <NButton @click.prevent="emit('dismiss')">
- {{ $t("common.close") }}
- </NButton>
- </div>
- </div>
- </template>
- </DrawerContent>
- </Drawer>
-</template>
-
-<script lang="ts" setup>
-import { NButton } from "naive-ui";
-import { Drawer, DrawerContent } from "@/components/v2";
-import RawSQLEditor from "./RawSQLEditor.vue";
-import type { RawSQLState } from "./types";
-
-defineProps<{
- rawSqlState: RawSQLState;
-}>();
-
-const emit = defineEmits<{
- (event: "dismiss"): void;
-}>();
-</script>
diff --git a/frontend/src/components/SyncDatabaseSchema/types.ts b/frontend/src/components/SyncDatabaseSchema/types.ts
deleted file mode 100644
index 48de624873..0000000000
--- a/frontend/src/components/SyncDatabaseSchema/types.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import type { Engine } from "@/types/proto/v1/common";
-import type { ChangeHistory } from "@/types/proto/v1/database_service";
-
-export type SourceSchemaType = "SCHEMA_HISTORY_VERSION" | "RAW_SQL";
-
-export interface ChangeHistorySourceSchema {
- projectName?: string;
- environmentName?: string;
- databaseName?: string;
- changeHistory?: ChangeHistory;
- conciseHistory?: string;
- isFetching?: boolean;
-}
-
-export interface RawSQLState {
- projectName?: string;
- engine: Engine;
- statement: string;
- sheetId?: number;
-}
diff --git a/frontend/src/components/SyncDatabaseSchemaV1/DatabaseSchemaSelector.vue b/frontend/src/components/SyncDatabaseSchemaV1/DatabaseSchemaSelector.vue
new file mode 100644
index 0000000000..52b3fab144
--- /dev/null
+++ b/frontend/src/components/SyncDatabaseSchemaV1/DatabaseSchemaSelector.vue
@@ -0,0 +1,343 @@
+<template>
+ <div
+ class="w-full mx-auto flex flex-col justify-start items-start space-y-3 mb-6"
+ >
+ <div
+ class="w-full flex flex-col gap-y-2 lg:flex-row justify-start items-start lg:items-center"
+ >
+ <span class="flex w-40 items-center shrink-0 text-sm">
+ {{ $t("common.database") }}
+ </span>
+ <EnvironmentSelect
+ class="!w-60 mr-3 shrink-0"
+ name="environment"
+ :environment-name="state.environmentName"
+ @update:environment-name="handleEnvironmentSelect"
+ />
+ <DatabaseSelect
+ class="!w-128 max-w-full"
+ :project-name="project.name"
+ :database-name="state.databaseName"
+ :environment-name="state.environmentName"
+ :placeholder="$t('db.select')"
+ :allowed-engine-type-list="ALLOWED_ENGINES"
+ :fallback-option="false"
+ @update:database-name="handleDatabaseSelect"
+ />
+ </div>
+ <div
+ class="w-full flex flex-col gap-y-2 lg:flex-row justify-start items-start lg:items-center"
+ >
+ <span class="flex w-40 items-center shrink-0 text-sm">
+ {{ $t("database.sync-schema.schema-version.self") }}
+ </span>
+ <div
+ class="w-192 max-w-full flex flex-row justify-start items-center relative"
+ >
+ <NSelect
+ :loading="isPreparingSchemaVersionOptions"
+ :value="state.changelogName"
+ :options="schemaVersionOptions"
+ :placeholder="$t('change-history.select')"
+ :disabled="schemaVersionOptions.length === 0"
+ :render-label="renderSchemaVersionLabel"
+ :fallback-option="
+ isMockLatestSchemaChangelogSelected
+ ? fallbackSchemaVersionOption
+ : false
+ "
+ @update:value="handleSchemaVersionSelect"
+ />
+ </div>
+ </div>
+ </div>
+
+ <FeatureModal
+ feature="bb.feature.sync-schema-all-versions"
+ :open="state.showFeatureModal"
+ :instance="database?.instanceResource"
+ @cancel="state.showFeatureModal = false"
+ />
+</template>
+
+<script lang="tsx" setup>
+import { head } from "lodash-es";
+import type { SelectOption } from "naive-ui";
+import { NSelect, NTag } from "naive-ui";
+import { computed, reactive, ref, watch } from "vue";
+import { useI18n } from "vue-i18n";
+import { EnvironmentSelect, DatabaseSelect } from "@/components/v2";
+import {
+ useDatabaseV1Store,
+ useSubscriptionV1Store,
+ useDBSchemaV1Store,
+ useChangelogStore,
+} from "@/store";
+import {
+ UNKNOWN_ID,
+ getDateForPbTimestamp,
+ isValidDatabaseName,
+ type ComposedProject,
+} from "@/types";
+import type { Changelog } from "@/types/proto/v1/database_service";
+import {
+ Changelog_Type,
+ DatabaseMetadataView,
+ changelog_TypeToJSON,
+} from "@/types/proto/v1/database_service";
+import {
+ extractChangelogUID,
+ isValidChangelogName,
+ mockLatestChangelog,
+} from "@/utils/v1/changelog";
+import { FeatureModal } from "../FeatureGuard";
+import FeatureBadge from "../FeatureGuard/FeatureBadge.vue";
+import HumanizeDate from "../misc/HumanizeDate.vue";
+import { ALLOWED_ENGINES, type ChangelogSourceSchema } from "./types";
+
+const ALLOWED_CHANGELOG_TYPES: Changelog_Type[] = [
+ Changelog_Type.BASELINE,
+ Changelog_Type.MIGRATE,
+];
+
+const props = defineProps<{
+ project: ComposedProject;
+ sourceSchema?: ChangelogSourceSchema;
+}>();
+
+const emit = defineEmits<{
+ (event: "update", sourceSchema: ChangelogSourceSchema): void;
+}>();
+
+interface LocalState {
+ showFeatureModal: boolean;
+ environmentName?: string;
+ databaseName?: string;
+ changelogName?: string;
+}
+
+const { t } = useI18n();
+const state = reactive<LocalState>({
+ showFeatureModal: false,
+ environmentName: props.sourceSchema?.environmentName,
+ databaseName: props.sourceSchema?.databaseName,
+ changelogName: props.sourceSchema?.changelogName,
+});
+const databaseStore = useDatabaseV1Store();
+const dbSchemaStore = useDBSchemaV1Store();
+const changelogStore = useChangelogStore();
+
+const database = computed(() => {
+ return isValidDatabaseName(state.databaseName)
+ ? databaseStore.getDatabaseByName(state.databaseName)
+ : undefined;
+});
+
+const isPreparingSchemaVersionOptions = ref(false);
+
+const hasSyncSchemaFeature = computed(() => {
+ return useSubscriptionV1Store().hasInstanceFeature(
+ "bb.feature.sync-schema-all-versions",
+ database.value?.instanceResource
+ );
+});
+
+const handleEnvironmentSelect = async (name: string | undefined) => {
+ if (name !== state.environmentName) {
+ state.databaseName = undefined;
+ }
+ state.environmentName = name;
+};
+
+const handleDatabaseSelect = async (name: string | undefined) => {
+ if (isValidDatabaseName(name)) {
+ const database = databaseStore.getDatabaseByName(name);
+ if (!database) {
+ return;
+ }
+ state.environmentName = database.effectiveEnvironment;
+ state.databaseName = name;
+ dbSchemaStore.getOrFetchDatabaseMetadata({
+ database: database.name,
+ view: DatabaseMetadataView.DATABASE_METADATA_VIEW_FULL,
+ });
+ } else {
+ state.databaseName = undefined;
+ }
+};
+
+const databaseChangelogList = (databaseName: string) => {
+ return changelogStore
+ .changelogListByDatabase(databaseName)
+ .filter((changelog) => ALLOWED_CHANGELOG_TYPES.includes(changelog.type));
+};
+
+const schemaVersionOptions = computed(() => {
+ const { databaseName } = state;
+ if (!isValidDatabaseName(databaseName)) {
+ return [];
+ }
+ const changelogs = databaseChangelogList(databaseName);
+ if (changelogs.length === 0) return [];
+ const options: SelectOption[] = [
+ {
+ value: "PLACEHOLDER",
+ label: t("change-history.select"),
+ disabled: true,
+ style: "cursor: default",
+ },
+ ];
+ options.push(
+ ...changelogs.map<SelectOption>((changelog, index) => {
+ return {
+ changelog,
+ index,
+ value: changelog.name,
+ label: changelog.name,
+ };
+ })
+ );
+ return options;
+});
+
+const renderSchemaVersionLabel = (option: SelectOption) => {
+ if (option.disabled || !option.changelog) {
+ return option.label as string;
+ }
+ const changelog = option.changelog as Changelog;
+ if (!isValidChangelogName(changelog.name)) {
+ return "Latest version";
+ }
+
+ const index = option.index as number;
+ return (
+ <div class="w-full flex flex-row justify-start items-center truncate">
+ {index > 0 && (
+ <FeatureBadge
+ feature="bb.feature.sync-schema-all-versions"
+ customClass="mr-1"
+ instance={database.value?.instanceResource}
+ />
+ )}
+ <HumanizeDate
+ class="text-control-light mr-1"
+ date={getDateForPbTimestamp(changelog.createTime)}
+ />
+ <NTag class="mr-1" round size="small">
+ {changelog_TypeToJSON(changelog.type)}
+ </NTag>
+ {changelog.version && (
+ <NTag class="mr-1" round size="small">
+ {changelog.version}
+ </NTag>
+ )}
+ <span class="truncate">{changelog.statement}</span>
+ </div>
+ );
+};
+
+const isMockLatestSchemaChangelogSelected = computed(() => {
+ if (!state.changelogName) return false;
+ return extractChangelogUID(state.changelogName) === String(UNKNOWN_ID);
+});
+
+const fallbackSchemaVersionOption = (value: string): SelectOption => {
+ if (extractChangelogUID(value) === String(UNKNOWN_ID)) {
+ const { databaseName } = state;
+ if (isValidDatabaseName(databaseName)) {
+ const db = databaseStore.getDatabaseByName(databaseName);
+ const changelog = mockLatestChangelog(db);
+ return {
+ changelog,
+ index: 0,
+ value: changelog.name,
+ label: changelog.name,
+ };
+ }
+ }
+ return {
+ value: "PLACEHOLDER",
+ disabled: true,
+ label: t("change-history.select"),
+ style: "cursor: default",
+ };
+};
+
+const handleSchemaVersionSelect = async (_: string, option: SelectOption) => {
+ const changelog = option.changelog as Changelog;
+ const index = databaseChangelogList(state.databaseName as string).findIndex(
+ (c) => c.name === changelog.name
+ );
+ if (index > 0 && !hasSyncSchemaFeature.value) {
+ state.showFeatureModal = true;
+ return;
+ }
+ state.changelogName = changelog.name;
+};
+
+watch(
+ () => state.databaseName,
+ async (databaseName) => {
+ if (!isValidDatabaseName(databaseName)) {
+ state.changelogName = undefined;
+ return;
+ }
+
+ const database = databaseStore.getDatabaseByName(databaseName);
+ if (database) {
+ try {
+ isPreparingSchemaVersionOptions.value = true;
+ const changelogList = (
+ await changelogStore.getOrFetchChangelogListOfDatabase(database.name)
+ ).filter((changelog) =>
+ ALLOWED_CHANGELOG_TYPES.includes(changelog.type)
+ );
+
+ if (!state.changelogName) {
+ if (changelogList.length > 0) {
+ // Default select the first changelog.
+ state.changelogName = head(changelogList)?.name;
+ } else {
+ // If database has no changelog, we will use its latest schema.
+ state.changelogName = mockLatestChangelog(database).name;
+ }
+ }
+ } finally {
+ isPreparingSchemaVersionOptions.value = false;
+ }
+ } else {
+ state.changelogName = undefined;
+ }
+ },
+ { immediate: true }
+);
+
+watch(
+ [
+ () => state.environmentName,
+ () => state.databaseName,
+ () => state.changelogName,
+ ],
+ ([environmentName, databaseName, changelogName]) => {
+ const params: ChangelogSourceSchema = {
+ environmentName,
+ databaseName,
+ changelogName,
+ };
+ emit("update", params);
+ }
+);
+
+watch(
+ [
+ () => props.sourceSchema?.environmentName,
+ () => props.sourceSchema?.databaseName,
+ () => props.sourceSchema?.changelogName,
+ ],
+ ([environmentName, databaseName, changelogName]) => {
+ state.environmentName = environmentName;
+ state.databaseName = databaseName;
+ state.changelogName = changelogName;
+ }
+);
+</script>
diff --git a/frontend/src/components/SyncDatabaseSchema/DiffViewPanel.vue b/frontend/src/components/SyncDatabaseSchemaV1/DiffViewPanel.vue
similarity index 91%
rename from frontend/src/components/SyncDatabaseSchema/DiffViewPanel.vue
rename to frontend/src/components/SyncDatabaseSchemaV1/DiffViewPanel.vue
index 70a4cd5e3d..c477a6cf9c 100644
--- a/frontend/src/components/SyncDatabaseSchema/DiffViewPanel.vue
+++ b/frontend/src/components/SyncDatabaseSchemaV1/DiffViewPanel.vue
@@ -15,7 +15,7 @@
v-if="shouldShowDiff"
:title="previewSchemaChangeMessage"
:original="targetDatabaseSchema"
- :modified="displayOnlySourceDatabaseSchema"
+ :modified="sourceDatabaseSchema"
:show-fullscreen="true"
/>
<div
@@ -69,9 +69,6 @@ defineProps<{
engine: Engine;
targetDatabaseSchema: string;
sourceDatabaseSchema: string;
- // The source database schema that is displayed in the diff editor.
- // It's different from `sourceDatabaseSchema` when for Oracle.
- displayOnlySourceDatabaseSchema: string;
shouldShowDiff: boolean;
previewSchemaChangeMessage: string;
}>();
diff --git a/frontend/src/components/SyncDatabaseSchemaV1/RawSQLEditor.vue b/frontend/src/components/SyncDatabaseSchemaV1/RawSQLEditor.vue
new file mode 100644
index 0000000000..4dc2598b5a
--- /dev/null
+++ b/frontend/src/components/SyncDatabaseSchemaV1/RawSQLEditor.vue
@@ -0,0 +1,93 @@
+<template>
+ <div class="w-full h-auto flex flex-col justify-start items-start">
+ <div class="w-full h-auto shrink-0 flex flex-row justify-between items-end">
+ <div class="flex flex-col justify-start items-start gap-y-2">
+ <div class="flex flex-row justify-start items-center">
+ <span class="mr-2 w-20 shrink-0 text-sm">{{
+ $t("database.engine")
+ }}</span>
+ <NSelect
+ v-model:value="state.engine"
+ :consistent-menu-width="false"
+ :options="engineSelectorOptions"
+ @update:value="handleEngineChange"
+ />
+ </div>
+ </div>
+ <div class="flex flex-row justify-end items-center space-x-3">
+ <SQLUploadButton @update:sql="handleStatementChange">
+ {{ $t("issue.upload-sql") }}
+ </SQLUploadButton>
+ </div>
+ </div>
+ <div class="mt-4 w-full h-96 overflow-hidden">
+ <MonacoEditor
+ class="w-full h-full border"
+ :content="state.statement"
+ :auto-focus="true"
+ :dialect="dialectOfEngineV1(state.engine)"
+ @update:content="handleStatementChange"
+ />
+ </div>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { NSelect } from "naive-ui";
+import { computed, nextTick, reactive } from "vue";
+import { MonacoEditor } from "@/components/MonacoEditor";
+import SQLUploadButton from "@/components/misc/SQLUploadButton.vue";
+import { dialectOfEngineV1, type ComposedProject } from "@/types";
+import { Engine } from "@/types/proto/v1/common";
+import { engineNameV1 } from "@/utils";
+import { ALLOWED_ENGINES, type RawSQLState } from "./types";
+
+interface LocalState {
+ engine: Engine;
+ statement: string;
+}
+
+const props = defineProps<{
+ project: ComposedProject;
+ engine: Engine;
+ statement?: string;
+}>();
+
+const emit = defineEmits<{
+ (event: "update", rawSQLState: RawSQLState): void;
+}>();
+
+const state = reactive<LocalState>({
+ engine: props.engine || Engine.MYSQL,
+ statement: props.statement || "",
+});
+
+const engineSelectorOptions = computed(() => {
+ return ALLOWED_ENGINES.map((engine) => {
+ return {
+ label: engineNameV1(engine),
+ value: engine,
+ };
+ });
+});
+
+const handleEngineChange = () => {
+ nextTick(() => {
+ update();
+ });
+};
+
+const handleStatementChange = (statement: string) => {
+ state.statement = statement;
+ nextTick(() => {
+ update();
+ });
+};
+
+const update = () => {
+ emit("update", {
+ engine: state.engine,
+ statement: state.statement,
+ });
+};
+</script>
diff --git a/frontend/src/components/SyncDatabaseSchema/SchemaDiffViewer.vue b/frontend/src/components/SyncDatabaseSchemaV1/SchemaDiffViewer.vue
similarity index 100%
rename from frontend/src/components/SyncDatabaseSchema/SchemaDiffViewer.vue
rename to frontend/src/components/SyncDatabaseSchemaV1/SchemaDiffViewer.vue
diff --git a/frontend/src/components/SyncDatabaseSchema/SchemaDiffViewerModal.vue b/frontend/src/components/SyncDatabaseSchemaV1/SchemaDiffViewerModal.vue
similarity index 100%
rename from frontend/src/components/SyncDatabaseSchema/SchemaDiffViewerModal.vue
rename to frontend/src/components/SyncDatabaseSchemaV1/SchemaDiffViewerModal.vue
diff --git a/frontend/src/components/SyncDatabaseSchema/SelectTargetDatabasesView.vue b/frontend/src/components/SyncDatabaseSchemaV1/SelectTargetDatabasesView.vue
similarity index 50%
rename from frontend/src/components/SyncDatabaseSchema/SelectTargetDatabasesView.vue
rename to frontend/src/components/SyncDatabaseSchemaV1/SelectTargetDatabasesView.vue
index 21ff31d3f1..abea9573ee 100644
--- a/frontend/src/components/SyncDatabaseSchema/SelectTargetDatabasesView.vue
+++ b/frontend/src/components/SyncDatabaseSchemaV1/SelectTargetDatabasesView.vue
@@ -2,80 +2,6 @@
<div
class="select-target-database-view h-full overflow-y-hidden flex flex-col gap-y-4"
>
- <div class="w-full flex flex-col md:flex-row gap-y-4 md:gap-4 textlabel">
- <span class="shrink-0 textinfolabel">{{
- $t("database.sync-schema.source-schema")
- }}</span>
- <div class="flex flex-row justify-start items-center gap-x-4 flex-wrap">
- <template
- v-if="
- sourceSchemaType === 'SCHEMA_HISTORY_VERSION' &&
- databaseSourceSchema
- "
- >
- <div>
- <span>{{ $t("common.project") }} - </span>
- <a
- class="normal-link inline-flex items-center"
- :href="`/${project.name}`"
- >{{ project.title }}</a
- >
- </div>
- <div>
- <span>{{ $t("common.environment") }} - </span>
- <a
- class="normal-link inline-flex items-center"
- :href="`/${getDatabaseSourceSchemaEnvironment()!.name}`"
- >{{ getDatabaseSourceSchemaEnvironment()!.title }}</a
- >
- </div>
- <div class="flex flex-row justify-start items-center whitespace-pre">
- <span>{{ $t("common.database") }} - </span>
- <a
- class="normal-link inline-flex items-center"
- :href="databaseV1Url(getSourceDatabase()!)"
- >
- <EngineIcon custom-class="mr-1" :engine="engine" />
- {{ getSourceDatabase()!.databaseName }}
- </a>
- </div>
- <div
- v-if="
- isValidChangeHistoryName(databaseSourceSchema.changeHistory.name)
- "
- >
- <span>{{ $t("database.sync-schema.schema-version.self") }} - </span>
- <a
- class="normal-link inline-flex items-center"
- :href="changeHistoryLink(databaseSourceSchema.changeHistory)"
- >
- {{ databaseSourceSchema.changeHistory.version }}
- </a>
- </div>
- </template>
- <template v-else>
- <div>
- <span>{{ $t("common.project") }} - </span>
- <a
- class="normal-link inline-flex items-center"
- :href="`/${project.name}`"
- >{{ project.title }}</a
- >
- </div>
- <div class="flex flex-row justify-start items-center whitespace-pre">
- <span>{{ "Schema" }} - </span>
- <span
- class="normal-link inline-flex items-center"
- @click="state.showViewRawSQLPanel = true"
- >
- <EngineIcon custom-class="mr-1" :engine="engine" />
- <span>{{ $t("schema-editor.raw-sql") }}</span>
- </span>
- </div>
- </template>
- </div>
- </div>
-
<div
class="relative border rounded-lg w-full flex flex-row flex-1 overflow-hidden"
>
@@ -99,35 +25,34 @@
<heroicons-outline:plus class="w-4 h-auto" />
</button>
</div>
- <div v-if="targetDatabaseList.length > 0" class="w-full p-2">
- <div
- class="w-full grid grid-cols-2 bg-gray-100 p-0.5 gap-0.5 rounded text-sm leading-6"
+ <div v-if="targetDatabaseList.length > 0" class="w-full mt-2 px-2">
+ <NTabs
+ type="segment"
+ size="small"
+ :active-tab="Number(state.showDatabaseWithDiff)"
+ @update:value="state.showDatabaseWithDiff = $event === 1"
>
- <div
- class="w-full text-center rounded cursor-pointer select-none hover:bg-white"
- :class="state.showDatabaseWithDiff && 'bg-white shadow'"
- @click="state.showDatabaseWithDiff = true"
- >
- {{ $t("database.sync-schema.with-diff") }}
- <span class="text-gray-400"
- >({{ databaseListWithDiff.length }})</span
- >
- </div>
- <div
- class="w-full text-center rounded cursor-pointer select-none hover:bg-white"
- :class="!state.showDatabaseWithDiff && 'bg-white shadow'"
- @click="state.showDatabaseWithDiff = false"
- >
- {{ $t("database.sync-schema.no-diff") }}
- <span class="text-gray-400"
- >({{ databaseListWithoutDiff.length }})</span
- >
- </div>
- </div>
+ <NTabPane :name="1">
+ <template #tab>
+ <span>{{ $t("database.sync-schema.with-diff") }}</span>
+ <span class="text-gray-400 ml-1"
+ >({{ databaseListWithDiff.length }})</span
+ >
+ </template>
+ </NTabPane>
+ <NTabPane :name="0">
+ <template #tab>
+ {{ $t("database.sync-schema.no-diff") }}
+ <span class="text-gray-400 ml-1"
+ >({{ databaseListWithoutDiff.length }})</span
+ >
+ </template>
+ </NTabPane>
+ </NTabs>
</div>
</div>
<div
- class="w-full grow flex flex-col justify-start items-start p-2 -mt-2 gap-1"
+ class="w-full grow flex flex-col justify-start items-start px-2 gap-1"
>
<div
v-for="database of shownDatabaseList"
@@ -185,13 +110,12 @@
v-show="selectedDatabase"
:statement="
state.selectedDatabaseName
- ? (databaseDiffCache[state.selectedDatabaseName]?.edited ?? '')
+ ? (schemaDiffCache[state.selectedDatabaseName]?.edited ?? '')
: ''
"
- :engine="engine"
- :target-database-schema="targetDatabaseSchema"
- :source-database-schema="sourceDatabaseSchema"
- :display-only-source-database-schema="displayOnlySourceDatabaseSchema"
+ :engine="sourceEngine"
+ :target-database-schema="targetSchemaDisplayString"
+ :source-database-schema="sourceSchemaDisplayString"
:should-show-diff="shouldShowDiff"
:preview-schema-change-message="previewSchemaChangeMessage"
@statement-change="onStatementChange"
@@ -218,169 +142,108 @@
<TargetDatabasesSelectPanel
v-if="state.showSelectDatabasePanel"
- :project="projectName"
- :engine="engine"
+ :project="project.name"
+ :engine="sourceEngine"
:selected-database-name-list="state.selectedDatabaseNameList"
@close="state.showSelectDatabasePanel = false"
@update="handleSelectedDatabaseNameListChanged"
/>
-
- <RawSQLEditorPanel
- v-if="state.showViewRawSQLPanel && rawSqlState"
- :raw-sql-state="rawSqlState"
- :view-mode="true"
- @dismiss="state.showViewRawSQLPanel = false"
- />
</template>
<script lang="ts" setup>
import { head } from "lodash-es";
-import { NEllipsis } from "naive-ui";
+import { NEllipsis, NTabs, NTabPane } from "naive-ui";
import { computed, nextTick, onMounted, reactive, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
+import { useRoute } from "vue-router";
import { BBSpin } from "@/bbkit";
import { InstanceV1EngineIcon } from "@/components/v2";
+import { databaseServiceClient } from "@/grpcweb";
import {
pushNotification,
useDatabaseV1Store,
useEnvironmentV1Store,
- useProjectV1Store,
- useSheetV1Store,
} from "@/store";
-import type { ComposedDatabase } from "@/types";
+import {
+ isValidDatabaseName,
+ type ComposedDatabase,
+ type ComposedProject,
+} from "@/types";
import { Engine } from "@/types/proto/v1/common";
-import type { ChangeHistory } from "@/types/proto/v1/database_service";
+import { ChangelogView } from "@/types/proto/v1/database_service";
+import { instanceV1SupportsConciseSchema, toClipboard } from "@/utils";
import {
- changeHistoryLink,
- databaseV1Url,
- getSheetStatement,
- instanceV1SupportsConciseSchema,
- isValidChangeHistoryName,
- toClipboard,
-} from "@/utils";
-import { EngineIcon } from "../Icon";
+ extractDatabaseNameAndChangelogUID,
+ isValidChangelogName,
+} from "@/utils/v1/changelog";
import DiffViewPanel from "./DiffViewPanel.vue";
-import RawSQLEditorPanel from "./RawSQLEditorPanel.vue";
import TargetDatabasesSelectPanel from "./TargetDatabasesSelectPanel.vue";
-import type { RawSQLState, SourceSchemaType } from "./types";
-
-interface DatabaseSourceSchema {
- environmentName: string;
- databaseName: string;
- changeHistory: ChangeHistory;
- conciseHistory?: string;
-}
interface LocalState {
isLoading: boolean;
showDatabaseWithDiff: boolean;
- selectedDatabaseName: string | undefined;
- selectedDatabaseNameList: string[];
showSelectDatabasePanel: boolean;
- showViewRawSQLPanel: boolean;
+ selectedDatabaseNameList: string[];
+ // The current selected target database name.
+ selectedDatabaseName?: string;
}
const props = defineProps<{
- projectName: string;
- sourceSchemaType: SourceSchemaType;
- databaseSourceSchema?: DatabaseSourceSchema;
- rawSqlState?: RawSQLState;
- targetDatabaseNameList?: string[];
+ project: ComposedProject;
+ sourceSchemaString: string;
+ sourceEngine: Engine;
+ sourceChangelogName?: string;
}>();
const { t } = useI18n();
+const route = useRoute();
const environmentV1Store = useEnvironmentV1Store();
const databaseStore = useDatabaseV1Store();
-const sheetStore = useSheetV1Store();
const diffViewerRef = ref<HTMLDivElement>();
const state = reactive<LocalState>({
- isLoading: true,
+ isLoading: false,
showDatabaseWithDiff: true,
showSelectDatabasePanel: false,
- selectedDatabaseName: undefined,
selectedDatabaseNameList: [],
- showViewRawSQLPanel: false,
});
-const databaseSchemaCache = reactive<Record<string, string>>({});
-const conciseSchemaCache = reactive<Record<string, string>>({});
-const databaseDiffCache = reactive<
+const databaseSchemaCache = ref<Record<string, string>>({});
+const schemaDiffCache = ref<
Record<
- string,
+ string, // The database name.
{
raw: string;
edited: string;
}
>
>({});
-const project = computed(() => {
- return useProjectV1Store().getProjectByName(props.projectName);
-});
-const displayOnlySourceDatabaseSchema = computed(() => {
- if (props.sourceSchemaType === "SCHEMA_HISTORY_VERSION") {
- if (instanceV1SupportsConciseSchema(engine.value)) {
- return props.databaseSourceSchema?.conciseHistory || "";
- }
- }
- return sourceDatabaseSchema.value;
-});
+const sourceSchemaDisplayString = ref<string>(props.sourceSchemaString);
-const sourceDatabaseSchema = computed(() => {
- if (props.sourceSchemaType === "SCHEMA_HISTORY_VERSION") {
- return props.databaseSourceSchema?.changeHistory.schema || "";
- } else if (props.sourceSchemaType === "RAW_SQL") {
- let statement = props.rawSqlState?.statement || "";
- if (props.rawSqlState?.sheetId) {
- const sheet = sheetStore.getSheetByUID(
- String(props.rawSqlState.sheetId),
- "FULL"
- );
- if (sheet) {
- statement = getSheetStatement(sheet);
- }
- }
- return statement;
- } else {
- return "";
- }
-});
-const engine = computed(() => {
- if (props.sourceSchemaType === "SCHEMA_HISTORY_VERSION") {
- return databaseStore.getDatabaseByName(
- props.databaseSourceSchema!.databaseName
- ).instanceResource.engine;
- } else if (props.sourceSchemaType === "RAW_SQL") {
- return props.rawSqlState!.engine;
- } else {
- return Engine.ENGINE_UNSPECIFIED;
- }
-});
const targetDatabaseList = computed(() => {
return state.selectedDatabaseNameList.map((name) => {
return databaseStore.getDatabaseByName(name);
});
});
-const targetDatabaseSchema = computed(() => {
- if (instanceV1SupportsConciseSchema(engine.value)) {
- return state.selectedDatabaseName
- ? conciseSchemaCache[state.selectedDatabaseName]
- : "";
- }
+
+const targetSchemaDisplayString = computed(() => {
return state.selectedDatabaseName
- ? databaseSchemaCache[state.selectedDatabaseName]
+ ? databaseSchemaCache.value[state.selectedDatabaseName]
: "";
});
+
const selectedDatabase = computed(() => {
return state.selectedDatabaseName
? databaseStore.getDatabaseByName(state.selectedDatabaseName)
: undefined;
});
+
const shouldShowDiff = computed(() => {
return !!(
state.selectedDatabaseName &&
- databaseDiffCache[state.selectedDatabaseName]?.raw !== ""
+ schemaDiffCache.value[state.selectedDatabaseName]?.raw !== ""
);
});
+
const previewSchemaChangeMessage = computed(() => {
if (!state.selectedDatabaseName) {
return "";
@@ -399,14 +262,15 @@ const previewSchemaChangeMessage = computed(() => {
database: `${database.databaseName} (${environment?.title} - ${database.instanceResource.title})`,
});
});
+
const databaseListWithDiff = computed(() => {
return targetDatabaseList.value.filter(
- (db) => databaseDiffCache[db.name]?.raw !== ""
+ (db) => schemaDiffCache.value[db.name]?.raw !== ""
);
});
const databaseListWithoutDiff = computed(() => {
return targetDatabaseList.value.filter(
- (db) => databaseDiffCache[db.name]?.raw === ""
+ (db) => schemaDiffCache.value[db.name]?.raw === ""
);
});
const shownDatabaseList = computed(() => {
@@ -417,51 +281,11 @@ const shownDatabaseList = computed(() => {
);
});
-onMounted(async () => {
- state.isLoading = false;
-
- // Prepare raw sql statement from sheet.
- if (props.rawSqlState?.sheetId) {
- await sheetStore.getOrFetchSheetByUID(
- String(props.rawSqlState.sheetId),
- "FULL"
- );
- }
-});
-
-const getSourceDatabase = () => {
- if (!props.databaseSourceSchema) {
- return;
- }
- return databaseStore.getDatabaseByName(
- props.databaseSourceSchema.databaseName
- );
-};
-
-const getDatabaseSourceSchemaEnvironment = () => {
- if (!props.databaseSourceSchema) {
- return;
- }
- return environmentV1Store.getEnvironmentByName(
- props.databaseSourceSchema.environmentName
- );
-};
-
const handleSelectedDatabaseNameListChanged = (databaseNameList: string[]) => {
state.selectedDatabaseNameList = databaseNameList;
state.showSelectDatabasePanel = false;
};
-watch(
- () => props.targetDatabaseNameList,
- () => {
- handleSelectedDatabaseNameListChanged(props.targetDatabaseNameList ?? []);
- },
- {
- immediate: true,
- }
-);
-
const handleUnselectDatabase = (database: ComposedDatabase) => {
state.selectedDatabaseNameList = state.selectedDatabaseNameList.filter(
(name) => name !== database.name
@@ -473,7 +297,7 @@ const handleUnselectDatabase = (database: ComposedDatabase) => {
const onCopyStatement = () => {
const editStatement = state.selectedDatabaseName
- ? databaseDiffCache[state.selectedDatabaseName].edited
+ ? schemaDiffCache.value[state.selectedDatabaseName].edited
: "";
toClipboard(editStatement).then(() => {
@@ -485,9 +309,9 @@ const onCopyStatement = () => {
});
};
-const onStatementChange = (value: string) => {
+const onStatementChange = (statement: string) => {
if (state.selectedDatabaseName) {
- databaseDiffCache[state.selectedDatabaseName].edited = value;
+ schemaDiffCache.value[state.selectedDatabaseName].edited = statement;
}
};
@@ -499,45 +323,34 @@ watch(
);
watch(
- () => [state.selectedDatabaseNameList, sourceDatabaseSchema.value],
- async (_, oldValue) => {
- if (!sourceDatabaseSchema.value) {
- return;
- }
-
- // If source schema changed, we need to recompute the diff for all target databases.
- const skipCache = oldValue[1] !== sourceDatabaseSchema.value;
+ () => state.selectedDatabaseNameList,
+ async () => {
const schedule = setTimeout(() => {
state.isLoading = true;
}, 300);
for (const name of state.selectedDatabaseNameList) {
- if (databaseSchemaCache[name] && !skipCache) {
+ if (databaseSchemaCache.value[name]) {
continue;
}
const db = databaseStore.getDatabaseByName(name);
+ const concise = instanceV1SupportsConciseSchema(props.sourceEngine);
const schema = await databaseStore.fetchDatabaseSchema(
- `${db.name}/schema`
+ `${db.name}/schema`,
+ false /* sdlFormat */,
+ concise
);
- databaseSchemaCache[name] = schema.schema;
- if (instanceV1SupportsConciseSchema(engine.value)) {
- const conciseSchema = await databaseStore.fetchDatabaseSchema(
- `${db.name}/schema`,
- false /* sdlFormat */,
- true /* concise */
- );
- conciseSchemaCache[name] = conciseSchema.schema;
- }
- if (databaseDiffCache[name] && !skipCache) {
+ databaseSchemaCache.value[name] = schema.schema;
+ if (schemaDiffCache.value[name]) {
continue;
} else {
const diffResp = await databaseStore.diffSchema({
name: db.name,
- schema: sourceDatabaseSchema.value,
+ schema: props.sourceSchemaString,
sdlFormat: false,
});
const schemaDiff = diffResp.diff ?? "";
- databaseDiffCache[name] = {
+ schemaDiffCache.value[name] = {
raw: schemaDiff,
edited: schemaDiff,
};
@@ -556,15 +369,54 @@ watch(
state.selectedDatabaseName = undefined;
}
- if (state.selectedDatabaseName === undefined) {
+ if (!state.selectedDatabaseName) {
state.selectedDatabaseName = head(databaseListWithDiff.value)?.name;
}
});
}
);
+onMounted(async () => {
+ const targetDatabaseName = route.query.target as string;
+ if (isValidDatabaseName(targetDatabaseName)) {
+ const database =
+ await databaseStore.getOrFetchDatabaseByName(targetDatabaseName);
+ if (database && database.instanceResource.engine === props.sourceEngine) {
+ state.selectedDatabaseNameList = [targetDatabaseName];
+ state.selectedDatabaseName = targetDatabaseName;
+ }
+ }
+
+ // Prepare the source schema display string.
+ if (
+ props.sourceChangelogName &&
+ instanceV1SupportsConciseSchema(props.sourceEngine)
+ ) {
+ state.isLoading = true;
+ if (isValidChangelogName(props.sourceChangelogName)) {
+ const changelog = await databaseServiceClient.getChangelog({
+ name: props.sourceChangelogName,
+ view: ChangelogView.CHANGELOG_VIEW_FULL,
+ concise: true,
+ });
+ sourceSchemaDisplayString.value = changelog.schema;
+ } else {
+ const { databaseName } = extractDatabaseNameAndChangelogUID(
+ props.sourceChangelogName
+ );
+ const databaseSchema = await databaseStore.fetchDatabaseSchema(
+ `${databaseName}/schema`,
+ false /* sdlFormat */,
+ true /* concise */
+ );
+ sourceSchemaDisplayString.value = databaseSchema.schema;
+ }
+ state.isLoading = false;
+ }
+});
+
defineExpose({
targetDatabaseList,
- databaseDiffCache,
+ schemaDiffCache,
});
</script>
diff --git a/frontend/src/components/SyncDatabaseSchema/TargetDatabasesSelectPanel.vue b/frontend/src/components/SyncDatabaseSchemaV1/TargetDatabasesSelectPanel.vue
similarity index 97%
rename from frontend/src/components/SyncDatabaseSchema/TargetDatabasesSelectPanel.vue
rename to frontend/src/components/SyncDatabaseSchemaV1/TargetDatabasesSelectPanel.vue
index c2040bc890..b3385fc31b 100644
--- a/frontend/src/components/SyncDatabaseSchema/TargetDatabasesSelectPanel.vue
+++ b/frontend/src/components/SyncDatabaseSchemaV1/TargetDatabasesSelectPanel.vue
@@ -141,7 +141,9 @@ const selectedEnvironment = computed(() => {
});
const filteredDatabaseList = computed(() => {
- let list = databaseList.value;
+ let list = databaseList.value.filter(
+ (db) => db.instanceResource.engine === props.engine
+ );
if (selectedEnvironment.value !== `${UNKNOWN_ID}`) {
list = list.filter(
(db) =>
diff --git a/frontend/src/components/SyncDatabaseSchema/index.vue b/frontend/src/components/SyncDatabaseSchemaV1/index.vue
similarity index 52%
rename from frontend/src/components/SyncDatabaseSchema/index.vue
rename to frontend/src/components/SyncDatabaseSchemaV1/index.vue
index 5ad9011142..d9fa54ed7d 100644
--- a/frontend/src/components/SyncDatabaseSchema/index.vue
+++ b/frontend/src/components/SyncDatabaseSchemaV1/index.vue
@@ -6,7 +6,15 @@
url="https://www.bytebase.com/docs/change-database/synchronize-schema?source=console"
/>
</p>
+
+ <div
+ v-if="state.isLoading"
+ class="flex items-center justify-center py-2 text-gray-400 text-sm"
+ >
+ <BBSpin />
+ </div>
<StepTab
+ v-else
class="pt-4 flex-1 overflow-hidden flex flex-col"
:step-list="stepTabList"
:current-index="state.currentStep"
@@ -14,7 +22,6 @@
:allow-next="allowNext"
:finish-title="$t('database.sync-schema.preview-issue')"
pane-class="flex-1 overflow-y-auto"
- :next-button-props="nextButtonProps"
@cancel="cancelSetup"
@update:current-index="tryChangeStep"
@finish="tryFinishSetup"
@@ -23,7 +30,7 @@
<div class="mb-4">
<NRadioGroup v-model:value="state.sourceSchemaType" class="space-x-4">
<NRadio
- :value="'SCHEMA_HISTORY_VERSION'"
+ :value="SourceSchemaType.SCHEMA_HISTORY_VERSION"
:label="$t('database.sync-schema.schema-history-version')"
/>
<NRadio
@@ -33,29 +40,28 @@
</NRadioGroup>
</div>
<DatabaseSchemaSelector
- v-if="state.sourceSchemaType === 'SCHEMA_HISTORY_VERSION'"
- :select-state="changeHistorySourceSchemaState"
- :disable-project-select="!!project"
+ v-if="
+ state.sourceSchemaType === SourceSchemaType.SCHEMA_HISTORY_VERSION
+ "
+ :project="project"
+ :source-schema="changelogSourceSchemaState"
@update="handleChangeHistorySchemaVersionChanges"
/>
<RawSQLEditor
- v-if="state.sourceSchemaType === 'RAW_SQL'"
- :project-name="rawSQLState.projectName"
+ v-if="state.sourceSchemaType === SourceSchemaType.RAW_SQL"
+ :project="project"
:engine="rawSQLState.engine"
:statement="rawSQLState.statement"
- :sheet-id="rawSQLState.sheetId"
- :disable-project-select="!!project"
- @update="handleRawSQLStateChange"
+ @update="(state) => Object.assign(rawSQLState, state)"
/>
</template>
<template #1>
<SelectTargetDatabasesView
ref="targetDatabaseViewRef"
- :project-name="projectName"
- :source-schema-type="state.sourceSchemaType"
- :database-source-schema="changeHistorySourceSchemaState as any"
- :raw-sql-state="rawSQLState"
- :target-database-name-list="targetDatabaseList"
+ :project="project"
+ :source-schema-string="sourceSchemaString"
+ :source-engine="sourceEngine"
+ :source-changelog-bane="changelogSourceSchemaState.changelogName"
/>
</template>
</StepTab>
@@ -63,90 +69,137 @@
</template>
<script lang="ts" setup>
+import { asyncComputed } from "@vueuse/core";
import { isUndefined } from "lodash-es";
-import type { ButtonProps } from "naive-ui";
import { NRadioGroup, NRadio, useDialog } from "naive-ui";
import { v4 as uuidv4 } from "uuid";
-import { computed, reactive, ref, watchEffect } from "vue";
+import { computed, onMounted, reactive, ref } from "vue";
import { useI18n } from "vue-i18n";
-import { useRouter } from "vue-router";
+import { useRoute, useRouter } from "vue-router";
+import { BBSpin } from "@/bbkit";
import { StepTab } from "@/components/v2";
import { PROJECT_V1_ROUTE_ISSUE_DETAIL } from "@/router/dashboard/projectV1";
import { WORKSPACE_ROOT_MODULE } from "@/router/dashboard/workspaceRoutes";
-import { useProjectV1Store, useStorageStore } from "@/store";
-import type { ComposedProject } from "@/types";
import {
- isValidDatabaseName,
- isValidEnvironmentName,
- isValidProjectName,
-} from "@/types";
+ useChangelogStore,
+ useDatabaseV1Store,
+ useStorageStore,
+} from "@/store";
+import type { ComposedProject } from "@/types";
+import { isValidDatabaseName, isValidEnvironmentName } from "@/types";
import { Engine } from "@/types/proto/v1/common";
+import { ChangelogView } from "@/types/proto/v1/database_service";
import { extractProjectResourceName, generateIssueTitle } from "@/utils";
+import {
+ extractDatabaseNameAndChangelogUID,
+ isValidChangelogName,
+} from "@/utils/v1/changelog";
import LearnMoreLink from "../LearnMoreLink.vue";
import DatabaseSchemaSelector from "./DatabaseSchemaSelector.vue";
import RawSQLEditor from "./RawSQLEditor.vue";
import SelectTargetDatabasesView from "./SelectTargetDatabasesView.vue";
-import type {
- ChangeHistorySourceSchema,
- RawSQLState,
+import {
+ type ChangelogSourceSchema,
+ type RawSQLState,
SourceSchemaType,
} from "./types";
-const SELECT_SOURCE_SCHEMA = 0;
-const SELECT_TARGET_DATABASE_LIST = 1;
-
-type Step = typeof SELECT_SOURCE_SCHEMA | typeof SELECT_TARGET_DATABASE_LIST;
+enum Step {
+ SELECT_SOURCE_SCHEMA,
+ SELECT_TARGET_DATABASE_LIST,
+}
interface LocalState {
+ isLoading: boolean;
sourceSchemaType: SourceSchemaType;
currentStep: Step;
}
const props = defineProps<{
project: ComposedProject;
- sourceSchemaType?: SourceSchemaType;
- source?: ChangeHistorySourceSchema;
- targetDatabaseList?: string[];
}>();
const { t } = useI18n();
+const route = useRoute();
const router = useRouter();
const dialog = useDialog();
-const projectStore = useProjectV1Store();
-const targetDatabaseViewRef =
- ref<InstanceType<typeof SelectTargetDatabasesView>>();
+const changelogStore = useChangelogStore();
+const databaseStore = useDatabaseV1Store();
const state = reactive<LocalState>({
- sourceSchemaType: props.sourceSchemaType ?? "SCHEMA_HISTORY_VERSION",
- currentStep: SELECT_SOURCE_SCHEMA,
-});
-const changeHistorySourceSchemaState = reactive<ChangeHistorySourceSchema>({
- projectName: props.project.name,
+ isLoading: true,
+ sourceSchemaType: SourceSchemaType.SCHEMA_HISTORY_VERSION,
+ currentStep: Step.SELECT_SOURCE_SCHEMA,
});
+const changelogSourceSchemaState = reactive<ChangelogSourceSchema>({});
const rawSQLState = reactive<RawSQLState>({
- projectName: props.project.name,
engine: Engine.MYSQL,
statement: "",
});
+const targetDatabaseViewRef =
+ ref<InstanceType<typeof SelectTargetDatabasesView>>();
+
+const sourceSchemaString = asyncComputed(async () => {
+ if (state.sourceSchemaType === SourceSchemaType.SCHEMA_HISTORY_VERSION) {
+ if (isValidChangelogName(changelogSourceSchemaState.changelogName)) {
+ const changelog = changelogStore.getChangelogByName(
+ changelogSourceSchemaState?.changelogName || ""
+ );
+ if (changelog) {
+ return changelog.schema;
+ }
+ console.error("Changelog not found");
+ return "";
+ } else if (isValidDatabaseName(changelogSourceSchemaState.databaseName)) {
+ const databaseSchema = await databaseStore.fetchDatabaseSchema(
+ `${changelogSourceSchemaState.databaseName}/schema`
+ );
+ return databaseSchema.schema;
+ }
+ // Fallback to empty string if no valid source schema.
+ return "";
+ } else {
+ return rawSQLState.statement;
+ }
+}, "");
-const projectName = computed(() => {
- return props.project.name;
+const sourceEngine = computed(() => {
+ if (state.sourceSchemaType === SourceSchemaType.SCHEMA_HISTORY_VERSION) {
+ if (!changelogSourceSchemaState.databaseName) {
+ return Engine.ENGINE_UNSPECIFIED;
+ }
+ const database = databaseStore.getDatabaseByName(
+ changelogSourceSchemaState.databaseName
+ );
+ return database.instanceResource.engine;
+ } else {
+ return rawSQLState.engine;
+ }
});
const handleChangeHistorySchemaVersionChanges = (
- schemaVersion: ChangeHistorySourceSchema
+ schemaVersion: ChangelogSourceSchema
) => {
- Object.assign(changeHistorySourceSchemaState, schemaVersion);
+ Object.assign(changelogSourceSchemaState, schemaVersion);
};
-const autoNext = ref<boolean>(true);
-watchEffect(() => {
- if (props.source) {
- handleChangeHistorySchemaVersionChanges(props.source);
- if (autoNext.value) {
- state.currentStep = SELECT_TARGET_DATABASE_LIST;
- autoNext.value = false;
- }
+onMounted(async () => {
+ const changelogName = route.query.changelog as string;
+ if (isValidChangelogName(changelogName)) {
+ // Prepare source schema from the selected changelog.
+ await changelogStore.getOrFetchChangelogByName(
+ changelogName,
+ ChangelogView.CHANGELOG_VIEW_FULL
+ );
+ const { databaseName } = extractDatabaseNameAndChangelogUID(changelogName);
+ const database = await databaseStore.getOrFetchDatabaseByName(databaseName);
+ handleChangeHistorySchemaVersionChanges({
+ environmentName: database.effectiveEnvironment,
+ databaseName: databaseName,
+ changelogName: changelogName,
+ });
+ state.currentStep = Step.SELECT_TARGET_DATABASE_LIST;
}
+ state.isLoading = false;
});
const stepTabList = computed(() => {
@@ -157,21 +210,15 @@ const stepTabList = computed(() => {
});
const allowNext = computed(() => {
- if (state.currentStep === SELECT_SOURCE_SCHEMA) {
- if (state.sourceSchemaType === "SCHEMA_HISTORY_VERSION") {
+ if (state.currentStep === Step.SELECT_SOURCE_SCHEMA) {
+ if (state.sourceSchemaType === SourceSchemaType.SCHEMA_HISTORY_VERSION) {
return (
- !changeHistorySourceSchemaState.isFetching &&
- isValidEnvironmentName(
- changeHistorySourceSchemaState.environmentName
- ) &&
- isValidDatabaseName(changeHistorySourceSchemaState.databaseName) &&
- !isUndefined(changeHistorySourceSchemaState.changeHistory)
+ isValidEnvironmentName(changelogSourceSchemaState.environmentName) &&
+ isValidDatabaseName(changelogSourceSchemaState.databaseName) &&
+ !isUndefined(changelogSourceSchemaState.changelogName)
);
} else {
- return (
- isValidProjectName(rawSQLState.projectName) &&
- (rawSQLState.statement !== "" || !isUndefined(rawSQLState.sheetId))
- );
+ return rawSQLState.statement !== "";
}
} else {
if (!targetDatabaseViewRef.value) {
@@ -180,7 +227,7 @@ const allowNext = computed(() => {
const targetDatabaseList = targetDatabaseViewRef.value?.targetDatabaseList;
const targetDatabaseDiffList = targetDatabaseList
.map((db) => {
- const diff = targetDatabaseViewRef.value!.databaseDiffCache[db.name];
+ const diff = targetDatabaseViewRef.value!.schemaDiffCache[db.name];
return {
name: db.name,
diff: diff?.edited || "",
@@ -191,25 +238,11 @@ const allowNext = computed(() => {
}
});
-const nextButtonProps = computed((): ButtonProps | undefined => {
- if (state.currentStep === SELECT_SOURCE_SCHEMA) {
- if (state.sourceSchemaType === "SCHEMA_HISTORY_VERSION") {
- if (changeHistorySourceSchemaState.isFetching) {
- return {
- loading: true,
- };
- }
- }
- }
- return undefined;
-});
-
-const handleRawSQLStateChange = (state: RawSQLState) => {
- Object.assign(rawSQLState, state);
-};
-
const tryChangeStep = async (nextStepIndex: number) => {
- if (state.currentStep === 1 && nextStepIndex === 0) {
+ if (
+ state.currentStep === Step.SELECT_TARGET_DATABASE_LIST &&
+ nextStepIndex === Step.SELECT_SOURCE_SCHEMA
+ ) {
const targetDatabaseList =
targetDatabaseViewRef.value?.targetDatabaseList || [];
if (targetDatabaseList.length > 0) {
@@ -230,6 +263,17 @@ const tryChangeStep = async (nextStepIndex: number) => {
});
return;
}
+ } else if (
+ state.currentStep === Step.SELECT_SOURCE_SCHEMA &&
+ nextStepIndex === Step.SELECT_TARGET_DATABASE_LIST
+ ) {
+ // Prepare source schema from the selected changelog.
+ if (changelogSourceSchemaState?.changelogName) {
+ await changelogStore.getOrFetchChangelogByName(
+ changelogSourceSchemaState.changelogName,
+ ChangelogView.CHANGELOG_VIEW_FULL
+ );
+ }
}
state.currentStep = nextStepIndex as Step;
};
@@ -240,8 +284,6 @@ const tryFinishSetup = async () => {
}
const targetDatabaseList = targetDatabaseViewRef.value.targetDatabaseList;
- const project = await projectStore.getOrFetchProjectByName(projectName.value);
-
const query: Record<string, any> = {
template: "bb.issue.database.schema.update",
mode: "normal",
@@ -249,7 +291,7 @@ const tryFinishSetup = async () => {
};
const sqlMap: Record<string, string> = {};
targetDatabaseList.forEach((db) => {
- const diff = targetDatabaseViewRef.value!.databaseDiffCache[db.name];
+ const diff = targetDatabaseViewRef.value!.schemaDiffCache[db.name];
// Only allow edited database to be included in the issue.
if (diff.edited) {
sqlMap[db.name] = diff.edited;
@@ -267,7 +309,7 @@ const tryFinishSetup = async () => {
const routeInfo = {
name: PROJECT_V1_ROUTE_ISSUE_DETAIL,
params: {
- projectId: extractProjectResourceName(project.name),
+ projectId: extractProjectResourceName(props.project.name),
issueSlug: "create",
},
query,
diff --git a/frontend/src/components/SyncDatabaseSchemaV1/types.ts b/frontend/src/components/SyncDatabaseSchemaV1/types.ts
new file mode 100644
index 0000000000..fd670c4fc7
--- /dev/null
+++ b/frontend/src/components/SyncDatabaseSchemaV1/types.ts
@@ -0,0 +1,25 @@
+import { Engine } from "@/types/proto/v1/common";
+
+export enum SourceSchemaType {
+ SCHEMA_HISTORY_VERSION,
+ RAW_SQL,
+}
+
+export interface ChangelogSourceSchema {
+ environmentName?: string;
+ databaseName?: string;
+ changelogName?: string;
+}
+
+export interface RawSQLState {
+ engine: Engine;
+ statement: string;
+}
+
+export const ALLOWED_ENGINES: Engine[] = [
+ Engine.MYSQL,
+ Engine.POSTGRES,
+ Engine.TIDB,
+ Engine.ORACLE,
+ Engine.MSSQL,
+];
diff --git a/frontend/src/router/dashboard/projectV1.ts b/frontend/src/router/dashboard/projectV1.ts
index 8ee990170f..aa5f4f1ee0 100644
--- a/frontend/src/router/dashboard/projectV1.ts
+++ b/frontend/src/router/dashboard/projectV1.ts
@@ -311,7 +311,8 @@ const projectV1Routes: RouteRecordRaw[] = [
"bb.databases.sync",
],
},
- component: () => import("@/views/project/ProjectSyncDatabasePanel.vue"),
+ component: () =>
+ import("@/views/project/ProjectSyncDatabasePanelV1.vue"),
props: true,
},
{
@@ -508,7 +509,6 @@ const projectV1Routes: RouteRecordRaw[] = [
path: "changelogs/:changelogId",
name: PROJECT_V1_ROUTE_DATABASE_CHANGELOG_DETAIL,
meta: {
- overrideTitle: true,
requiredProjectPermissionList: () => [
"bb.projects.get",
"bb.databases.get",
diff --git a/frontend/src/store/modules/v1/changelog.ts b/frontend/src/store/modules/v1/changelog.ts
index ba574133af..9ebef424a1 100644
--- a/frontend/src/store/modules/v1/changelog.ts
+++ b/frontend/src/store/modules/v1/changelog.ts
@@ -38,18 +38,21 @@ export const useChangelogStore = defineStore("changelog", () => {
const fetchChangelogList = async (params: Partial<ListChangelogsRequest>) => {
const { parent } = params;
if (!parent) throw new Error('"parent" field is required');
- const { changelogs } = await databaseServiceClient.listChangelogs(params);
+ const { changelogs, nextPageToken } =
+ await databaseServiceClient.listChangelogs(params);
await upsertChangelogsMap(parent, changelogs);
- return changelogs;
+ return { changelogs, nextPageToken };
};
const getOrFetchChangelogListOfDatabase = async (databaseName: string) => {
if (changelogsMapByDatabase.has(databaseName)) {
return changelogsMapByDatabase.get(databaseName) ?? [];
}
- return fetchChangelogList({
+ // Fetch all changelogs of the database with max DEFAULT_PAGE_SIZE.
+ const { changelogs } = await fetchChangelogList({
parent: databaseName,
pageSize: DEFAULT_PAGE_SIZE,
});
+ return changelogs;
};
const changelogListByDatabase = (name: string) => {
return changelogsMapByDatabase.get(name) ?? [];
@@ -64,7 +67,8 @@ export const useChangelogStore = defineStore("changelog", () => {
};
const getOrFetchChangelogByName = async (
name: string,
- view: ChangelogView
+ view: ChangelogView = ChangelogView.CHANGELOG_VIEW_BASIC,
+ concise = false
) => {
const uid = extractChangelogUID(name);
if (!uid || uid === String(UNKNOWN_ID)) {
@@ -78,7 +82,7 @@ export const useChangelogStore = defineStore("changelog", () => {
if (request) {
return request;
}
- const promise = fetchChangelog({ name, view });
+ const promise = fetchChangelog({ name, view, concise });
cache.setRequest([name, view], promise);
return promise;
};
diff --git a/frontend/src/utils/v1/changelog.ts b/frontend/src/utils/v1/changelog.ts
index 5c247d1e4b..ba58528939 100644
--- a/frontend/src/utils/v1/changelog.ts
+++ b/frontend/src/utils/v1/changelog.ts
@@ -5,10 +5,7 @@ import { useDBSchemaV1Store, useDatabaseV1Store } from "@/store";
import type { ComposedDatabase } from "@/types";
import { EMPTY_ID, UNKNOWN_ID } from "@/types";
import { type AffectedTable, EmptyAffectedTable } from "@/types";
-import {
- Changelog_Type,
- type DatabaseSchema,
-} from "@/types/proto/v1/database_service";
+import { Changelog_Type } from "@/types/proto/v1/database_service";
import { Changelog } from "@/types/proto/v1/database_service";
import { databaseV1Url, extractDatabaseResourceName } from "./database";
@@ -99,15 +96,12 @@ export const getAffectedTableDisplayName = (affectedTable: AffectedTable) => {
export const mockLatestChangelog = (
database: ComposedDatabase,
- schema: DatabaseSchema | undefined = undefined
+ schema: string = ""
) => {
return Changelog.fromPartial({
name: `${database.name}/changelogs/${UNKNOWN_ID}`,
- schema: schema?.schema,
- schemaSize: Long.fromNumber(
- new TextEncoder().encode(schema?.schema).length
- ),
- version: "Latest version",
+ schema: schema,
+ schemaSize: Long.fromNumber(new TextEncoder().encode(schema).length),
});
};
diff --git a/frontend/src/views/project/ProjectSyncDatabasePanel.vue b/frontend/src/views/project/ProjectSyncDatabasePanel.vue
deleted file mode 100644
index bf98274536..0000000000
--- a/frontend/src/views/project/ProjectSyncDatabasePanel.vue
+++ /dev/null
@@ -1,103 +0,0 @@
-<template>
- <SyncDatabaseSchema
- :key="project.name"
- :project="project"
- :source="source"
- :source-schema-type="source ? 'SCHEMA_HISTORY_VERSION' : undefined"
- :target-database-list="targetDatabaseList"
- />
-</template>
-
-<script setup lang="ts">
-import { computed, ref, onMounted } from "vue";
-import { useRoute } from "vue-router";
-import SyncDatabaseSchema from "@/components/SyncDatabaseSchema/index.vue";
-import { type ChangeHistorySourceSchema } from "@/components/SyncDatabaseSchema/types";
-import {
- useProjectByName,
- useDatabaseV1Store,
- useChangeHistoryStore,
-} from "@/store";
-import { projectNamePrefix } from "@/store/modules/v1/common";
-import { UNKNOWN_DATABASE_NAME } from "@/types";
-import { ChangeHistoryView } from "@/types/proto/v1/database_service";
-import { extractDatabaseNameAndChangeHistoryUID, instanceV1SupportsConciseSchema } from "@/utils";
-
-const props = defineProps<{
- projectId: string;
-}>();
-
-const route = useRoute();
-const changeHistoryStore = useChangeHistoryStore();
-const databaseStore = useDatabaseV1Store();
-const targetDatabaseList = ref<string[]>([]);
-const conciseHistory = ref<string | undefined>(undefined);
-
-const changeHistoryVersion = computed(() => {
- const version = route.query.version as string;
- return version || "";
-});
-
-const changeHistory = computed(() => {
- if (!changeHistoryVersion.value) {
- return;
- }
- return changeHistoryStore.getChangeHistoryByName(changeHistoryVersion.value);
-});
-
-onMounted(async () => {
- if (!changeHistoryVersion.value) {
- return;
- }
- const history = await changeHistoryStore.getOrFetchChangeHistoryByName(
- changeHistoryVersion.value,
- ChangeHistoryView.CHANGE_HISTORY_VIEW_FULL
- );
- if (!history) {
- return;
- }
- const { databaseName } = extractDatabaseNameAndChangeHistoryUID(history.name);
- const database = await databaseStore.getOrFetchDatabaseByName(databaseName);
- if (instanceV1SupportsConciseSchema(database.instanceResource)) {
- const conciseSchema = await changeHistoryStore.fetchChangeHistory({
- name: history.name,
- view: ChangeHistoryView.CHANGE_HISTORY_VIEW_FULL,
- concise: true,
- });
- conciseHistory.value = conciseSchema?.schema;
- }
-
- const target = route.query.target as string;
- const databaseList = (target || "").split(",").filter((n) => n);
-
- const databaseNameList = [];
- for (const dbName of databaseList) {
- const database = await databaseStore.getOrFetchDatabaseByName(dbName);
- if (database.name !== UNKNOWN_DATABASE_NAME) {
- databaseNameList.push(databaseName);
- }
- }
- targetDatabaseList.value = databaseNameList;
-});
-
-const source = computed((): ChangeHistorySourceSchema | undefined => {
- if (!changeHistory.value) {
- return;
- }
- const { databaseName } = extractDatabaseNameAndChangeHistoryUID(
- changeHistory.value.name
- );
- const database = databaseStore.getDatabaseByName(databaseName);
- return {
- databaseName,
- changeHistory: changeHistory.value,
- conciseHistory: conciseHistory.value,
- environmentName: database.effectiveEnvironment,
- projectName: database.project,
- };
-});
-
-const { project } = useProjectByName(
- computed(() => `${projectNamePrefix}${props.projectId}`)
-);
-</script>
diff --git a/frontend/src/views/project/ProjectSyncDatabasePanelV1.vue b/frontend/src/views/project/ProjectSyncDatabasePanelV1.vue
new file mode 100644
index 0000000000..3513e33e9b
--- /dev/null
+++ b/frontend/src/views/project/ProjectSyncDatabasePanelV1.vue
@@ -0,0 +1,18 @@
+<template>
+ <SyncDatabaseSchema :key="project.name" :project="project" />
+</template>
+
+<script setup lang="ts">
+import { computed } from "vue";
+import SyncDatabaseSchema from "@/components/SyncDatabaseSchemaV1/index.vue";
+import { useProjectByName } from "@/store";
+import { projectNamePrefix } from "@/store/modules/v1/common";
+
+const props = defineProps<{
+ projectId: string;
+}>();
+
+const { project } = useProjectByName(
+ computed(() => `${projectNamePrefix}${props.projectId}`)
+);
+</script>