Skip to content

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

chore: remove old schema editor (#8203)

boojackce4ef8c79321
diff --git a/frontend/src/components/AlterSchemaPrepForm/DatabaseGroupPrevEditorModal.vue b/frontend/src/components/AlterSchemaPrepForm/DatabaseGroupPrevEditorModal.vue
index f5a08bcf3b..63c2b859f1 100644
--- a/frontend/src/components/AlterSchemaPrepForm/DatabaseGroupPrevEditorModal.vue
+++ b/frontend/src/components/AlterSchemaPrepForm/DatabaseGroupPrevEditorModal.vue
@@ -75,7 +75,7 @@
import { computed, onMounted, PropType, reactive } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
-import ActionConfirmModal from "@/components/SchemaEditor/Modals/ActionConfirmModal.vue";
+import ActionConfirmModal from "@/components/SchemaEditorV1/Modals/ActionConfirmModal.vue";
import { useDBGroupStore, useNotificationStore } from "@/store";
import { ComposedDatabaseGroup, ComposedSchemaGroup } from "@/types";
import { generateDatabaseGroupIssueRoute } from "@/utils/databaseGroup/issue";
diff --git a/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vue b/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vue
index ce9d5f9f2a..4ddc16d686 100644
--- a/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vue
+++ b/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vue
@@ -33,13 +33,17 @@
</button>
</div>
<div class="w-full h-full max-h-full overflow-auto border-b mb-4">
- <SchemaEditorV1
+ <div
v-show="state.selectedTab === 'schema-editor'"
- :engine="databaseEngine"
- :project="project"
- :resource-type="'database'"
- :databases="databaseList"
- />
+ class="w-full h-full py-2"
+ >
+ <SchemaEditorV1
+ :engine="databaseEngine"
+ :project="project"
+ :resource-type="'database'"
+ :databases="databaseList"
+ />
+ </div>
<div
v-show="state.selectedTab === 'raw-sql'"
class="w-full h-full grid grid-rows-[50px,_1fr] overflow-y-auto"
@@ -133,7 +137,7 @@ import { computed, onMounted, PropType, reactive, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import BBBetaBadge from "@/bbkit/BBBetaBadge.vue";
-import ActionConfirmModal from "@/components/SchemaEditor/Modals/ActionConfirmModal.vue";
+import ActionConfirmModal from "@/components/SchemaEditorV1/Modals/ActionConfirmModal.vue";
import SchemaEditorV1 from "@/components/SchemaEditorV1/index.vue";
import {
useDatabaseV1Store,
@@ -539,7 +543,6 @@ const generateIssueName = (
const datetime = dayjs().format("@MM-DD HH:mm");
const tz = "UTC" + dayjs().format("ZZ");
issueNameParts.push(`${datetime} ${tz}`);
-
return issueNameParts.join(" ");
};
diff --git a/frontend/src/components/SchemaDesigner/CreateSchemaDesignPanel.vue b/frontend/src/components/SchemaDesigner/CreateSchemaDesignPanel.vue
index 0d225c9fe3..674c6aefb2 100644
--- a/frontend/src/components/SchemaDesigner/CreateSchemaDesignPanel.vue
+++ b/frontend/src/components/SchemaDesigner/CreateSchemaDesignPanel.vue
@@ -47,14 +47,15 @@
:baseline-schema="state.baselineSchema"
@update="handleBaselineSchemaChange"
/>
- <SchemaEditorV1
- :key="refreshId"
- class="!mt-6"
- :project="project"
- :resource-type="'branch'"
- :branches="[state.schemaDesign]"
- :readonly="true"
- />
+ <div class="!mt-6 w-full h-[32rem]">
+ <SchemaEditorV1
+ :key="refreshId"
+ :project="project"
+ :resource-type="'branch'"
+ :branches="[state.schemaDesign]"
+ :readonly="true"
+ />
+ </div>
</div>
<template #footer>
diff --git a/frontend/src/components/SchemaDesigner/EditSchemaDesignPanel.vue b/frontend/src/components/SchemaDesigner/EditSchemaDesignPanel.vue
index dec4a3184d..68c381d39b 100644
--- a/frontend/src/components/SchemaDesigner/EditSchemaDesignPanel.vue
+++ b/frontend/src/components/SchemaDesigner/EditSchemaDesignPanel.vue
@@ -147,13 +147,15 @@
</template>
</div>
- <SchemaEditorV1
- :key="schemaEditorKey"
- :readonly="!state.isEditing"
- :project="project"
- :resource-type="'branch'"
- :branches="[schemaDesign]"
- />
+ <div class="w-full h-[32rem]">
+ <SchemaEditorV1
+ :key="schemaEditorKey"
+ :readonly="!state.isEditing"
+ :project="project"
+ :resource-type="'branch'"
+ :branches="[schemaDesign]"
+ />
+ </div>
<!-- Don't show delete button in view mode. -->
<div v-if="!viewMode">
<BBButtonConfirm
diff --git a/frontend/src/components/SchemaEditor/AsidePanel.vue b/frontend/src/components/SchemaEditor/AsidePanel.vue
deleted file mode 100644
index 3bba344d8a..0000000000
--- a/frontend/src/components/SchemaEditor/AsidePanel.vue
+++ /dev/null
@@ -1,7 +0,0 @@
-<template>
- <DatabaseTree />
-</template>
-
-<script lang="ts" setup>
-import DatabaseTree from "./DatabaseTree.vue";
-</script>
diff --git a/frontend/src/components/SchemaEditor/DatabaseTree.vue b/frontend/src/components/SchemaEditor/DatabaseTree.vue
deleted file mode 100644
index 0256c320f9..0000000000
--- a/frontend/src/components/SchemaEditor/DatabaseTree.vue
+++ /dev/null
@@ -1,831 +0,0 @@
-<template>
- <div class="w-full h-full pl-1 pr-2 relative overflow-y-hidden">
- <div class="w-full sticky top-0 pt-2 h-12 bg-white z-10">
- <NInput
- v-model:value="searchPattern"
- :placeholder="$t('schema-editor.search-database-and-table')"
- >
- <template #prefix>
- <heroicons-outline:search class="w-4 h-auto text-gray-300" />
- </template>
- </NInput>
- </div>
- <div
- class="schema-editor-database-tree pb-2 overflow-y-auto h-full text-sm"
- >
- <NTree
- ref="treeRef"
- block-line
- virtual-scroll
- style="height: 100%"
- :data="treeDataRef"
- :pattern="searchPattern"
- :render-prefix="renderPrefix"
- :render-label="renderLabel"
- :render-suffix="renderSuffix"
- :node-props="nodeProps"
- :on-load="loadSubTree"
- :expanded-keys="expandedKeysRef"
- :selected-keys="selectedKeysRef"
- :on-update:expanded-keys="handleExpandedKeysChange"
- />
- <NDropdown
- trigger="manual"
- placement="bottom-start"
- :show="contextMenu.showDropdown"
- :options="contextMenuOptions"
- :x="contextMenu.clientX"
- :y="contextMenu.clientY"
- to="body"
- @select="handleContextMenuDropdownSelect"
- @clickoutside="handleDropdownClickoutside"
- />
- </div>
- </div>
-
- <SchemaNameModal
- v-if="state.schemaNameModalContext !== undefined"
- :database-id="state.schemaNameModalContext.databaseId"
- :schema-id="state.schemaNameModalContext.schemaId"
- @close="state.schemaNameModalContext = undefined"
- />
-
- <TableNameModal
- v-if="state.tableNameModalContext !== undefined"
- :database-id="state.tableNameModalContext.databaseId"
- :schema-id="state.tableNameModalContext.schemaId"
- :table-id="state.tableNameModalContext.tableId"
- @close="state.tableNameModalContext = undefined"
- />
-</template>
-
-<script lang="ts" setup>
-import { escape, head, isUndefined } from "lodash-es";
-import { TreeOption, NEllipsis, NInput, NDropdown, NTree } from "naive-ui";
-import { computed, onMounted, watch, ref, h, reactive, nextTick } from "vue";
-import { useI18n } from "vue-i18n";
-import DatabaseIcon from "~icons/heroicons-outline/circle-stack";
-import TableIcon from "~icons/heroicons-outline/table-cells";
-import SchemaIcon from "~icons/heroicons-outline/view-columns";
-import EllipsisIcon from "~icons/heroicons-solid/ellipsis-horizontal";
-import { InstanceV1EngineIcon } from "@/components/v2";
-import {
- useSchemaEditorStore,
- generateUniqueTabId,
- useInstanceV1Store,
- useNotificationStore,
-} from "@/store";
-import { SchemaEditorTabType } from "@/types";
-import { Engine } from "@/types/proto/v1/common";
-import { Schema, Table } from "@/types/schemaEditor/atomType";
-import { getHighlightHTMLByKeyWords, isDescendantOf } from "@/utils";
-import SchemaNameModal from "./Modals/SchemaNameModal.vue";
-import TableNameModal from "./Modals/TableNameModal.vue";
-import { isSchemaChanged } from "./utils/schema";
-import { isTableChanged } from "./utils/table";
-
-interface BaseTreeNode extends TreeOption {
- key: string;
- label: string;
- isLeaf: boolean;
- children?: TreeNode[];
-}
-
-interface TreeNodeForInstance extends BaseTreeNode {
- type: "instance";
- instanceId: string;
-}
-
-interface TreeNodeForDatabase extends BaseTreeNode {
- type: "database";
- instanceId: string;
- databaseId: string;
-}
-
-interface TreeNodeForSchema extends BaseTreeNode {
- type: "schema";
- instanceId: string;
- databaseId: string;
- schemaId: string;
-}
-
-interface TreeNodeForTable extends BaseTreeNode {
- type: "table";
- instanceId: string;
- databaseId: string;
- schemaId: string;
- tableId: string;
-}
-
-type TreeNode =
- | TreeNodeForInstance
- | TreeNodeForDatabase
- | TreeNodeForSchema
- | TreeNodeForTable;
-
-interface TreeContextMenu {
- showDropdown: boolean;
- clientX: number;
- clientY: number;
- treeNode?: TreeNode;
-}
-
-interface LocalState {
- shouldRelocateTreeNode: boolean;
- schemaNameModalContext?: {
- databaseId: string;
- schemaId: string | undefined;
- };
- tableNameModalContext?: {
- databaseId: string;
- schemaId: string;
- tableId: string | undefined;
- };
-}
-
-const { t } = useI18n();
-const editorStore = useSchemaEditorStore();
-const instanceStore = useInstanceV1Store();
-const state = reactive<LocalState>({
- shouldRelocateTreeNode: false,
-});
-const contextMenu = reactive<TreeContextMenu>({
- showDropdown: false,
- clientX: 0,
- clientY: 0,
- treeNode: undefined,
-});
-const treeRef = ref<InstanceType<typeof NTree>>();
-const searchPattern = ref("");
-const expandedKeysRef = ref<string[]>([]);
-const selectedKeysRef = ref<string[]>([]);
-const treeDataRef = ref<TreeNode[]>([]);
-const databaseDataLoadedSet = ref<Set<string>>(new Set());
-
-const databaseList = computed(() => editorStore.databaseList);
-const schemaList = computed(() =>
- Array.from(editorStore.databaseSchemaById.values())
- .map((databaseState) => databaseState.schemaList)
- .flat()
-);
-const tableList = computed(() =>
- schemaList.value.map((schema) => schema.tableList).flat()
-);
-const contextMenuOptions = computed(() => {
- const treeNode = contextMenu.treeNode;
- if (isUndefined(treeNode)) {
- return [];
- }
- const instanceEngine = instanceStore.getInstanceByUID(
- treeNode.instanceId
- ).engine;
-
- if (treeNode.type === "database") {
- const options = [];
- if (instanceEngine === Engine.MYSQL) {
- options.push({
- key: "create-table",
- label: t("schema-editor.actions.create-table"),
- });
- } else if (instanceEngine === Engine.POSTGRES) {
- options.push({
- key: "create-schema",
- label: t("schema-editor.actions.create-schema"),
- });
- }
- return options;
- } else if (treeNode.type === "schema") {
- const options = [];
- if (instanceEngine === Engine.POSTGRES) {
- const schema = editorStore.getSchema(
- treeNode.databaseId,
- treeNode.schemaId
- );
- if (!schema) {
- return [];
- }
-
- const isDropped = schema.status === "dropped";
- if (isDropped) {
- options.push({
- key: "restore",
- label: t("schema-editor.actions.restore"),
- });
- } else {
- options.push({
- key: "create-table",
- label: t("schema-editor.actions.create-table"),
- });
- options.push({
- key: "rename",
- label: t("schema-editor.actions.rename"),
- });
- options.push({
- key: "drop-schema",
- label: t("schema-editor.actions.drop-schema"),
- });
- }
- }
- return options;
- } else if (treeNode.type === "table") {
- const table = editorStore.databaseSchemaById
- .get(treeNode.databaseId)
- ?.schemaList.find((schema) => schema.id === treeNode.schemaId)
- ?.tableList.find((table) => table.id === treeNode.tableId);
- if (!table) {
- return [];
- }
-
- const isDropped = table.status === "dropped";
- const options = [];
- if (isDropped) {
- options.push({
- key: "restore",
- label: t("schema-editor.actions.restore"),
- });
- } else {
- options.push({
- key: "rename",
- label: t("schema-editor.actions.rename"),
- });
- options.push({
- key: "drop",
- label: t("schema-editor.actions.drop-table"),
- });
- }
- return options;
- }
-
- return [];
-});
-
-onMounted(async () => {
- const treeNodeList: TreeNode[] = [];
- const instanceTreeNodeMap: Map<string, TreeNodeForInstance> = new Map();
- const databaseTreeNodeList: TreeNodeForDatabase[] = [];
- for (const database of databaseList.value) {
- const instance = database.instanceEntity;
- let instanceTreeNode: TreeNodeForInstance;
- if (instanceTreeNodeMap.has(instance.uid)) {
- instanceTreeNode = instanceTreeNodeMap.get(
- instance.uid
- ) as TreeNodeForInstance;
- } else {
- instanceTreeNode = {
- type: "instance",
- key: `i-${instance.uid}`,
- label: instance.title,
- isLeaf: false,
- instanceId: instance.uid,
- children: [],
- };
- instanceTreeNodeMap.set(instance.uid, instanceTreeNode);
- treeNodeList.push(instanceTreeNode);
- // Make the instance tree node expanded as default.
- expandedKeysRef.value.push(instanceTreeNode.key);
- }
-
- const databaseTreeNode: TreeNodeForDatabase = {
- type: "database",
- key: `d-${database.uid}`,
- label: database.databaseName,
- isLeaf: false,
- instanceId: instance.uid,
- databaseId: database.uid,
- };
- instanceTreeNode.children?.push(databaseTreeNode);
- databaseTreeNodeList.push(databaseTreeNode);
- }
- treeDataRef.value = treeNodeList;
-});
-
-watch(
- [
- () => schemaList.value,
- () => tableList.value,
- () => databaseDataLoadedSet.value,
- ],
- () => {
- const databaseTreeNodeList: TreeNodeForDatabase[] = [];
- for (const treeNode of treeDataRef.value) {
- if (treeNode.type === "instance") {
- databaseTreeNodeList.push(
- ...(treeNode.children as TreeNodeForDatabase[])
- );
- }
- }
-
- for (const database of databaseList.value) {
- if (!databaseDataLoadedSet.value.has(database.uid)) {
- continue;
- }
- const databaseTreeNode = databaseTreeNodeList.find(
- (treeNode) =>
- treeNode.databaseId === database.uid &&
- databaseDataLoadedSet.value.has(treeNode.databaseId)
- );
- if (isUndefined(databaseTreeNode)) {
- continue;
- }
- const instance = database.instanceEntity;
- const instanceEngine = instance.engine;
- if (instanceEngine === Engine.MYSQL) {
- const schemaList: Schema[] =
- editorStore.databaseSchemaById.get(database.uid)?.schemaList || [];
- const schema = head(schemaList);
- if (!schema) {
- return;
- }
- const tableList: Table[] = schema.tableList;
- if (tableList.length === 0) {
- databaseTreeNode.isLeaf = true;
- databaseTreeNode.children = [];
- } else {
- databaseTreeNode.isLeaf = false;
- databaseTreeNode.children = tableList.map((table) => {
- return {
- type: "table",
- key: `t-${database.uid}-${table.id}`,
- label: table.name,
- children: [],
- isLeaf: true,
- instanceId: instance.uid,
- databaseId: database.uid,
- schemaId: schema.id,
- tableId: table.id,
- };
- });
- }
- } else if (instanceEngine === Engine.POSTGRES) {
- const schemaList: Schema[] =
- editorStore.databaseSchemaById.get(database.uid)?.schemaList || [];
- const schemaTreeNodeList: TreeNodeForSchema[] = [];
- for (const schema of schemaList) {
- const schemaTreeNode: TreeNodeForSchema = {
- type: "schema",
- key: `s-${database.uid}-${schema.id}`,
- label: schema.name,
- instanceId: instance.uid,
- databaseId: database.uid,
- schemaId: schema.id,
- isLeaf: true,
- };
-
- if (schema.tableList.length === 0) {
- schemaTreeNode.isLeaf = true;
- schemaTreeNode.children = [];
- } else {
- schemaTreeNode.isLeaf = false;
- schemaTreeNode.children = schema.tableList.map((table) => {
- return {
- type: "table",
- key: `t-${database.uid}-${table.id}`,
- label: table.name,
- children: [],
- isLeaf: true,
- instanceId: instance.uid,
- databaseId: database.uid,
- schemaId: schema.id,
- tableId: table.id,
- };
- });
- }
- schemaTreeNodeList.push(schemaTreeNode);
- }
-
- if (schemaTreeNodeList.length === 0) {
- databaseTreeNode.isLeaf = true;
- databaseTreeNode.children = [];
- } else {
- databaseTreeNode.isLeaf = false;
- databaseTreeNode.children = schemaTreeNodeList;
- }
- }
- }
- },
- {
- deep: true,
- }
-);
-
-watch(
- () => editorStore.currentTab,
- () => {
- const currentTab = editorStore.currentTab;
- if (!currentTab) {
- selectedKeysRef.value = [];
- return;
- }
-
- if (currentTab.type === SchemaEditorTabType.TabForDatabase) {
- if (currentTab.selectedSchemaId) {
- const key = `s-${currentTab.databaseId}-${currentTab.selectedSchemaId}`;
- selectedKeysRef.value = [key];
- } else {
- const key = `d-${currentTab.databaseId}`;
- selectedKeysRef.value = [key];
- }
- } else if (currentTab.type === SchemaEditorTabType.TabForTable) {
- const databaseTreeNodeKey = `d-${currentTab.databaseId}`;
- if (!expandedKeysRef.value.includes(databaseTreeNodeKey)) {
- expandedKeysRef.value.push(databaseTreeNodeKey);
- }
- const schemaTreeNodeKey = `s-${currentTab.databaseId}-${currentTab.schemaId}`;
- if (!expandedKeysRef.value.includes(schemaTreeNodeKey)) {
- expandedKeysRef.value.push(schemaTreeNodeKey);
- }
- const tableTreeNodeKey = `t-${currentTab.databaseId}-${currentTab.tableId}`;
- selectedKeysRef.value = [tableTreeNodeKey];
- }
-
- if (state.shouldRelocateTreeNode) {
- nextTick(() => {
- treeRef.value?.scrollTo({
- key: selectedKeysRef.value[0],
- });
- });
- }
- }
-);
-
-watch(searchPattern, () => {
- for (const treeNode of treeDataRef.value) {
- if (treeNode.type === "instance" && treeNode.children) {
- for (const databaseTreeNode of treeNode.children) {
- if (databaseTreeNode.children === undefined) {
- loadSubTree(databaseTreeNode);
- }
- }
- }
- }
-});
-
-// Render prefix icons before label text.
-const renderPrefix = ({ option: treeNode }: { option: TreeNode }) => {
- if (treeNode.type === "instance") {
- const instance = instanceStore.getInstanceByUID(treeNode.instanceId);
- const children = [
- h(InstanceV1EngineIcon, {
- instance,
- }),
- h(
- "span",
- {
- class: "text-gray-500 text-sm",
- },
- `(${instance.environmentEntity.title})`
- ),
- ];
-
- return h("span", { class: "flex items-center gap-x-1" }, children);
- } else if (treeNode.type === "database") {
- return h(DatabaseIcon, {
- class: "w-4 h-auto text-gray-400",
- });
- } else if (treeNode.type === "schema") {
- return h(SchemaIcon, {
- class: "w-4 h-auto text-gray-400",
- });
- } else if (treeNode.type === "table") {
- return h(TableIcon, {
- class: "w-4 h-auto text-gray-400",
- });
- }
- return null;
-};
-
-// Render label text.
-const renderLabel = ({ option: treeNode }: { option: TreeNode }) => {
- const additionalClassList: string[] = ["select-none"];
-
- if (treeNode.type === "schema") {
- const schema = editorStore.databaseSchemaById
- .get(treeNode.databaseId)
- ?.schemaList.find((schema) => schema.id === treeNode.schemaId);
-
- if (schema) {
- if (schema.status === "created") {
- additionalClassList.push("text-green-700");
- } else if (schema.status === "dropped") {
- additionalClassList.push("text-red-700 line-through");
- } else {
- if (isSchemaChanged(treeNode.databaseId, treeNode.schemaId)) {
- additionalClassList.push("text-yellow-700");
- }
- }
- }
- } else if (treeNode.type === "table") {
- const table = editorStore.databaseSchemaById
- .get(treeNode.databaseId)
- ?.schemaList.find((schema) => schema.id === treeNode.schemaId)
- ?.tableList.find((table) => table.id === treeNode.tableId);
-
- if (table) {
- if (table.status === "created") {
- additionalClassList.push("text-green-700");
- } else if (table.status === "dropped") {
- additionalClassList.push("text-red-700 line-through");
- } else {
- if (
- isTableChanged(
- treeNode.databaseId,
- treeNode.schemaId,
- treeNode.tableId
- )
- ) {
- additionalClassList.push("text-yellow-700");
- }
- }
- }
- }
-
- return h(
- NEllipsis,
- {
- class: additionalClassList.join(" "),
- },
- () => [
- h("span", {
- innerHTML: getHighlightHTMLByKeyWords(
- escape(treeNode.label),
- escape(searchPattern.value)
- ),
- }),
- ]
- );
-};
-
-// Render a 'menu' icon in the right of the node
-const renderSuffix = ({ option: treeNode }: { option: TreeNode }) => {
- const icon = h(EllipsisIcon, {
- class: "w-4 h-auto text-gray-600",
- onClick: (e) => {
- handleShowDropdown(e, treeNode);
- },
- });
- const instanceEngine = instanceStore.getInstanceByUID(
- treeNode.instanceId
- ).engine;
- if (treeNode.type === "database") {
- return icon;
- } else if (treeNode.type === "schema") {
- if (instanceEngine === Engine.POSTGRES) {
- return icon;
- }
- } else if (treeNode.type === "table") {
- return icon;
- }
- return null;
-};
-
-const handleShowDropdown = (e: MouseEvent, treeNode: TreeNode) => {
- e.preventDefault();
- e.stopPropagation();
- contextMenu.treeNode = treeNode;
- contextMenu.showDropdown = true;
- contextMenu.clientX = e.clientX;
- contextMenu.clientY = e.clientY;
- selectedKeysRef.value = [treeNode.key];
-};
-
-// Dynamic fetching table list when database tree node clicking.
-const loadSubTree = async (treeNode: TreeNode) => {
- if (treeNode.type === "database") {
- const databaseId = treeNode.databaseId;
- if (databaseDataLoadedSet.value.has(databaseId)) {
- return;
- }
-
- databaseDataLoadedSet.value.add(databaseId);
- try {
- const schemaList = await editorStore.fetchSchemaListByDatabaseId(
- databaseId,
- true
- );
- if (schemaList.length === 0) {
- treeNode.children = [];
- treeNode.isLeaf = true;
- }
- } catch (error) {
- useNotificationStore().pushNotification({
- module: "bytebase",
- style: "CRITICAL",
- title: t("schema-editor.message.failed-to-fetch-database-schema"),
- });
- }
- }
-};
-
-// Set event handler to tree nodes.
-const nodeProps = ({ option: treeNode }: { option: TreeNode }) => {
- return {
- async onclick(e: MouseEvent) {
- // Check if clicked on the content part.
- // And ignore the fold/unfold arrow.
- if (isDescendantOf(e.target as Element, ".n-tree-node-content")) {
- state.shouldRelocateTreeNode = false;
-
- if (treeNode.type === "instance") {
- // Toggle instance tree node expanded status.
- const index = expandedKeysRef.value.findIndex(
- (key) => key === treeNode.key
- );
- if (index >= 0) {
- expandedKeysRef.value.splice(index, 1);
- } else {
- expandedKeysRef.value.push(treeNode.key);
- }
- } else if (treeNode.type === "database") {
- await loadSubTree(treeNode);
- const index = expandedKeysRef.value.findIndex(
- (key) => key === treeNode.key
- );
- if (index < 0) {
- expandedKeysRef.value.push(treeNode.key);
- }
- editorStore.addTab({
- id: generateUniqueTabId(),
- type: SchemaEditorTabType.TabForDatabase,
- databaseId: treeNode.databaseId,
- });
- } else if (treeNode.type === "schema") {
- const index = expandedKeysRef.value.findIndex(
- (key) => key === treeNode.key
- );
- if (index < 0) {
- expandedKeysRef.value.push(treeNode.key);
- }
- editorStore.addTab({
- id: generateUniqueTabId(),
- type: SchemaEditorTabType.TabForDatabase,
- databaseId: treeNode.databaseId,
- selectedSchemaId: treeNode.schemaId,
- });
- } else if (treeNode.type === "table") {
- editorStore.addTab({
- id: generateUniqueTabId(),
- type: SchemaEditorTabType.TabForTable,
- databaseId: treeNode.databaseId,
- schemaId: treeNode.schemaId,
- tableId: treeNode.tableId,
- });
- }
-
- nextTick(() => {
- if (treeNode.type === "database") {
- selectedKeysRef.value = [`d-${treeNode.databaseId}`];
- } else if (treeNode.type === "schema") {
- selectedKeysRef.value = [
- `s-${treeNode.databaseId}-${treeNode.schemaId}`,
- ];
- } else if (treeNode.type === "table") {
- selectedKeysRef.value = [
- `t-${treeNode.databaseId}-${treeNode.tableId}`,
- ];
- }
- state.shouldRelocateTreeNode = true;
- });
- } else {
- nextTick(() => {
- selectedKeysRef.value = [];
- });
- }
- },
- async ondblclick() {
- await loadSubTree(treeNode);
- nextTick(() => {
- const index = expandedKeysRef.value.findIndex(
- (key) => key === treeNode.key
- );
- if (index >= 0) {
- expandedKeysRef.value.splice(index, 1);
- } else {
- expandedKeysRef.value.push(treeNode.key);
- }
- });
- },
- oncontextmenu(e: MouseEvent) {
- handleShowDropdown(e, treeNode);
- },
- };
-};
-
-const handleContextMenuDropdownSelect = async (key: string) => {
- const treeNode = contextMenu.treeNode;
- if (treeNode?.type === "database") {
- if (key === "create-table") {
- await loadSubTree(treeNode);
- const instanceEngine = instanceStore.getInstanceByUID(
- treeNode.instanceId
- ).engine;
- if (instanceEngine === Engine.MYSQL) {
- const schemaList: Schema[] =
- editorStore.databaseSchemaById.get(treeNode.databaseId)?.schemaList ||
- [];
- const schema = head(schemaList);
- if (!schema) {
- return;
- }
- state.tableNameModalContext = {
- databaseId: treeNode.databaseId,
- schemaId: schema.id,
- tableId: undefined,
- };
- }
- } else if (key === "create-schema") {
- state.schemaNameModalContext = {
- databaseId: treeNode.databaseId,
- schemaId: undefined,
- };
- }
- } else if (treeNode?.type === "schema") {
- if (key === "create-table") {
- await loadSubTree(treeNode);
- state.tableNameModalContext = {
- databaseId: treeNode.databaseId,
- schemaId: treeNode.schemaId,
- tableId: undefined,
- };
- } else if (key === "rename") {
- state.schemaNameModalContext = {
- databaseId: treeNode.databaseId,
- schemaId: treeNode.schemaId,
- };
- } else if (key === "drop-schema") {
- editorStore.dropSchema(treeNode.databaseId, treeNode.schemaId);
- } else if (key === "restore") {
- editorStore.restoreSchema(treeNode.databaseId, treeNode.schemaId);
- }
- } else if (treeNode?.type === "table") {
- if (key === "rename") {
- state.tableNameModalContext = {
- databaseId: treeNode.databaseId,
- schemaId: treeNode.schemaId,
- tableId: treeNode.tableId,
- };
- } else if (key === "drop") {
- editorStore.dropTable(
- treeNode.databaseId,
- treeNode.schemaId,
- treeNode.tableId
- );
- } else if (key === "restore") {
- editorStore.restoreTable(
- treeNode.databaseId,
- treeNode.schemaId,
- treeNode.tableId
- );
- }
- }
- contextMenu.showDropdown = false;
-};
-
-const handleDropdownClickoutside = (e: MouseEvent) => {
- if (
- !isDescendantOf(e.target as Element, ".n-tree-node-wrapper") ||
- e.button !== 2
- ) {
- selectedKeysRef.value = [];
- contextMenu.showDropdown = false;
- }
-};
-
-const handleExpandedKeysChange = (expandedKeys: string[]) => {
- expandedKeysRef.value = expandedKeys;
-};
-</script>
-
-<style>
-.schema-editor-database-tree .n-tree-node-wrapper {
- @apply !py-px;
-}
-.schema-editor-database-tree .n-tree-node-content__prefix {
- @apply shrink-0 !mr-1;
-}
-.schema-editor-database-tree .n-tree-node-content__text {
- @apply truncate mr-1;
-}
-.schema-editor-database-tree .n-tree-node-content__suffix {
- @apply rounded-sm !hidden hover:opacity-80;
-}
-.schema-editor-database-tree
- .n-tree-node-wrapper:hover
- .n-tree-node-content__suffix {
- @apply !flex;
-}
-.schema-editor-database-tree
- .n-tree-node-wrapper
- .n-tree-node--selected
- .n-tree-node-content__suffix {
- @apply !flex;
-}
-.schema-editor-database-tree .n-tree-node-switcher {
- @apply px-0 !w-4 !h-7;
-}
-</style>
-
-<style scoped>
-.schema-editor-database-tree {
- max-height: calc(100% - 48px);
-}
-</style>
diff --git a/frontend/src/components/SchemaEditor/EmptyTips.vue b/frontend/src/components/SchemaEditor/EmptyTips.vue
deleted file mode 100644
index b74e12488c..0000000000
--- a/frontend/src/components/SchemaEditor/EmptyTips.vue
+++ /dev/null
@@ -1,8 +0,0 @@
-<template>
- <div
- class="w-full h-full flex flex-row justify-center items-center text-gray-600 font-medium"
- >
- <heroicons-solid:pencil-square class="w-4 h-auto mr-2" />
- {{ $t("schema-editor.use-tips") }}
- </div>
-</template>
diff --git a/frontend/src/components/SchemaEditor/Modals/ActionConfirmModal.vue b/frontend/src/components/SchemaEditor/Modals/ActionConfirmModal.vue
deleted file mode 100644
index b68f82a26e..0000000000
--- a/frontend/src/components/SchemaEditor/Modals/ActionConfirmModal.vue
+++ /dev/null
@@ -1,49 +0,0 @@
-<template>
- <BBModal
- :title="props.title"
- class="shadow-inner outline outline-gray-200"
- @close="dismissModal"
- >
- <div class="w-80 mb-6">
- <p>{{ props.description }}</p>
- </div>
- <div class="w-full flex items-center justify-end mt-2 space-x-3 pr-1 pb-1">
- <button type="button" class="btn-cancel" @click="dismissModal">
- {{ $t("common.cancel") }}
- </button>
- <button :class="`btn-${props.style}`" @click="handleConfirmButtonClick">
- {{ $t("common.confirm") }}
- </button>
- </div>
- </BBModal>
-</template>
-
-<script lang="ts" setup>
-const props = defineProps({
- title: {
- type: String,
- default: "",
- },
- description: {
- type: String,
- default: "",
- },
- style: {
- type: String,
- default: "primary",
- },
-});
-
-const emit = defineEmits<{
- (event: "close"): void;
- (event: "confirm"): void;
-}>();
-
-const handleConfirmButtonClick = async () => {
- emit("confirm");
-};
-
-const dismissModal = () => {
- emit("close");
-};
-</script>
diff --git a/frontend/src/components/SchemaEditor/Modals/EditColumnForeignKeyModal.vue b/frontend/src/components/SchemaEditor/Modals/EditColumnForeignKeyModal.vue
deleted file mode 100644
index ecdf04f295..0000000000
--- a/frontend/src/components/SchemaEditor/Modals/EditColumnForeignKeyModal.vue
+++ /dev/null
@@ -1,277 +0,0 @@
-<template>
- <BBModal
- :title="$t('schema-editor.edit-foreign-key')"
- class="shadow-inner outline outline-gray-200"
- @close="dismissModal"
- >
- <div v-if="shouldShowSchemaSelector" class="w-72">
- <p class="mb-2">{{ $t("schema-editor.select-reference-schema") }}</p>
- <BBSelect
- :selected-item="selectedSchema"
- :item-list="schemaList"
- :placeholder="$t('schema-editor.schema.select')"
- :show-prefix-item="true"
- @select-item="(schema: Schema) => state.referencedSchemaId = schema.id"
- >
- <template #menuItem="{ item }">
- {{ item.name }}
- </template>
- </BBSelect>
- </div>
- <div class="w-72">
- <p class="mt-4 mb-2">{{ $t("schema-editor.select-reference-table") }}</p>
- <BBSelect
- :selected-item="selectedTable"
- :item-list="tableList"
- :placeholder="$t('schema-editor.table.select')"
- :show-prefix-item="true"
- @select-item="(table: Table) => state.referencedTableId = table.id"
- >
- <template #menuItem="{ item }">
- {{ item.name }}
- </template>
- </BBSelect>
- </div>
- <div class="w-72">
- <p class="mt-4 mb-2">{{ $t("schema-editor.select-reference-column") }}</p>
- <BBSelect
- :selected-item="selectedColumn"
- :item-list="columnList"
- :placeholder="$t('schema-editor.column.select')"
- :show-prefix-item="true"
- @select-item="(column: Column) => state.referencedColumnId = column.id"
- >
- <template #menuItem="{ item }">
- {{ item.name }}
- </template>
- </BBSelect>
- </div>
- <div
- class="w-full flex items-center justify-between mt-6 space-x-2 pr-1 pb-1"
- >
- <div class="flex items-center justify-start">
- <button
- v-if="foreignKey !== undefined"
- type="button"
- class="btn-danger"
- @click="handleRemoveFKButtonClick"
- >
- Remove
- </button>
- </div>
- <div class="flex items-center justify-end space-x-2">
- <button type="button" class="btn-normal" @click="dismissModal">
- {{ $t("common.cancel") }}
- </button>
- <button class="btn-primary" @click="handleConfirmButtonClick">
- {{ $t("common.save") }}
- </button>
- </div>
- </div>
- </BBModal>
-</template>
-
-<script lang="ts" setup>
-import { isUndefined } from "lodash-es";
-import { v1 as uuidv1 } from "uuid";
-import { computed, onMounted, reactive, watch } from "vue";
-import { BBModal, BBSelect } from "@/bbkit";
-import { useSchemaEditorStore } from "@/store";
-import { UNKNOWN_ID } from "@/types";
-import { Engine } from "@/types/proto/v1/common";
-import {
- Column,
- ForeignKey,
- Schema,
- Table,
-} from "@/types/schemaEditor/atomType";
-
-interface LocalState {
- referencedSchemaId?: string;
- referencedTableId?: string;
- referencedColumnId?: string;
-}
-
-const props = defineProps({
- databaseId: {
- type: String,
- default: String(UNKNOWN_ID),
- },
- schemaId: {
- type: String,
- default: "",
- },
- tableId: {
- type: String,
- default: "",
- },
- columnId: {
- type: String,
- default: "",
- },
-});
-
-const emit = defineEmits<{
- (event: "close"): void;
-}>();
-
-const editorStore = useSchemaEditorStore();
-const databaseSchema = computed(() => {
- return editorStore.databaseSchemaById.get(props.databaseId)!;
-});
-const database = computed(() => databaseSchema.value.database);
-const databaseEngine = computed(() => database.value.instanceEntity.engine);
-const schemaList = computed(() => databaseSchema.value.schemaList);
-const state = reactive<LocalState>({
- referencedSchemaId: props.schemaId,
-});
-
-const schema = computed(() => {
- return editorStore.getSchema(props.databaseId, props.schemaId) as Schema;
-});
-
-const table = computed(() => {
- return editorStore.getTable(props.databaseId, props.schemaId, props.tableId);
-});
-
-const propsColumn = computed(() => {
- return table.value?.columnList.find((column) => column.id === props.columnId);
-});
-
-const foreignKeyList = computed(() => {
- return schema.value?.foreignKeyList.filter(
- (pk) => pk.tableId === props.tableId
- );
-});
-
-const shouldShowSchemaSelector = computed(() => {
- return databaseEngine.value === Engine.POSTGRES;
-});
-
-const selectedSchema = computed(() => {
- return schemaList.value.find(
- (schema) => schema.id === state.referencedSchemaId
- );
-});
-
-const tableList = computed(() => {
- return selectedSchema.value?.tableList || [];
-});
-
-const selectedTable = computed(() => {
- return tableList.value.find(
- (table: Table) => table.id === state.referencedTableId
- );
-});
-
-const columnList = computed(() => {
- if (!selectedTable.value) {
- return [];
- }
-
- return selectedTable.value.columnList.filter(
- (column) =>
- column.id !== props.columnId &&
- column.type.toUpperCase() === propsColumn.value?.type.toUpperCase() &&
- selectedTable.value?.primaryKey.columnIdList.includes(column.id)
- );
-});
-
-const selectedColumn = computed(() => {
- return columnList.value.find(
- (column) => column.id === state.referencedColumnId
- );
-});
-
-const foreignKey = computed(() => {
- for (const fk of foreignKeyList.value) {
- const foundIndex = fk.columnIdList.findIndex(
- (columnId) => columnId === props.columnId
- );
- if (foundIndex > -1) {
- return fk;
- }
- }
- return undefined;
-});
-
-onMounted(() => {
- if (foreignKey.value) {
- const foundIndex = foreignKey.value.columnIdList.findIndex(
- (columnId) => columnId === props.columnId
- );
- if (foundIndex > -1) {
- state.referencedSchemaId = foreignKey.value.referencedSchemaId;
- state.referencedTableId = foreignKey.value.referencedTableId;
- state.referencedColumnId =
- foreignKey.value.referencedColumnIdList[foundIndex];
- }
- }
-});
-
-watch(
- () => state.referencedTableId,
- () => {
- const found = columnList.value.find(
- (column) => column.id === state.referencedColumnId
- );
- if (!found) {
- state.referencedColumnId = undefined;
- }
- }
-);
-
-const handleRemoveFKButtonClick = async () => {
- if (isUndefined(foreignKey.value)) {
- return;
- }
-
- const index = foreignKey.value.columnIdList.findIndex(
- (columnId) => columnId === propsColumn.value?.id
- );
- if (index > -1) {
- foreignKey.value.referencedColumnIdList.splice(index, 1);
- foreignKey.value.columnIdList.splice(index, 1);
- dismissModal();
- }
-};
-
-const handleConfirmButtonClick = async () => {
- if (
- isUndefined(state.referencedSchemaId) ||
- isUndefined(state.referencedTableId) ||
- isUndefined(state.referencedColumnId)
- ) {
- return;
- }
-
- const column = propsColumn.value as Column;
- if (isUndefined(foreignKey.value)) {
- const fk: ForeignKey = {
- name: uuidv1(),
- tableId: props.tableId,
- columnIdList: [column.id],
- referencedSchemaId: state.referencedSchemaId,
- referencedTableId: state.referencedTableId,
- referencedColumnIdList: [state.referencedColumnId],
- };
- schema.value.foreignKeyList.push(fk);
- } else {
- const index = foreignKey.value.columnIdList.findIndex(
- (columnId) => columnId === column.id
- );
- if (index >= 0) {
- foreignKey.value.referencedColumnIdList[index] = state.referencedColumnId;
- foreignKey.value.columnIdList[index] = column.id;
- } else {
- foreignKey.value.referencedColumnIdList.push(state.referencedColumnId);
- foreignKey.value.columnIdList.push(column.id);
- }
- }
- dismissModal();
-};
-
-const dismissModal = () => {
- emit("close");
-};
-</script>
diff --git a/frontend/src/components/SchemaEditor/Modals/SchemaNameModal.vue b/frontend/src/components/SchemaEditor/Modals/SchemaNameModal.vue
deleted file mode 100644
index 7a5febc570..0000000000
--- a/frontend/src/components/SchemaEditor/Modals/SchemaNameModal.vue
+++ /dev/null
@@ -1,145 +0,0 @@
-<template>
- <BBModal
- :title="
- isCreatingSchema
- ? $t('schema-editor.actions.create-schema')
- : $t('schema-editor.actions.rename')
- "
- class="shadow-inner outline outline-gray-200"
- @close="dismissModal"
- >
- <div class="w-72">
- <p>{{ $t("schema-editor.schema.name") }}</p>
- <BBTextField
- class="my-2 w-full"
- :required="true"
- :focus-on-mount="true"
- :value="state.schemaName"
- @input="handleSchemaNameChange"
- />
- </div>
- <div class="w-full flex items-center justify-end mt-2 space-x-3 pr-1 pb-1">
- <button type="button" class="btn-normal" @click="dismissModal">
- {{ $t("common.cancel") }}
- </button>
- <button class="btn-primary" @click="handleConfirmButtonClick">
- {{ isCreatingSchema ? $t("common.create") : $t("common.save") }}
- </button>
- </div>
- </BBModal>
-</template>
-
-<script lang="ts" setup>
-import { computed, onMounted, reactive } from "vue";
-import { useI18n } from "vue-i18n";
-import {
- useSchemaEditorStore,
- useNotificationStore,
- generateUniqueTabId,
-} from "@/store";
-import { SchemaEditorTabType, UNKNOWN_ID } from "@/types";
-import { SchemaMetadata } from "@/types/proto/store/database";
-import { convertSchemaMetadataToSchema } from "@/types/schemaEditor/atomType";
-
-const schemaNameFieldRegexp = /^\S+$/;
-
-interface LocalState {
- schemaName: string;
-}
-
-const props = defineProps({
- databaseId: {
- type: String,
- default: String(UNKNOWN_ID),
- },
- schemaId: {
- type: String,
- default: undefined,
- },
-});
-
-const emit = defineEmits<{
- (event: "close"): void;
-}>();
-
-const { t } = useI18n();
-const editorStore = useSchemaEditorStore();
-const notificationStore = useNotificationStore();
-const state = reactive<LocalState>({
- schemaName: "",
-});
-
-const isCreatingSchema = computed(() => {
- return props.schemaId === undefined;
-});
-
-onMounted(() => {
- if (props.schemaId === undefined) {
- return;
- }
-
- const schema = editorStore.getSchema(props.databaseId, props.schemaId);
- if (schema) {
- state.schemaName = schema.name;
- }
-});
-
-const handleSchemaNameChange = (event: Event) => {
- state.schemaName = (event.target as HTMLInputElement).value;
-};
-
-const handleConfirmButtonClick = async () => {
- if (!schemaNameFieldRegexp.test(state.schemaName)) {
- notificationStore.pushNotification({
- module: "bytebase",
- style: "CRITICAL",
- title: t("schema-editor.message.invalid-schema-name"),
- });
- return;
- }
-
- const databaseId = props.databaseId;
- const databaseSchema = editorStore.databaseSchemaById.get(databaseId);
- if (!databaseSchema) {
- return;
- }
- const schemaNameList =
- databaseSchema.schemaList.map((schema) => schema.name) || [];
- if (schemaNameList.includes(state.schemaName)) {
- notificationStore.pushNotification({
- module: "bytebase",
- style: "CRITICAL",
- title: t("schema-editor.message.duplicated-schema-name"),
- });
- return;
- }
-
- if (isCreatingSchema.value) {
- const schema = convertSchemaMetadataToSchema(
- SchemaMetadata.fromPartial({})
- );
- schema.name = state.schemaName;
- schema.status = "created";
- databaseSchema.schemaList.push(schema);
- editorStore.addTab({
- id: generateUniqueTabId(),
- type: SchemaEditorTabType.TabForDatabase,
- databaseId: databaseId,
- selectedSchemaId: schema.id,
- });
- } else {
- const schema = editorStore.getSchema(
- props.databaseId,
- props.schemaId ?? ""
- );
- if (schema) {
- schema.name = state.schemaName;
- }
- }
- dismissModal();
-};
-
-const dismissModal = () => {
- emit("close");
-};
-</script>
diff --git a/frontend/src/components/SchemaEditor/Modals/TableNameModal.vue b/frontend/src/components/SchemaEditor/Modals/TableNameModal.vue
deleted file mode 100644
index 246950c360..0000000000
--- a/frontend/src/components/SchemaEditor/Modals/TableNameModal.vue
+++ /dev/null
@@ -1,172 +0,0 @@
-<template>
- <BBModal
- :title="
- isCreatingTable
- ? $t('schema-editor.actions.create-table')
- : $t('schema-editor.actions.rename')
- "
- class="shadow-inner outline outline-gray-200"
- @close="dismissModal"
- >
- <div class="w-72">
- <p>{{ $t("schema-editor.table.name") }}</p>
- <BBTextField
- class="my-2 w-full"
- :required="true"
- :focus-on-mount="true"
- :value="state.tableName"
- @input="handleTableNameChange"
- />
- </div>
- <div class="w-full flex items-center justify-end mt-2 space-x-3 pr-1 pb-1">
- <button type="button" class="btn-normal" @click="dismissModal">
- {{ $t("common.cancel") }}
- </button>
- <button class="btn-primary" @click="handleConfirmButtonClick">
- {{ isCreatingTable ? $t("common.create") : $t("common.save") }}
- </button>
- </div>
- </BBModal>
-</template>
-
-<script lang="ts" setup>
-import { computed, onMounted, reactive } from "vue";
-import { useI18n } from "vue-i18n";
-import {
- useSchemaEditorStore,
- useNotificationStore,
- generateUniqueTabId,
- useDatabaseV1Store,
-} from "@/store";
-import { UNKNOWN_ID, SchemaEditorTabType } from "@/types";
-import { ColumnMetadata, TableMetadata } from "@/types/proto/store/database";
-import { Engine } from "@/types/proto/v1/common";
-import {
- convertColumnMetadataToColumn,
- convertTableMetadataToTable,
- Schema,
-} from "@/types/schemaEditor/atomType";
-
-const tableNameFieldRegexp = /^\S+$/;
-
-interface LocalState {
- tableName: string;
-}
-
-const props = defineProps({
- databaseId: {
- type: String,
- default: String(UNKNOWN_ID),
- },
- schemaId: {
- type: String,
- default: "",
- },
- tableId: {
- type: String,
- default: undefined,
- },
-});
-
-const emit = defineEmits<{
- (event: "close"): void;
-}>();
-
-const { t } = useI18n();
-const editorStore = useSchemaEditorStore();
-const notificationStore = useNotificationStore();
-const state = reactive<LocalState>({
- tableName: "",
-});
-
-const isCreatingTable = computed(() => {
- return props.tableId === undefined;
-});
-
-onMounted(() => {
- if (props.tableId === undefined) {
- return;
- }
-
- const table = editorStore.getTable(
- props.databaseId,
- props.schemaId,
- props.tableId
- );
- if (table) {
- state.tableName = table.name;
- }
-});
-
-const handleTableNameChange = (event: Event) => {
- state.tableName = (event.target as HTMLInputElement).value;
-};
-
-const handleConfirmButtonClick = async () => {
- if (!tableNameFieldRegexp.test(state.tableName)) {
- notificationStore.pushNotification({
- module: "bytebase",
- style: "CRITICAL",
- title: t("schema-editor.message.invalid-table-name"),
- });
- return;
- }
-
- const databaseId = props.databaseId;
- const database = useDatabaseV1Store().getDatabaseByUID(databaseId);
- const instanceEngine = database.instanceEntity.engine;
- const schema = editorStore.getSchema(databaseId, props.schemaId) as Schema;
- const tableNameList = schema.tableList.map((table) => table.name);
- if (tableNameList.includes(state.tableName)) {
- notificationStore.pushNotification({
- module: "bytebase",
- style: "CRITICAL",
- title: t("schema-editor.message.duplicated-table-name"),
- });
- return;
- }
-
- if (isCreatingTable.value) {
- const table = convertTableMetadataToTable(TableMetadata.fromPartial({}));
- table.name = state.tableName;
- table.status = "created";
-
- const column = convertColumnMetadataToColumn(
- ColumnMetadata.fromPartial({})
- );
- column.name = "id";
- if (instanceEngine === Engine.POSTGRES) {
- column.type = "INTEGER";
- } else {
- column.type = "INT";
- }
- column.comment = "ID";
- column.status = "created";
- table.columnList.push(column);
- table.primaryKey.columnIdList.push(column.id);
-
- schema.tableList.push(table);
- editorStore.addTab({
- id: generateUniqueTabId(),
- type: SchemaEditorTabType.TabForTable,
- databaseId: props.databaseId,
- schemaId: props.schemaId,
- tableId: table.id,
- });
- } else {
- const table = editorStore.getTable(
- props.databaseId,
- props.schemaId,
- props.tableId ?? ""
- );
- if (table) {
- table.name = state.tableName;
- }
- }
- dismissModal();
-};
-
-const dismissModal = () => {
- emit("close");
-};
-</script>
diff --git a/frontend/src/components/SchemaEditor/Panels/DatabaseEditor.vue b/frontend/src/components/SchemaEditor/Panels/DatabaseEditor.vue
deleted file mode 100644
index c9c43b882b..0000000000
--- a/frontend/src/components/SchemaEditor/Panels/DatabaseEditor.vue
+++ /dev/null
@@ -1,531 +0,0 @@
-<template>
- <div class="flex flex-col w-full h-full overflow-y-auto">
- <div class="py-2 w-full flex flex-row justify-between items-center">
- <div>
- <div
- v-if="state.selectedSubtab === 'table-list'"
- class="w-full flex justify-between items-center space-x-2"
- >
- <div class="flex flex-row justify-start items-center">
- <div
- v-if="shouldShowSchemaSelector"
- class="ml-2 flex flex-row justify-start items-center mr-3 text-sm"
- >
- <span class="mr-1">Schema:</span>
- <n-select
- v-model:value="state.selectedSchemaId"
- class="min-w-[8rem]"
- :options="schemaSelectorOptionList"
- />
- </div>
- <button
- class="flex flex-row justify-center items-center border px-3 py-1 leading-6 rounded text-sm hover:opacity-80 disabled:cursor-not-allowed disabled:opacity-60"
- :disabled="!allowCreateTable"
- @click="handleCreateNewTable"
- >
- <heroicons-outline:plus class="w-4 h-auto mr-1 text-gray-400" />
- {{ $t("schema-editor.actions.create-table") }}
- </button>
- </div>
- </div>
- </div>
- <div class="flex justify-end items-center">
- <NInput
- v-if="state.selectedSubtab === 'table-list'"
- v-model:value="searchPattern"
- class="!w-48 mr-3"
- :placeholder="$t('schema-editor.search-table')"
- >
- <template #prefix>
- <heroicons-outline:search class="w-4 h-auto text-gray-300" />
- </template>
- </NInput>
- <div
- class="flex flex-row justify-end items-center bg-gray-100 p-1 rounded"
- >
- <button
- class="px-2 leading-7 text-sm text-gray-500 cursor-pointer select-none rounded flex justify-center items-center"
- :class="
- state.selectedSubtab === 'table-list' &&
- 'bg-gray-200 text-gray-800'
- "
- @click="handleChangeTab('table-list')"
- >
- <heroicons-outline:queue-list class="inline w-4 h-auto mr-1" />
- {{ $t("schema-editor.tables") }}
- </button>
- <button
- class="px-2 leading-7 text-sm text-gray-500 cursor-pointer select-none rounded flex justify-center items-center"
- :class="
- state.selectedSubtab === 'raw-sql' && 'bg-gray-200 text-gray-800'
- "
- @click="handleChangeTab('raw-sql')"
- >
- <heroicons-outline:clipboard class="inline w-4 h-auto mr-1" />
- {{ $t("schema-editor.raw-sql") }}
- </button>
- <button
- class="px-2 leading-7 text-sm text-gray-500 cursor-pointer select-none rounded flex justify-center items-center"
- :class="
- state.selectedSubtab === 'schema-diagram' &&
- 'bg-gray-200 text-gray-800'
- "
- @click="handleChangeTab('schema-diagram')"
- >
- <SchemaDiagramIcon class="mr-1" />
- {{ $t("schema-diagram.self") }}
- </button>
- </div>
- </div>
- </div>
-
- <!-- List view -->
- <template v-if="state.selectedSubtab === 'table-list'">
- <!-- table list -->
- <div
- class="w-full h-auto grid auto-rows-auto border-y relative overflow-y-auto"
- >
- <!-- table header -->
- <div
- class="sticky top-0 z-10 grid grid-cols-[repeat(6,_minmax(0,_1fr))_32px] w-full border-b text-sm leading-6 select-none bg-gray-50 text-gray-400"
- >
- <span
- v-for="header in tableHeaderList"
- :key="header.key"
- class="table-header-item-container"
- >{{ header.label }}</span
- >
- <span></span>
- </div>
- <!-- table body -->
- <div class="w-full">
- <div
- v-for="(table, index) in shownTableList"
- :key="`${index}-${table.name}`"
- class="grid grid-cols-[repeat(6,_minmax(0,_1fr))_32px] text-sm even:bg-gray-50"
- :class="
- isDroppedTable(table) && 'text-red-700 !bg-red-50 opacity-70'
- "
- >
- <div class="table-body-item-container">
- <NEllipsis
- class="w-full cursor-pointer leading-6 my-2 hover:text-accent"
- >
- <span @click="handleTableItemClick(table)">
- {{ table.name }}
- </span>
- </NEllipsis>
- </div>
- <div class="table-body-item-container">
- {{ table.rowCount }}
- </div>
- <div class="table-body-item-container">
- {{ bytesToString(table.dataSize) }}
- </div>
- <div class="table-body-item-container">
- {{ table.engine }}
- </div>
- <div class="table-body-item-container">
- {{ table.collation }}
- </div>
- <div class="table-body-item-container">
- {{ table.comment }}
- </div>
- <div class="w-full flex justify-start items-center">
- <NTooltip v-if="!isDroppedTable(table)" trigger="hover" to="body">
- <template #trigger>
- <heroicons:trash
- class="w-[14px] h-auto text-gray-500 cursor-pointer hover:opacity-80"
- @click="handleDropTable(table)"
- />
- </template>
- <span>{{ $t("schema-editor.actions.drop-table") }}</span>
- </NTooltip>
- <NTooltip v-else trigger="hover" to="body">
- <template #trigger>
- <heroicons:arrow-uturn-left
- class="w-[14px] h-auto text-gray-500 cursor-pointer hover:opacity-80"
- @click="handleRestoreTable(table)"
- />
- </template>
- <span>{{ $t("schema-editor.actions.restore") }}</span>
- </NTooltip>
- </div>
- </div>
- </div>
- </div>
- </template>
- <div
- v-else-if="state.selectedSubtab === 'raw-sql'"
- class="w-full h-full overflow-y-auto"
- >
- <div
- v-if="state.isFetchingDDL"
- class="w-full h-full min-h-[64px] flex justify-center items-center"
- >
- <BBSpin />
- </div>
- <template v-else>
- <HighlightCodeBlock
- v-if="state.statement !== ''"
- class="text-sm px-3 py-2 whitespace-pre-wrap break-all"
- language="sql"
- :code="state.statement"
- ></HighlightCodeBlock>
- <div v-else class="flex px-3 py-2 italic text-sm text-gray-600">
- {{ $t("schema-editor.nothing-changed") }}
- </div>
- </template>
- </div>
- <template v-else-if="state.selectedSubtab === 'schema-diagram'">
- <SchemaDiagram
- :key="currentTab.databaseId"
- :database="databaseV1"
- :database-metadata="databaseMetadata"
- :schema-status="schemaStatus"
- :table-status="tableStatus"
- :column-status="columnStatus"
- :editable="true"
- @edit-table="tryEditTable"
- @edit-column="tryEditColumn"
- />
- </template>
- </div>
-
- <TableNameModal
- v-if="state.tableNameModalContext !== undefined"
- :database-id="state.tableNameModalContext.databaseId"
- :schema-id="state.tableNameModalContext.schemaId"
- :table-name="state.tableNameModalContext.tableName"
- @close="state.tableNameModalContext = undefined"
- />
-</template>
-
-<script lang="ts" setup>
-import { head } from "lodash-es";
-import { NEllipsis, NTooltip } from "naive-ui";
-import scrollIntoView from "scroll-into-view-if-needed";
-import { computed, nextTick, reactive, ref, watch } from "vue";
-import { useI18n } from "vue-i18n";
-import HighlightCodeBlock from "@/components/HighlightCodeBlock";
-import { SchemaDiagram, SchemaDiagramIcon } from "@/components/SchemaDiagram";
-import {
- generateUniqueTabId,
- useDatabaseV1Store,
- useNotificationStore,
- useSchemaEditorStore,
-} from "@/store";
-import {
- DatabaseTabContext,
- DatabaseSchema,
- SchemaEditorTabType,
- DatabaseEdit,
-} from "@/types";
-import {
- ColumnMetadata,
- SchemaMetadata,
- TableMetadata,
-} from "@/types/proto/store/database";
-import { Engine } from "@/types/proto/v1/common";
-import { Table } from "@/types/schemaEditor/atomType";
-import { bytesToString } from "@/utils";
-import {
- checkHasSchemaChanges,
- diffSchema,
- mergeDiffResults,
-} from "@/utils/schemaEditor/diffSchema";
-import TableNameModal from "../Modals/TableNameModal.vue";
-import { useMetadataForDiagram } from "../utils/useMetadataForDiagram";
-
-type SubtabType = "table-list" | "schema-diagram" | "raw-sql";
-
-interface LocalState {
- selectedSubtab: SubtabType;
- selectedSchemaId: string;
- isFetchingDDL: boolean;
- statement: string;
- tableNameModalContext?: {
- databaseId: string;
- schemaId: string;
- tableName: string | undefined;
- };
-}
-
-const { t } = useI18n();
-const editorStore = useSchemaEditorStore();
-const notificationStore = useNotificationStore();
-const searchPattern = ref("");
-const currentTab = computed(() => editorStore.currentTab as DatabaseTabContext);
-const state = reactive<LocalState>({
- selectedSubtab:
- (currentTab.value.selectedSubtab as SubtabType) || "table-list",
- selectedSchemaId: "",
- isFetchingDDL: false,
- statement: "",
-});
-const databaseSchema = computed(() => {
- return editorStore.databaseSchemaById.get(
- currentTab.value.databaseId
- ) as DatabaseSchema;
-});
-const database = computed(() => databaseSchema.value.database);
-const databaseV1 = computed(() => {
- return useDatabaseV1Store().getDatabaseByUID(database.value.uid);
-});
-const databaseEngine = computed(() => database.value.instanceEntity.engine);
-const schemaList = computed(() => {
- return databaseSchema.value.schemaList;
-});
-const selectedSchema = computed(() => {
- return schemaList.value.find(
- (schema) => schema.id === state.selectedSchemaId
- );
-});
-const tableList = computed(() => {
- return selectedSchema.value?.tableList ?? [];
-});
-const shownTableList = computed(() => {
- return tableList.value.filter((table) =>
- table.name.includes(searchPattern.value.trim())
- );
-});
-
-const shouldShowSchemaSelector = computed(() => {
- return databaseEngine.value === Engine.POSTGRES;
-});
-
-const allowCreateTable = computed(() => {
- if (databaseEngine.value === Engine.POSTGRES) {
- return (
- schemaList.value.length > 0 &&
- selectedSchema.value &&
- selectedSchema.value.status !== "dropped"
- );
- }
- return true;
-});
-
-const schemaSelectorOptionList = computed(() => {
- const optionList = [];
- for (const schema of schemaList.value) {
- optionList.push({
- label: schema.name,
- value: schema.id,
- });
- }
- return optionList;
-});
-
-const tableHeaderList = computed(() => {
- return [
- {
- key: "name",
- label: t("schema-editor.database.name"),
- },
- {
- key: "raw-count",
- label: t("schema-editor.database.row-count"),
- },
- {
- key: "data-size",
- label: t("schema-editor.database.data-size"),
- },
- {
- key: "engine",
- label: t("schema-editor.database.engine"),
- },
- {
- key: "collation",
- label: t("schema-editor.database.collation"),
- },
- {
- key: "comment",
- label: t("schema-editor.database.comment"),
- },
- ];
-});
-
-watch(
- [() => currentTab.value, () => schemaList],
- () => {
- const schemaIdList = schemaList.value.map((schema) => schema.id);
- if (
- currentTab.value &&
- currentTab.value.selectedSchemaId &&
- schemaIdList.includes(currentTab.value.selectedSchemaId)
- ) {
- state.selectedSchemaId = currentTab.value.selectedSchemaId;
- } else {
- state.selectedSchemaId = head(schemaIdList) || "";
- }
- },
- {
- immediate: true,
- deep: true,
- }
-);
-
-watch(
- () => state.selectedSubtab,
- async () => {
- currentTab.value.selectedSubtab = state.selectedSubtab;
- if (state.selectedSubtab === "raw-sql") {
- state.isFetchingDDL = true;
- const databaseEditList: DatabaseEdit[] = [];
- for (const schema of databaseSchema.value.schemaList) {
- const originSchema = databaseSchema.value.originSchemaList.find(
- (originSchema) => originSchema.id === schema.id
- );
- const diffSchemaResult = diffSchema(
- database.value.uid,
- originSchema,
- schema
- );
- if (checkHasSchemaChanges(diffSchemaResult)) {
- const index = databaseEditList.findIndex(
- (edit) => String(edit.databaseId) === database.value.uid
- );
- if (index !== -1) {
- databaseEditList[index] = {
- databaseId: Number(database.value.uid),
- ...mergeDiffResults([diffSchemaResult, databaseEditList[index]]),
- };
- } else {
- databaseEditList.push({
- databaseId: Number(database.value.uid),
- ...diffSchemaResult,
- });
- }
- }
- }
-
- if (databaseEditList.length > 0) {
- const statementList: string[] = [];
- for (const databaseEdit of databaseEditList) {
- const databaseEditResult = await editorStore.postDatabaseEdit(
- databaseEdit
- );
- if (databaseEditResult.validateResultList.length > 0) {
- notificationStore.pushNotification({
- module: "bytebase",
- style: "CRITICAL",
- title: "Invalid request",
- description: databaseEditResult.validateResultList
- .map((result) => result.message)
- .join("\n"),
- });
- state.statement = "";
- return;
- }
- statementList.push(databaseEditResult.statement);
- }
- state.statement = statementList.join("\n");
- } else {
- state.statement = "";
- }
- state.isFetchingDDL = false;
- }
- },
- {
- immediate: true,
- }
-);
-
-const isDroppedTable = (table: Table) => {
- return table.status === "dropped";
-};
-
-const handleChangeTab = (tab: SubtabType) => {
- state.selectedSubtab = tab;
-};
-
-const handleCreateNewTable = () => {
- const selectedSchema = schemaList.value.find(
- (schema) => schema.id === state.selectedSchemaId
- );
- if (selectedSchema) {
- state.tableNameModalContext = {
- databaseId: database.value.uid,
- schemaId: selectedSchema.id,
- tableName: undefined,
- };
- }
-};
-
-const handleTableItemClick = (table: Table) => {
- editorStore.addTab({
- id: generateUniqueTabId(),
- type: SchemaEditorTabType.TabForTable,
- databaseId: database.value.uid,
- schemaId: state.selectedSchemaId,
- tableId: table.id,
- });
-};
-
-const handleDropTable = (table: Table) => {
- editorStore.dropTable(database.value.uid, state.selectedSchemaId, table.id);
-};
-
-const handleRestoreTable = (table: Table) => {
- editorStore.restoreTable(
- database.value.uid,
- state.selectedSchemaId,
- table.id
- );
-};
-
-const {
- databaseMetadata,
- schemaStatus,
- tableStatus,
- columnStatus,
- editableSchema,
- editableTable,
- editableColumn,
-} = useMetadataForDiagram(databaseSchema);
-
-const tryEditTable = async (
- schemaMeta: SchemaMetadata,
- tableMeta: TableMetadata
-) => {
- const schema = editableSchema(schemaMeta);
- const table = editableTable(tableMeta);
- if (schema && table) {
- state.selectedSchemaId = schema.id;
- await nextTick();
- handleTableItemClick(table);
- }
-};
-
-const tryEditColumn = async (
- schemaMeta: SchemaMetadata,
- tableMeta: TableMetadata,
- columnMeta: ColumnMetadata,
- target: "name" | "type"
-) => {
- const schema = editableSchema(schemaMeta);
- const table = editableTable(tableMeta);
- const column = editableColumn(columnMeta);
- if (schema && table && column) {
- await tryEditTable(schemaMeta, tableMeta);
- await nextTick();
- const container = document.querySelector("#table-editor-container");
- const input = container?.querySelector(
- `.column-${column.id} .column-${target}-input`
- ) as HTMLInputElement | undefined;
- if (input) {
- input.focus();
- scrollIntoView(input);
- }
- }
-};
-</script>
-
-<style scoped>
-.table-header-item-container {
- @apply py-2 px-3;
-}
-.table-body-item-container {
- @apply w-full h-10 box-border p-px pl-3 pr-4 relative truncate leading-10;
-}
-</style>
diff --git a/frontend/src/components/SchemaEditor/Panels/TableEditor.vue b/frontend/src/components/SchemaEditor/Panels/TableEditor.vue
deleted file mode 100644
index 0950431723..0000000000
--- a/frontend/src/components/SchemaEditor/Panels/TableEditor.vue
+++ /dev/null
@@ -1,837 +0,0 @@
-<template>
- <div class="flex flex-col w-full h-full overflow-y-auto">
- <div class="py-2 w-full flex flex-row justify-between items-center">
- <div>
- <div
- v-if="state.selectedSubtab === 'column-list'"
- class="w-full flex justify-between items-center space-x-2"
- >
- <button
- class="flex flex-row justify-center items-center border px-3 py-1 leading-6 text-sm text-gray-700 rounded cursor-pointer hover:opacity-80 disabled:cursor-not-allowed disabled:opacity-60"
- :disabled="disableChangeTable"
- @click="handleAddColumn"
- >
- <heroicons-outline:plus class="w-4 h-auto mr-1 text-gray-400" />
- {{ $t("schema-editor.actions.add-column") }}
- </button>
- <button
- class="flex flex-row justify-center items-center border px-3 py-1 leading-6 text-sm text-gray-700 rounded cursor-pointer hover:opacity-80 disabled:cursor-not-allowed disabled:opacity-60"
- :disabled="disableChangeTable"
- @click="state.showSchemaTemplateDrawer = true"
- >
- <FeatureBadge feature="bb.feature.schema-template" />
- <heroicons-outline:plus class="w-4 h-auto mr-1 text-gray-400" />
- {{ $t("schema-editor.actions.add-from-template") }}
- </button>
- <button
- v-if="table.status !== 'created'"
- class="flex flex-row justify-center items-center border px-3 py-1 leading-6 text-sm text-gray-700 rounded cursor-pointer hover:opacity-80 disabled:cursor-not-allowed disabled:opacity-60"
- :disabled="!allowResetTable"
- @click="handleDiscardChanges"
- >
- <heroicons-solid:arrow-uturn-left
- class="w-4 h-auto mr-1 text-gray-400"
- />
- {{ $t("schema-editor.actions.reset") }}
- </button>
- </div>
- </div>
- <div class="flex justify-end items-center">
- <NInput
- v-if="state.selectedSubtab === 'column-list'"
- v-model:value="searchPattern"
- class="!w-48 mr-3"
- :placeholder="$t('schema-editor.search-column')"
- >
- <template #prefix>
- <heroicons-outline:search class="w-4 h-auto text-gray-300" />
- </template>
- </NInput>
- <div
- class="flex flex-row justify-end items-center bg-gray-100 p-1 rounded"
- >
- <button
- class="px-2 leading-7 text-sm text-gray-500 cursor-pointer select-none rounded flex justify-center items-center"
- :class="
- state.selectedSubtab === 'column-list' &&
- 'bg-gray-200 text-gray-800'
- "
- @click="handleChangeTab('column-list')"
- >
- <heroicons-outline:queue-list class="inline w-4 h-auto mr-1" />
- {{ $t("schema-editor.columns") }}
- </button>
- <button
- class="px-2 leading-7 text-sm text-gray-500 cursor-pointer select-none rounded flex justify-center items-center"
- :class="
- state.selectedSubtab === 'raw-sql' && 'bg-gray-200 text-gray-800'
- "
- @click="handleChangeTab('raw-sql')"
- >
- <heroicons-outline:clipboard class="inline w-4 h-auto mr-1" />
- {{ $t("schema-editor.raw-sql") }}
- </button>
- </div>
- </div>
- </div>
-
- <template v-if="state.selectedSubtab === 'column-list'">
- <!-- column table -->
- <div
- id="table-editor-container"
- ref="tableEditorContainerRef"
- class="w-full h-auto grid auto-rows-auto border-y relative overflow-y-auto"
- >
- <!-- column table header -->
- <div
- class="sticky top-0 z-10 grid grid-cols-[repeat(4,_minmax(0,_1fr))_repeat(2,_96px)_minmax(0,_1fr)_32px] w-full text-sm leading-6 select-none bg-gray-50 text-gray-400"
- :class="shownColumnList.length > 0 && 'border-b'"
- >
- <span
- v-for="header in columnHeaderList"
- :key="header.key"
- class="table-header-item-container"
- >{{ header.label }}</span
- >
- <span></span>
- </div>
- <!-- column table body -->
- <div class="w-full">
- <div
- v-for="(column, index) in shownColumnList"
- :key="`${index}-${column.id}`"
- class="grid grid-cols-[repeat(4,_minmax(0,_1fr))_repeat(2,_96px)_minmax(0,_1fr)_32px] gr text-sm even:bg-gray-50"
- :class="[
- `column-${column.id}`,
- getColumnItemComputedClassList(column),
- ]"
- >
- <div class="table-body-item-container">
- <input
- v-model="column.name"
- :disabled="disableAlterColumn(column)"
- placeholder="column name"
- class="column-field-input column-name-input"
- type="text"
- />
- </div>
- <div
- class="table-body-item-container flex flex-row justify-between items-center"
- >
- <input
- v-model="column.type"
- :disabled="
- disableAlterColumn(column) ||
- schemaTemplateColumnTypes.length > 0
- "
- placeholder="column type"
- class="column-field-input column-type-input !pr-8"
- type="text"
- />
- <NDropdown
- trigger="click"
- :disabled="disableAlterColumn(column)"
- :options="dataTypeOptions"
- @select="(dataType: string) => (column.type = dataType)"
- >
- <button class="absolute right-5">
- <heroicons-solid:chevron-up-down
- class="w-4 h-auto text-gray-400"
- />
- </button>
- </NDropdown>
- </div>
- <div
- class="table-body-item-container flex flex-row justify-between items-center"
- >
- <input
- v-model="column.default"
- :disabled="disableAlterColumn(column)"
- :placeholder="column.default === undefined ? 'EMPTY' : 'NULL'"
- class="column-field-input !pr-8"
- type="text"
- />
- <NDropdown
- trigger="click"
- :disabled="disableAlterColumn(column)"
- :options="dataDefaultOptions"
- @select="(defaultString:string)=>handleColumnDefaultFieldChange(column, defaultString)"
- >
- <button class="absolute right-5">
- <heroicons-solid:chevron-up-down
- class="w-4 h-auto text-gray-400"
- />
- </button>
- </NDropdown>
- </div>
- <div class="table-body-item-container">
- <input
- v-model="column.comment"
- :disabled="disableAlterColumn(column)"
- placeholder="comment"
- class="column-field-input"
- type="text"
- />
- </div>
- <div
- class="table-body-item-container flex justify-start items-center"
- >
- <BBCheckbox
- class="ml-3"
- :value="!column.nullable"
- :disabled="
- disableAlterColumn(column) || isColumnPrimaryKey(column)
- "
- @toggle="(value) => (column.nullable = !value)"
- />
- </div>
- <div
- class="table-body-item-container flex justify-start items-center"
- >
- <BBCheckbox
- class="ml-3"
- :value="isColumnPrimaryKey(column)"
- :disabled="disableAlterColumn(column)"
- @toggle="(value) => setColumnPrimaryKey(column, value)"
- />
- </div>
- <div
- class="table-body-item-container foreign-key-field flex justify-start items-center"
- >
- <span
- v-if="checkColumnHasForeignKey(column)"
- class="column-field-text cursor-pointer !w-auto hover:opacity-80"
- @click="gotoForeignKeyReferencedTable(column)"
- >
- {{ getReferencedForeignKeyName(column) }}
- </span>
- <span
- v-else
- class="column-field-text italic text-gray-400 !w-auto"
- >EMPTY</span
- >
- <button
- class="foreign-key-edit-button hidden cursor-pointer hover:opacity-80 disabled:cursor-not-allowed disabled:opacity-60"
- :disabled="disableAlterColumn(column)"
- @click="handleEditColumnForeignKey(column)"
- >
- <heroicons:pencil-square class="w-4 h-auto text-gray-400" />
- </button>
- </div>
- <div class="w-full flex justify-start items-center">
- <n-tooltip v-if="!isDroppedColumn(column)" trigger="hover">
- <template #trigger>
- <button
- :disabled="disableChangeTable"
- class="text-gray-500 cursor-pointer hover:opacity-80 disabled:cursor-not-allowed disabled:opacity-60"
- @click="handleDropColumn(column)"
- >
- <heroicons:trash class="w-4 h-auto" />
- </button>
- </template>
- <span>{{ $t("schema-editor.actions.drop-column") }}</span>
- </n-tooltip>
- <n-tooltip v-else trigger="hover">
- <template #trigger>
- <button
- class="text-gray-500 cursor-pointer hover:opacity-80 disabled:cursor-not-allowed disabled:opacity-60"
- :disabled="disableChangeTable"
- @click="handleRestoreColumn(column)"
- >
- <heroicons:arrow-uturn-left class="w-4 h-auto" />
- </button>
- </template>
- <span>{{ $t("schema-editor.actions.restore") }}</span>
- </n-tooltip>
- </div>
- </div>
- </div>
- </div>
- </template>
- <div
- v-else-if="state.selectedSubtab === 'raw-sql'"
- class="w-full h-full overflow-y-auto"
- >
- <div
- v-if="state.isFetchingDDL"
- class="w-full h-full min-h-[64px] flex justify-center items-center"
- >
- <BBSpin />
- </div>
- <template v-else>
- <HighlightCodeBlock
- v-if="state.statement !== ''"
- class="text-sm px-3 py-2 whitespace-pre-wrap break-all"
- language="sql"
- :code="state.statement"
- ></HighlightCodeBlock>
- <div v-else class="flex px-3 py-2 italic text-sm text-gray-600">
- {{ $t("schema-editor.nothing-changed") }}
- </div>
- </template>
- </div>
- </div>
-
- <EditColumnForeignKeyModal
- v-if="state.showEditColumnForeignKeyModal && editForeignKeyColumn"
- :database-id="currentTab.databaseId"
- :schema-id="schema.id"
- :table-id="table.id"
- :column-id="editForeignKeyColumn.id"
- @close="state.showEditColumnForeignKeyModal = false"
- />
- <Drawer
- :show="state.showSchemaTemplateDrawer"
- @close="state.showSchemaTemplateDrawer = false"
- >
- <DrawerContent :title="$t('schema-template.field-template.self')">
- <div class="w-[calc(100vw-36rem)] min-w-[64rem] max-w-[calc(100vw-8rem)]">
- <FieldTemplates
- :readonly="true"
- :engine="databaseEngine"
- @apply="handleApplyColumnTemplate"
- />
- </div>
- </DrawerContent>
- </Drawer>
- <FeatureModal
- feature="bb.feature.schema-template"
- :open="state.showFeatureModal"
- @cancel="state.showFeatureModal = false"
- />
-</template>
-
-<script lang="ts" setup>
-import { cloneDeep, isUndefined, flatten } from "lodash-es";
-import { NDropdown } from "naive-ui";
-import scrollIntoView from "scroll-into-view-if-needed";
-import { v1 as uuidv1 } from "uuid";
-import { computed, nextTick, reactive, ref, watch } from "vue";
-import { useI18n } from "vue-i18n";
-import { BBCheckbox, BBSpin } from "@/bbkit";
-import HighlightCodeBlock from "@/components/HighlightCodeBlock";
-import { Drawer, DrawerContent } from "@/components/v2";
-import {
- hasFeature,
- generateUniqueTabId,
- useNotificationStore,
- useSchemaEditorStore,
- useSettingV1Store,
-} from "@/store/modules";
-import { TableTabContext } from "@/types";
-import { Engine } from "@/types/proto/v1/common";
-import { ColumnMetadata } from "@/types/proto/v1/database_service";
-import { SchemaTemplateSetting_FieldTemplate } from "@/types/proto/v1/setting_service";
-import { DatabaseEdit, SchemaEditorTabType } from "@/types/schemaEditor";
-import {
- Column,
- Table,
- Schema,
- convertColumnMetadataToColumn,
- ForeignKey,
-} from "@/types/schemaEditor/atomType";
-import { getDataTypeSuggestionList } from "@/utils";
-import { diffSchema } from "@/utils/schemaEditor/diffSchema";
-import FieldTemplates from "@/views/SchemaTemplate/FieldTemplates.vue";
-import EditColumnForeignKeyModal from "../Modals/EditColumnForeignKeyModal.vue";
-import { isColumnChanged } from "../utils/column";
-import { isTableChanged } from "../utils/table";
-
-type SubtabType = "column-list" | "raw-sql";
-
-interface LocalState {
- selectedSubtab: SubtabType;
- isFetchingDDL: boolean;
- statement: string;
- showEditColumnForeignKeyModal: boolean;
- showSchemaTemplateDrawer: boolean;
- showFeatureModal: boolean;
-}
-
-const { t } = useI18n();
-const settingStore = useSettingV1Store();
-const editorStore = useSchemaEditorStore();
-const notificationStore = useNotificationStore();
-const currentTab = computed(() => editorStore.currentTab as TableTabContext);
-const databaseSchema = editorStore.databaseSchemaById.get(
- currentTab.value.databaseId
-)!;
-const state = reactive<LocalState>({
- selectedSubtab:
- (currentTab.value.selectedSubtab as SubtabType) || "column-list",
- isFetchingDDL: false,
- statement: "",
- showEditColumnForeignKeyModal: false,
- showSchemaTemplateDrawer: false,
- showFeatureModal: false,
-});
-
-const table = ref(editorStore.getTableWithTableTab(currentTab.value) as Table);
-const schema = computed(() => {
- return databaseSchema.schemaList.find(
- (schema) => schema.id === currentTab.value.schemaId
- ) as Schema;
-});
-const foreignKeyList = computed(() => {
- return schema.value.foreignKeyList.filter(
- (pk) => pk.tableId === currentTab.value.tableId
- ) as ForeignKey[];
-});
-
-const searchPattern = ref("");
-const tableEditorContainerRef = ref<HTMLDivElement>();
-const editForeignKeyColumn = ref<Column>();
-
-const shownColumnList = computed(() => {
- return table.value.columnList.filter((column) =>
- column.name.includes(searchPattern.value.trim())
- );
-});
-const isDroppedSchema = computed(() => {
- return schema.value.status === "dropped";
-});
-
-const isDroppedTable = computed(() => {
- return table.value.status === "dropped";
-});
-
-const allowResetTable = computed(() => {
- if (table.value.status === "created") {
- return false;
- }
-
- return (
- isTableChanged(
- currentTab.value.databaseId,
- currentTab.value.schemaId,
- currentTab.value.tableId
- ) || isDroppedTable.value
- );
-});
-
-const columnHeaderList = computed(() => {
- return [
- {
- key: "name",
- label: t("schema-editor.column.name"),
- },
- {
- key: "type",
- label: t("schema-editor.column.type"),
- },
- {
- key: "default",
- label: t("schema-editor.column.default"),
- },
- {
- key: "comment",
- label: t("schema-editor.column.comment"),
- },
- {
- key: "nullable",
- label: t("schema-editor.column.not-null"),
- },
- {
- key: "primary",
- label: t("schema-editor.column.primary"),
- },
- {
- key: "foreign_key",
- label: t("schema-editor.column.foreign-key"),
- },
- ];
-});
-
-const databaseEngine = computed(() => {
- return databaseSchema.database.instanceEntity.engine;
-});
-
-const schemaTemplateColumnTypes = computed(() => {
- const setting = settingStore.getSettingByName("bb.workspace.schema-template");
- const columnTypes = setting?.value?.schemaTemplateSettingValue?.columnTypes;
- if (columnTypes && columnTypes.length > 0) {
- const columnType = columnTypes.find(
- (columnType) => columnType.engine === databaseEngine.value
- );
- if (columnType && columnType.enabled) {
- return columnType.types;
- }
- }
- return [];
-});
-
-const dataTypeOptions = computed(() => {
- if (schemaTemplateColumnTypes.value.length > 0) {
- return schemaTemplateColumnTypes.value.map((columnType) => {
- return {
- label: columnType,
- key: columnType,
- };
- });
- }
-
- return getDataTypeSuggestionList(databaseEngine.value).map((dataType) => {
- return {
- label: dataType,
- key: dataType,
- };
- });
-});
-
-const getColumnItemComputedClassList = (column: Column) => {
- if (column.status === "dropped") {
- return ["text-red-700", "cursor-not-allowed", "!bg-red-50", "opacity-70"];
- } else if (column.status === "created") {
- return ["text-green-700", "!bg-green-50"];
- } else if (
- isColumnChanged(
- currentTab.value.databaseId,
- currentTab.value.schemaId,
- currentTab.value.tableId,
- column.id
- )
- ) {
- return ["text-yellow-700", "!bg-yellow-50"];
- }
- return [];
-};
-
-const dataDefaultOptions = [
- {
- label: "NULL",
- key: "NULL",
- },
- {
- label: "EMPTY",
- key: "EMPTY",
- },
-];
-
-watch(
- () => state.selectedSubtab,
- async () => {
- currentTab.value.selectedSubtab = state.selectedSubtab;
- if (state.selectedSubtab === "raw-sql") {
- const originSchema = editorStore.getOriginSchema(
- currentTab.value.databaseId,
- currentTab.value.schemaId
- ) as Schema;
- const diffSchemaResult = diffSchema(
- currentTab.value.databaseId,
- originSchema,
- schema.value
- );
- const databaseEdit: DatabaseEdit = {
- databaseId: Number(currentTab.value.databaseId),
- createSchemaList: [],
- renameSchemaList: [],
- dropSchemaList: [],
- createTableList: diffSchemaResult.createTableList.filter(
- (context) => context.name === table.value.name
- ),
- alterTableList: diffSchemaResult.alterTableList.filter(
- (context) => context.name === table.value.name
- ),
- renameTableList: diffSchemaResult.renameTableList.filter(
- (context) => context.newName === table.value.name
- ),
- dropTableList: diffSchemaResult.dropTableList.filter(
- (context) => context.name === table.value.name
- ),
- };
- state.isFetchingDDL = true;
- const databaseEditResult = await editorStore.postDatabaseEdit(
- databaseEdit
- );
- if (databaseEditResult.validateResultList.length > 0) {
- notificationStore.pushNotification({
- module: "bytebase",
- style: "CRITICAL",
- title: "Invalid request",
- description: databaseEditResult.validateResultList
- .map((result) => result.message)
- .join("\n"),
- });
- state.statement = "";
- return;
- }
- state.statement = databaseEditResult.statement;
- state.isFetchingDDL = false;
- }
- },
- {
- immediate: true,
- }
-);
-
-const isColumnPrimaryKey = (column: Column): boolean => {
- return table.value.primaryKey.columnIdList.includes(column.id);
-};
-
-const checkColumnHasForeignKey = (column: Column): boolean => {
- const columnIdList = flatten(
- foreignKeyList.value.map((fk) => fk.columnIdList)
- );
- return columnIdList.includes(column.id);
-};
-
-const getReferencedForeignKeyName = (column: Column) => {
- if (!checkColumnHasForeignKey(column)) {
- return;
- }
- const fk = foreignKeyList.value.find(
- (fk) =>
- fk.columnIdList.find((columnId) => columnId === column.id) !== undefined
- );
- const index = fk?.columnIdList.findIndex(
- (columnId) => columnId === column.id
- );
-
- if (isUndefined(fk) || isUndefined(index) || index < 0) {
- return;
- }
- const referencedSchema = editorStore.getSchema(
- currentTab.value.databaseId,
- fk.referencedSchemaId
- );
- const referencedTable = editorStore.getTable(
- currentTab.value.databaseId,
- fk.referencedSchemaId,
- fk.referencedTableId
- );
- if (!referencedTable) {
- return;
- }
- const referColumn = referencedTable.columnList.find(
- (column) => column.id === fk.referencedColumnIdList[index]
- );
- if (databaseEngine.value === Engine.MYSQL) {
- return `${referencedTable.name}(${referColumn?.name})`;
- } else {
- return `${referencedSchema?.name}.${referencedTable.name}(${referColumn?.name})`;
- }
-};
-
-const isDroppedColumn = (column: Column): boolean => {
- return column.status === "dropped";
-};
-
-const disableChangeTable = computed(() => {
- return isDroppedSchema.value || isDroppedTable.value;
-});
-
-const disableAlterColumn = (column: Column): boolean => {
- return (
- isDroppedSchema.value || isDroppedTable.value || isDroppedColumn(column)
- );
-};
-
-const setColumnPrimaryKey = (column: Column, isPrimaryKey: boolean) => {
- if (isPrimaryKey) {
- column.nullable = false;
- table.value.primaryKey.columnIdList.push(column.id);
- } else {
- table.value.primaryKey.columnIdList =
- table.value.primaryKey.columnIdList.filter(
- (columnId) => columnId !== column.id
- );
- }
-};
-
-const handleChangeTab = (tab: SubtabType) => {
- state.selectedSubtab = tab;
-};
-
-const handleApplyColumnTemplate = (
- template: SchemaTemplateSetting_FieldTemplate
-) => {
- if (!hasFeature("bb.feature.schema-template")) {
- state.showFeatureModal = true;
- return;
- }
- if (template.engine !== databaseEngine.value || !template.column) {
- return;
- }
- const column: Column = {
- id: uuidv1(),
- name: template.column.name,
- type: template.column.type,
- nullable: template.column.nullable,
- comment: template.column.comment,
- userComment: template.column.userComment,
- default: template.column.default,
- status: "created",
- };
- table.value.columnList.push(column);
- state.showSchemaTemplateDrawer = false;
-};
-
-const handleAddColumn = () => {
- const column = convertColumnMetadataToColumn(ColumnMetadata.fromPartial({}));
- column.status = "created";
- table.value.columnList.push(column);
- nextTick(() => {
- (
- tableEditorContainerRef.value?.querySelector(
- `.column-${column.id} .column-name-input`
- ) as HTMLInputElement
- )?.focus();
- });
-};
-
-const handleColumnDefaultFieldChange = (
- column: Column,
- defaultString: string
-) => {
- if (defaultString === "NULL") {
- column.default = "NULL";
- } else if (defaultString === "EMPTY") {
- column.default = undefined;
- }
-};
-
-const gotoForeignKeyReferencedTable = (column: Column) => {
- if (!checkColumnHasForeignKey(column)) {
- return;
- }
- const fk = foreignKeyList.value.find(
- (fk) =>
- fk.columnIdList.find((columnId) => columnId === column.id) !== undefined
- );
- const index = fk?.columnIdList.findIndex(
- (columnId) => columnId === column.id
- );
- if (isUndefined(fk) || isUndefined(index) || index < 0) {
- return;
- }
-
- const referencedSchema = editorStore.getSchema(
- currentTab.value.databaseId,
- fk.referencedSchemaId
- );
- const referencedTable = editorStore.getTable(
- currentTab.value.databaseId,
- fk.referencedSchemaId,
- fk.referencedTableId
- );
- const referColumn = referencedTable?.columnList.find(
- (column) => column.id === fk.referencedColumnIdList[index]
- );
- if (!referencedSchema || !referencedTable || !referColumn) {
- return;
- }
-
- editorStore.addTab({
- id: generateUniqueTabId(),
- type: SchemaEditorTabType.TabForTable,
- databaseId: currentTab.value.databaseId,
- schemaId: referencedSchema.id,
- tableId: referencedTable.id,
- });
-
- nextTick(() => {
- const container = document.querySelector("#table-editor-container");
- const input = container?.querySelector(
- `.column-${referColumn.id} .column-name-input`
- ) as HTMLInputElement | undefined;
- if (input) {
- input.focus();
- scrollIntoView(input);
- }
- });
-};
-
-const handleEditColumnForeignKey = (column: Column) => {
- editForeignKeyColumn.value = column;
- state.showEditColumnForeignKeyModal = true;
-};
-
-const handleDropColumn = (column: Column) => {
- if (column.status === "created") {
- table.value.columnList = table.value.columnList.filter(
- (item) => item !== column
- );
- table.value.primaryKey.columnIdList =
- table.value.primaryKey.columnIdList.filter(
- (columnId) => columnId !== column.id
- );
-
- const foreignKeyList = schema.value.foreignKeyList.filter(
- (fk) => fk.tableId === currentTab.value.tableId
- );
- for (const foreignKey of foreignKeyList) {
- const columnRefIndex = foreignKey.columnIdList.findIndex(
- (columnId) => columnId === column.id
- );
- if (columnRefIndex > -1) {
- foreignKey.columnIdList.splice(columnRefIndex, 1);
- foreignKey.referencedColumnIdList.splice(columnRefIndex, 1);
- }
- }
- } else {
- column.status = "dropped";
- }
-};
-
-const handleRestoreColumn = (column: Column) => {
- if (column.status === "created") {
- return;
- }
-
- column.status = "normal";
-};
-
-const handleDiscardChanges = () => {
- if (table.value.status === "created") {
- return;
- }
-
- const originSchema = editorStore.getOriginSchema(
- currentTab.value.databaseId,
- currentTab.value.schemaId
- );
- const originTable = editorStore.getOriginTable(
- currentTab.value.databaseId,
- currentTab.value.schemaId,
- table.value.id
- );
-
- if (!originTable) {
- return;
- }
-
- table.value.name = originTable.name;
- table.value.columnList = cloneDeep(originTable.columnList);
- table.value.primaryKey = cloneDeep(originTable.primaryKey);
- table.value.status = "normal";
-
- schema.value.foreignKeyList = schema.value.foreignKeyList.filter(
- (fk) => fk.tableId !== table.value.id
- );
- const originForeignKeyList =
- originSchema?.foreignKeyList.filter(
- (fk) => fk.tableId === table.value.id
- ) || [];
- for (const originForeignKey of originForeignKeyList) {
- schema.value.foreignKeyList.push(cloneDeep(originForeignKey));
- }
-};
-</script>
-
-<style scoped>
-.table-header-item-container {
- @apply py-2 px-3;
-}
-.table-body-item-container {
- @apply w-full h-10 box-border p-px pr-2 relative;
-}
-.column-field-input {
- @apply w-full pr-1 box-border border-transparent truncate select-none rounded bg-transparent text-sm placeholder:italic placeholder:text-gray-400 focus:bg-white focus:text-black;
-}
-.column-field-text {
- @apply w-full pl-3 pr-1 box-border border-transparent truncate select-none rounded bg-transparent text-sm placeholder:italic placeholder:text-gray-400 focus:bg-white focus:text-black;
-}
-.foreign-key-field:hover .foreign-key-edit-button {
- @apply block;
-}
-</style>
diff --git a/frontend/src/components/SchemaEditor/SchemaEditor.vue b/frontend/src/components/SchemaEditor/SchemaEditor.vue
deleted file mode 100644
index 8aefa4d786..0000000000
--- a/frontend/src/components/SchemaEditor/SchemaEditor.vue
+++ /dev/null
@@ -1,106 +0,0 @@
-<template>
- <div v-if="!state.isLoading" class="w-full h-full">
- <Splitpanes
- class="default-theme w-full h-full flex flex-row overflow-hidden"
- >
- <Pane min-size="15" size="20">
- <AsidePanel />
- </Pane>
- <Pane min-size="60" size="80">
- <main class="pl-2 pt-2 w-full h-full flex flex-col overflow-y-auto">
- <template v-if="currentTab">
- <TabsContainer />
- <div
- :key="currentTab.id"
- class="w-full h-full relative overflow-y-auto"
- >
- <DatabaseEditor
- v-if="currentTab.type === SchemaEditorTabType.TabForDatabase"
- />
- <TableEditor
- v-else-if="currentTab.type === SchemaEditorTabType.TabForTable"
- />
- </div>
- </template>
- <EmptyTips v-else />
- </main>
- </Pane>
- </Splitpanes>
- </div>
-</template>
-
-<script lang="ts" setup>
-import { uniq } from "lodash-es";
-import { Splitpanes, Pane } from "splitpanes";
-import { computed, onMounted, PropType, reactive } from "vue";
-import { useInstanceV1Store, useSchemaEditorStore } from "@/store";
-import { SchemaEditorTabType } from "@/types";
-import AsidePanel from "./AsidePanel.vue";
-import EmptyTips from "./EmptyTips.vue";
-import DatabaseEditor from "./Panels/DatabaseEditor.vue";
-import TableEditor from "./Panels/TableEditor.vue";
-import TabsContainer from "./TabsContainer.vue";
-
-interface LocalState {
- isLoading: boolean;
-}
-
-const props = defineProps({
- databaseIdList: {
- type: Array as PropType<string[]>,
- required: true,
- },
-});
-const state = reactive<LocalState>({
- isLoading: true,
-});
-
-const editorStore = useSchemaEditorStore();
-const instanceStore = useInstanceV1Store();
-const currentTab = computed(() => {
- return editorStore.currentTab;
-});
-
-onMounted(async () => {
- // Reset Schema Editor state before fetching latest data when mounted.
- editorStore.$reset();
-
- // Prepare instance and database data.
- const databaseIdList = props.databaseIdList;
- const databaseList = await editorStore.fetchDatabaseList(databaseIdList);
- const instanceIdList = uniq(
- databaseList.map((database) => database.instanceEntity.uid)
- );
- for (const instanceId of instanceIdList) {
- await instanceStore.getOrFetchInstanceByUID(instanceId);
- }
- state.isLoading = false;
-});
-</script>
-
-<style>
-@import "splitpanes/dist/splitpanes.css";
-
-/* splitpanes pane style */
-.splitpanes.default-theme .splitpanes__pane {
- @apply bg-transparent !transition-none;
-}
-
-.splitpanes.default-theme .splitpanes__splitter {
- @apply bg-gray-100 border-none;
-}
-
-.splitpanes.default-theme .splitpanes__splitter:hover {
- @apply bg-indigo-300;
-}
-
-.splitpanes.default-theme .splitpanes__splitter::before,
-.splitpanes.default-theme .splitpanes__splitter::after {
- @apply bg-gray-700 opacity-50 text-white;
-}
-
-.splitpanes.default-theme .splitpanes__splitter:hover::before,
-.splitpanes.default-theme .splitpanes__splitter:hover::after {
- @apply bg-white opacity-100;
-}
-</style>
diff --git a/frontend/src/components/SchemaEditor/TabsContainer.vue b/frontend/src/components/SchemaEditor/TabsContainer.vue
deleted file mode 100644
index 81df6e4f97..0000000000
--- a/frontend/src/components/SchemaEditor/TabsContainer.vue
+++ /dev/null
@@ -1,130 +0,0 @@
-<template>
- <div
- ref="tabsContainerRef"
- class="w-full max-w-full overflow-x-auto bg-gray-100 select-none shrink-0 rounded"
- >
- <div class="w-fit flex flex-nowrap">
- <div
- v-for="tab in tabList"
- :key="tab.id"
- class="relative px-1 pl-2 py-2 rounded w-40 flex flex-row justify-between items-center shrink-0 border border-transparent cursor-pointer"
- :class="[
- `tab-${tab.id}`,
- tab.id === currentTab?.id && 'bg-white border-gray-200',
- ]"
- @click="handleSelectTab(tab)"
- >
- <div class="flex flex-row justify-start items-center mr-1">
- <span class="mr-1">
- <heroicons-outline:circle-stack
- v-if="tab.type === SchemaEditorTabType.TabForDatabase"
- class="rounded w-4 h-auto text-gray-400"
- />
- <heroicons-outline:table-cells
- v-else-if="tab.type === SchemaEditorTabType.TabForTable"
- class="rounded w-4 h-auto text-gray-400"
- />
- </span>
- <NEllipsis
- class="text-sm w-24"
- :class="getTabComputedClassList(tab)"
- >{{ getTabName(tab) }}</NEllipsis
- >
- </div>
- <span class="tab-close-button shrink-0 flex">
- <heroicons-outline:x
- class="rounded w-4 h-auto text-gray-400 hover:text-gray-600"
- @click.stop.prevent="handleCloseTab(tab)"
- />
- </span>
- <div
- v-if="tab.id === currentTab?.id"
- class="absolute -bottom-px left-0 w-full h-[3px] bg-accent rounded"
- ></div>
- </div>
- </div>
- </div>
-</template>
-
-<script lang="ts" setup>
-import { NEllipsis } from "naive-ui";
-import scrollIntoView from "scroll-into-view-if-needed";
-import { computed, nextTick, ref, watch } from "vue";
-import { useSchemaEditorStore } from "@/store";
-import { TabContext, SchemaEditorTabType } from "@/types";
-import { isTableChanged } from "./utils/table";
-
-const editorStore = useSchemaEditorStore();
-const tabsContainerRef = ref();
-const tabList = computed(() => {
- return Array.from(editorStore.tabState.tabMap.values());
-});
-const currentTab = computed(() => {
- return editorStore.currentTab;
-});
-
-watch(
- () => currentTab.value,
- () => {
- nextTick(() => {
- const element = tabsContainerRef.value?.querySelector(
- `.tab-${currentTab.value?.id}`
- );
- if (element) {
- scrollIntoView(element, {
- scrollMode: "if-needed",
- });
- }
- });
- }
-);
-
-const getTabComputedClassList = (tab: TabContext) => {
- if (tab.type === SchemaEditorTabType.TabForTable) {
- const table = editorStore.getTableWithTableTab(tab);
- if (!table) {
- return [];
- }
-
- if (table.status === "dropped") {
- return ["text-red-700", "line-through"];
- }
- if (table.status === "created") {
- return ["text-green-700"];
- }
-
- if (isTableChanged(tab.databaseId, tab.schemaId, tab.tableId)) {
- return ["text-yellow-700"];
- }
- }
-
- return [];
-};
-
-const getTabName = (tab: TabContext) => {
- if (tab.type === SchemaEditorTabType.TabForDatabase) {
- const database = editorStore.databaseList.find(
- (database) => database.uid === tab.databaseId
- );
- return `${database?.databaseName || "unknown database"}`;
- } else if (tab.type === SchemaEditorTabType.TabForTable) {
- const table = editorStore.getTable(
- tab.databaseId,
- tab.schemaId,
- tab.tableId
- );
- return `${table?.name || ""}`;
- } else {
- // Should never reach here.
- return "unknown structure";
- }
-};
-
-const handleSelectTab = (tab: TabContext) => {
- editorStore.setCurrentTab(tab.id);
-};
-
-const handleCloseTab = (tab: TabContext) => {
- editorStore.closeTab(tab.id);
-};
-</script>
diff --git a/frontend/src/components/SchemaEditor/utils/column.ts b/frontend/src/components/SchemaEditor/utils/column.ts
deleted file mode 100644
index ee7bca1a88..0000000000
--- a/frontend/src/components/SchemaEditor/utils/column.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-import { isEqual, isUndefined } from "lodash-es";
-import { useSchemaEditorStore } from "@/store";
-
-export const isColumnChanged = (
- databaseId: string,
- schemaId: string,
- tableId: string,
- columnId: string
-): boolean => {
- const editorStore = useSchemaEditorStore();
- const originSchema = editorStore.getOriginSchema(databaseId, schemaId);
- const schema = editorStore.getSchema(databaseId, schemaId);
- const table = schema?.tableList.find((table) => table.id === tableId);
- const originTable = originSchema?.tableList.find(
- (table) => table.id === tableId
- );
- const column = table?.columnList.find((column) => column.id === columnId);
- const originColumn = originTable?.columnList.find(
- (column) => column.id === columnId
- );
-
- const isPrimaryKey = table?.primaryKey.columnIdList.includes(columnId);
- const isPrimaryKeyOrigin =
- originTable?.primaryKey.columnIdList.includes(columnId);
-
- const originForeignKey = originSchema?.foreignKeyList.find(
- (fk) => fk.tableId === table?.id && fk.columnIdList.includes(columnId)
- );
- const foreignKey = schema?.foreignKeyList.find(
- (fk) => fk.tableId === table?.id && fk.columnIdList.includes(columnId)
- );
- const originIndex = originForeignKey?.columnIdList.findIndex(
- (column) => column === columnId
- );
- const originForeignKeyColumn = isUndefined(originIndex)
- ? undefined
- : originForeignKey?.referencedColumnIdList[originIndex];
- const index = foreignKey?.columnIdList.findIndex(
- (column) => column === columnId
- );
- const foreignKeyColumn = isUndefined(index)
- ? undefined
- : foreignKey?.referencedColumnIdList[index];
-
- return (
- !isEqual(column, originColumn) ||
- !isEqual(isPrimaryKey, isPrimaryKeyOrigin) ||
- !isEqual(foreignKeyColumn, originForeignKeyColumn)
- );
-};
diff --git a/frontend/src/components/SchemaEditor/utils/schema.ts b/frontend/src/components/SchemaEditor/utils/schema.ts
deleted file mode 100644
index 7a642282e4..0000000000
--- a/frontend/src/components/SchemaEditor/utils/schema.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import { isEqual } from "lodash-es";
-import { useSchemaEditorStore } from "@/store";
-
-export const isSchemaChanged = (
- databaseId: string,
- schemaId: string
-): boolean => {
- const editorStore = useSchemaEditorStore();
- const originSchema = editorStore.getOriginSchema(databaseId, schemaId);
- const schema = editorStore.getSchema(databaseId, schemaId);
-
- return !isEqual(originSchema, schema);
-};
diff --git a/frontend/src/components/SchemaEditor/utils/table.ts b/frontend/src/components/SchemaEditor/utils/table.ts
deleted file mode 100644
index 842c72c251..0000000000
--- a/frontend/src/components/SchemaEditor/utils/table.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import { isEqual } from "lodash-es";
-import { useSchemaEditorStore } from "@/store";
-
-export const isTableChanged = (
- databaseId: string,
- schemaId: string,
- tableId: string
-): boolean => {
- const editorStore = useSchemaEditorStore();
- const originSchema = editorStore.getOriginSchema(databaseId, schemaId);
- const schema = editorStore.getSchema(databaseId, schemaId);
- const table = schema?.tableList.find((table) => table.id === tableId);
- const originTable = originSchema?.tableList.find(
- (table) => table.id === tableId
- );
-
- const originForeignKeyList =
- originSchema?.foreignKeyList.filter((fk) => fk.tableId === table?.id) || [];
- const foreignKeyList =
- schema?.foreignKeyList.filter((fk) => fk.tableId === table?.id) || [];
-
- return (
- !isEqual(originTable, table) ||
- !isEqual(originForeignKeyList, foreignKeyList)
- );
-};
diff --git a/frontend/src/components/SchemaEditor/utils/useMetadataForDiagram.ts b/frontend/src/components/SchemaEditor/utils/useMetadataForDiagram.ts
deleted file mode 100644
index dec8dabf00..0000000000
--- a/frontend/src/components/SchemaEditor/utils/useMetadataForDiagram.ts
+++ /dev/null
@@ -1,226 +0,0 @@
-import { computed, unref } from "vue";
-import { EditStatus } from "@/components/SchemaDiagram";
-import { Database, DatabaseSchema, MaybeRef } from "@/types";
-import {
- ColumnMetadata,
- DatabaseMetadata,
- ForeignKeyMetadata,
- IndexMetadata,
- SchemaMetadata,
- TableMetadata,
-} from "@/types/proto/store/database";
-import { Column, Schema, Table } from "@/types/schemaEditor/atomType";
-import { isColumnChanged } from "./column";
-import { isSchemaChanged } from "./schema";
-import { isTableChanged } from "./table";
-
-type MetadataWithEditStatus<T, E> = T & {
- $$status?: EditStatus;
- $$edit?: E;
-};
-
-const statusOfSchema = (database: Database, schema: Schema) => {
- const { status } = schema;
- if (status === "created" || status === "dropped") {
- return status;
- }
- if (isSchemaChanged(database.id, schema.id)) {
- return "changed";
- }
- return "normal";
-};
-
-const statusOfTable = (
- database: Database,
- schema: Schema,
- table: Table
-): EditStatus => {
- const { status } = table;
- if (status === "created" || status === "dropped") {
- return status;
- }
- if (isTableChanged(database.id, schema.id, table.id)) {
- return "changed";
- }
-
- return "normal";
-};
-
-const statusOfColumn = (
- database: Database,
- schema: Schema,
- table: Table,
- column: Column
-): EditStatus => {
- const { status } = column;
- if (status === "created" || status === "dropped") {
- return status;
- }
- if (isColumnChanged(database.id, schema.id, table.id, column.id)) {
- return "changed";
- }
-
- return "normal";
-};
-
-export const useMetadataForDiagram = (
- databaseSchema: MaybeRef<DatabaseSchema>
-) => {
- const databaseMetadata = computed(() => {
- const { database, schemaList } = unref(databaseSchema);
- const databaseMeta = DatabaseMetadata.fromPartial({});
- databaseMeta.name = database.name;
- databaseMeta.collation = database.collation;
- databaseMeta.characterSet = database.characterSet;
- databaseMeta.schemas = schemaList.map((schema) => {
- const schemaMeta = SchemaMetadata.fromPartial({});
- Object.defineProperty(schemaMeta, "$$status", {
- enumerable: false,
- value: statusOfSchema(database, schema),
- });
- Object.defineProperty(schemaMeta, "$$edit", {
- enumerable: false,
- value: schema,
- });
-
- schemaMeta.name = schema.name;
- schemaMeta.tables = schema.tableList.map((table) => {
- const tableMeta = TableMetadata.fromPartial({});
- Object.defineProperty(tableMeta, "$$status", {
- enumerable: false,
- value: statusOfTable(database, schema, table),
- });
- Object.defineProperty(tableMeta, "$$edit", {
- enumerable: false,
- value: table,
- });
-
- tableMeta.name = table.name;
- tableMeta.engine = table.engine;
- tableMeta.collation = table.collation;
- tableMeta.rowCount = table.rowCount;
- tableMeta.dataSize = table.dataSize;
- tableMeta.comment = table.comment;
-
- tableMeta.columns = table.columnList.map((column) => {
- const columnMeta = ColumnMetadata.fromPartial({});
- Object.defineProperty(columnMeta, "$$status", {
- enumerable: false,
- value: statusOfColumn(database, schema, table, column),
- });
- Object.defineProperty(columnMeta, "$$edit", {
- enumerable: false,
- value: column,
- });
-
- columnMeta.name = column.name;
- columnMeta.type = column.type;
- columnMeta.nullable = column.nullable;
- columnMeta.comment = column.comment;
- columnMeta.default = column.default;
-
- return columnMeta;
- });
-
- // We don't have indexes other than primary key in Schema Editor,
- // so something will lost here when converting Table back to
- // TableMetadata.
- // But they will be back soon when editing indexes is supported in
- // Schema Editor.
- const pk = IndexMetadata.fromPartial({});
- Object.assign(pk, {
- primary: true,
- name: table.primaryKey.name,
- expressions: table.primaryKey.columnIdList.map(
- (id) => table.columnList.find((col) => col.id === id)!.name
- ),
- });
- tableMeta.indexes = [pk];
-
- const foreignKeyList = schema.foreignKeyList.filter(
- (fk) => fk.tableId === table.id
- );
- tableMeta.foreignKeys = foreignKeyList.map((fk) => {
- // In PostgreSQL, foreign keys can cross different schemas.
- // So we need to search the schemaList here.
- const refSchema = schemaList.find(
- (schema) => schema.id === fk.referencedSchemaId
- )!;
- const refTable = refSchema.tableList.find(
- (table) => table.id === fk.referencedTableId
- )!;
- const fkMeta = ForeignKeyMetadata.fromPartial({});
- Object.assign(fkMeta, {
- columns: fk.columnIdList.map(
- (id) => table.columnList.find((col) => col.id === id)!.name
- ),
- name: fk.name,
- referencedSchema: refSchema.name,
- referencedTable: refTable.name,
- referencedColumns: fk.referencedColumnIdList.map(
- (id) => refTable.columnList.find((col) => col.id === id)!.name
- ),
- });
- return fkMeta;
- });
- return tableMeta;
- });
- return schemaMeta;
- });
-
- return databaseMeta;
- });
-
- const schemaStatus = (schemaMeta: SchemaMetadata): EditStatus => {
- const status = (schemaMeta as MetadataWithEditStatus<SchemaMetadata, Table>)
- .$$status;
- if (typeof status !== "undefined") {
- return status;
- }
- return "normal";
- };
- const tableStatus = (tableMeta: TableMetadata): EditStatus => {
- const status = (tableMeta as MetadataWithEditStatus<TableMetadata, Table>)
- .$$status;
- if (typeof status !== "undefined") {
- return status;
- }
- return "normal";
- };
- const columnStatus = (columnMeta: ColumnMetadata): EditStatus => {
- const status = (
- columnMeta as MetadataWithEditStatus<ColumnMetadata, Column>
- ).$$status;
- if (typeof status !== "undefined") {
- return status;
- }
- return "normal";
- };
- const editableSchema = (schemaMeta: SchemaMetadata) => {
- const schema = (
- schemaMeta as MetadataWithEditStatus<SchemaMetadata, Schema>
- ).$$edit;
- return schema;
- };
- const editableTable = (tableMeta: TableMetadata) => {
- const table = (tableMeta as MetadataWithEditStatus<TableMetadata, Table>)
- .$$edit;
- return table;
- };
- const editableColumn = (columnMeta: ColumnMetadata) => {
- const column = (
- columnMeta as MetadataWithEditStatus<ColumnMetadata, Column>
- ).$$edit;
- return column;
- };
-
- return {
- databaseMetadata,
- schemaStatus,
- tableStatus,
- columnStatus,
- editableSchema,
- editableTable,
- editableColumn,
- };
-};
diff --git a/frontend/src/components/SchemaEditorV1/Aside/DatabaseTree.vue b/frontend/src/components/SchemaEditorV1/Aside/DatabaseTree.vue
index 3e5772afce..d85e1db7ee 100644
--- a/frontend/src/components/SchemaEditorV1/Aside/DatabaseTree.vue
+++ b/frontend/src/components/SchemaEditorV1/Aside/DatabaseTree.vue
@@ -77,9 +77,9 @@ import {
useNotificationStore,
useSchemaEditorV1Store,
} from "@/store";
-import { SchemaEditorTabType } from "@/types";
import { Engine } from "@/types/proto/v1/common";
import { SchemaMetadata } from "@/types/proto/v1/database_service";
+import { SchemaEditorTabType } from "@/types/v1/schemaEditor";
import {
Schema,
Table,
diff --git a/frontend/src/components/SchemaEditorV1/index.vue b/frontend/src/components/SchemaEditorV1/index.vue
index f01253e295..2420900409 100644
--- a/frontend/src/components/SchemaEditorV1/index.vue
+++ b/frontend/src/components/SchemaEditorV1/index.vue
@@ -1,5 +1,9 @@
<template>
- <div v-if="state.initialized" class="w-full h-[32rem] border rounded-lg">
+ <div
+ v-if="state.initialized"
+ class="w-full h-full border rounded-lg overflow-hidden"
+ v-bind="$attrs"
+ >
<Splitpanes
class="default-theme w-full h-full flex flex-row overflow-hidden"
>
diff --git a/frontend/src/components/SchemaEditorV1/utils/metadata.ts b/frontend/src/components/SchemaEditorV1/utils/metadata.ts
index 19de58f75e..22a3167b5a 100644
--- a/frontend/src/components/SchemaEditorV1/utils/metadata.ts
+++ b/frontend/src/components/SchemaEditorV1/utils/metadata.ts
@@ -1,13 +1,4 @@
import { cloneDeep, isEqual, uniq } from "lodash-es";
-import {
- Column,
- ForeignKey,
- Schema,
- Table,
- convertColumnMetadataToColumn,
- convertSchemaMetadataToSchema,
- convertTableMetadataToTable,
-} from "@/types";
import {
ColumnMetadata,
DatabaseMetadata,
@@ -16,6 +7,15 @@ import {
SchemaMetadata,
TableMetadata,
} from "@/types/proto/v1/database_service";
+import {
+ Column,
+ ForeignKey,
+ Schema,
+ Table,
+ convertColumnMetadataToColumn,
+ convertSchemaMetadataToSchema,
+ convertTableMetadataToTable,
+} from "@/types/v1/schemaEditor";
import { randomString } from "@/utils";
export const mergeSchemaEditToMetadata = (
@@ -116,86 +116,92 @@ export const mergeSchemaEditToMetadata = (
}
}
}
+ }
- // Build foreign keys.
- for (const foreignKey of schemaEdit.foreignKeyList) {
- const schema = metadata.schemas.find(
- (schema) => schema.name === schemaEdit.name
- );
- if (!schema) {
- continue;
- }
- const tableEdit = schemaEdit.tableList.find(
- (table) => table.id === foreignKey.tableId
- );
- const table = schema.tables.find(
- (table) => table.name === tableEdit?.name
- );
- if (!tableEdit || !table) {
- continue;
- }
- const referencedSchema = metadata.schemas.find(
- (schema) =>
- schema.name ===
- schemaEdits.find(
- (schemaEdit) => schemaEdit.id === foreignKey.referencedSchemaId
- )?.name
- );
- if (!referencedSchema) {
- continue;
- }
- const referencedTableEdit = schemaEdits
- .find((schemaEdit) => schemaEdit.id === foreignKey.referencedSchemaId)
- ?.tableList.find((table) => table.id === foreignKey.referencedTableId);
- const referencedTable = referencedSchema.tables.find(
- (table) => table.name === referencedTableEdit?.name
+ for (const schema of metadata.schemas) {
+ const schemaEdit = schemaEdits.find((item) => item.name === schema.name);
+ if (!schemaEdit) {
+ metadata.schemas = metadata.schemas.filter(
+ (item) => item.name !== schema.name
);
- if (!referencedTableEdit || !referencedTable) {
- continue;
- }
+ continue;
+ }
- const foreignKeyName = foreignKey.name
- ? foreignKey.name
- : `${table.name}-fk-${randomString(8).toLowerCase()}`;
- const fk = ForeignKeyMetadata.fromPartial({
- name: foreignKeyName,
- referencedSchema: referencedSchema.name,
- referencedTable: referencedTable.name,
- });
- if (table.foreignKeys.find((fk) => fk.name === foreignKeyName)) {
- continue;
- }
- if (
- foreignKey.columnIdList.length !==
- foreignKey.referencedColumnIdList.length
- ) {
- continue;
- }
- for (const columnId of foreignKey.columnIdList) {
- const column = tableEdit.columnList.find(
- (column) => column.id === columnId
+ // Build foreign keys.
+ for (const tableEdit of schemaEdit?.tableList ?? []) {
+ for (const foreignKey of tableEdit.foreignKeyList) {
+ const schema = metadata.schemas.find(
+ (schema) => schema.name === schemaEdit.name
);
- if (column) {
- fk.columns.push(column.name);
+ if (!schema) {
+ continue;
}
- }
- for (const columnId of foreignKey.referencedColumnIdList) {
- const column = referencedTableEdit.columnList.find(
- (column) => column.id === columnId
+ const tableEdit = schemaEdit.tableList.find(
+ (table) => table.id === foreignKey.tableId
);
- if (column) {
- fk.referencedColumns.push(column.name);
+ const table = schema.tables.find(
+ (table) => table.name === tableEdit?.name
+ );
+ if (!tableEdit || !table) {
+ continue;
+ }
+ const referencedSchema = metadata.schemas.find(
+ (schema) =>
+ schema.name ===
+ schemaEdits.find(
+ (schemaEdit) => schemaEdit.id === foreignKey.referencedSchemaId
+ )?.name
+ );
+ if (!referencedSchema) {
+ continue;
}
+ const referencedTableEdit = schemaEdits
+ .find((schemaEdit) => schemaEdit.id === foreignKey.referencedSchemaId)
+ ?.tableList.find(
+ (table) => table.id === foreignKey.referencedTableId
+ );
+ const referencedTable = referencedSchema.tables.find(
+ (table) => table.name === referencedTableEdit?.name
+ );
+ if (!referencedTableEdit || !referencedTable) {
+ continue;
+ }
+
+ const foreignKeyName = foreignKey.name
+ ? foreignKey.name
+ : `${table.name}-fk-${randomString(8).toLowerCase()}`;
+ const fk = ForeignKeyMetadata.fromPartial({
+ name: foreignKeyName,
+ referencedSchema: referencedSchema.name,
+ referencedTable: referencedTable.name,
+ });
+ if (table.foreignKeys.find((fk) => fk.name === foreignKeyName)) {
+ continue;
+ }
+ if (
+ foreignKey.columnIdList.length !==
+ foreignKey.referencedColumnIdList.length
+ ) {
+ continue;
+ }
+ for (const columnId of foreignKey.columnIdList) {
+ const column = tableEdit.columnList.find(
+ (column) => column.id === columnId
+ );
+ if (column) {
+ fk.columns.push(column.name);
+ }
+ }
+ for (const columnId of foreignKey.referencedColumnIdList) {
+ const column = referencedTableEdit.columnList.find(
+ (column) => column.id === columnId
+ );
+ if (column) {
+ fk.referencedColumns.push(column.name);
+ }
+ }
+ table.foreignKeys.push(fk);
}
- table.foreignKeys.push(fk);
- }
- }
- for (const schema of metadata.schemas) {
- const schemaEdit = schemaEdits.find((item) => item.name === schema.name);
- if (!schemaEdit) {
- metadata.schemas = metadata.schemas.filter(
- (item) => item.name !== schema.name
- );
}
}
@@ -427,7 +433,6 @@ export const rebuildEditableSchemas = (
continue;
}
- const foreignKeyList: ForeignKey[] = [];
for (const table of schema.tables) {
const editableTable = editableSchema.tableList.find(
(item) => item.name === table.name
@@ -436,6 +441,7 @@ export const rebuildEditableSchemas = (
continue;
}
+ const foreignKeyList: ForeignKey[] = [];
for (const foreignKeyMetadata of table.foreignKeys) {
const referencedSchema = editableSchemas.find(
(schema) => schema.name === foreignKeyMetadata.referencedSchema
@@ -474,8 +480,8 @@ export const rebuildEditableSchemas = (
foreignKeyList.push(fk);
}
+ editableTable.foreignKeyList = foreignKeyList;
}
- editableSchema.foreignKeyList = foreignKeyList;
}
return editableSchemas;
diff --git a/frontend/src/store/modules/index.ts b/frontend/src/store/modules/index.ts
index c39ef5ab7b..5f7f15d566 100644
--- a/frontend/src/store/modules/index.ts
+++ b/frontend/src/store/modules/index.ts
@@ -24,7 +24,6 @@ export * from "./uistate";
export * from "./sqlReview";
export * from "./onboardingState";
export * from "./onboardingGuide";
-export * from "./schemaEditor";
export * from "./idp";
export * from "./user";
export * from "./risk";
diff --git a/frontend/src/store/modules/schemaEditor.ts b/frontend/src/store/modules/schemaEditor.ts
deleted file mode 100644
index ace6941114..0000000000
--- a/frontend/src/store/modules/schemaEditor.ts
+++ /dev/null
@@ -1,296 +0,0 @@
-import axios from "axios";
-import { cloneDeep, isUndefined } from "lodash-es";
-import { defineStore } from "pinia";
-import {
- ComposedDatabase,
- TabContext,
- SchemaEditorState,
- SchemaEditorTabType,
- TableTabContext,
- DatabaseEdit,
- ResourceObject,
-} from "@/types";
-import { Engine } from "@/types/proto/v1/common";
-import { SchemaMetadata } from "@/types/proto/v1/database_service";
-import { DatabaseEditResult } from "@/types/schemaEditor";
-import {
- convertSchemaMetadataList,
- convertSchemaMetadataToSchema,
- Table,
-} from "@/types/schemaEditor/atomType";
-import { useDatabaseV1Store, useDBSchemaV1Store } from ".";
-
-const getDefaultSchemaEditorState = (): SchemaEditorState => {
- return {
- tabState: {
- tabMap: new Map<string, TabContext>(),
- currentTabId: "",
- },
- databaseSchemaById: new Map(),
- };
-};
-
-function convertDatabaseEditResult(
- databaseEditResult: ResourceObject
-): DatabaseEditResult {
- return {
- ...databaseEditResult.attributes,
- } as any as DatabaseEditResult;
-}
-
-export const useSchemaEditorStore = defineStore("SchemaEditor", {
- state: (): SchemaEditorState => {
- return getDefaultSchemaEditorState();
- },
- getters: {
- currentTab(): TabContext | undefined {
- if (isUndefined(this.tabState.currentTabId)) {
- return undefined;
- }
- return this.tabState.tabMap.get(this.tabState.currentTabId);
- },
- tabList(): TabContext[] {
- return Array.from(this.tabState.tabMap.values());
- },
- databaseList(): ComposedDatabase[] {
- return Array.from(this.databaseSchemaById.values()).map(
- (databaseSchema) => databaseSchema.database
- );
- },
- },
- actions: {
- addTab(tab: TabContext, setAsCurrentTab = true) {
- const tabCache = this.tabList.find((item) => {
- if (item.type !== tab.type) {
- return false;
- }
-
- if (
- item.type === SchemaEditorTabType.TabForDatabase &&
- item.databaseId === tab.databaseId
- ) {
- return true;
- }
- if (
- item.type === SchemaEditorTabType.TabForTable &&
- item.databaseId === tab.databaseId &&
- item.tableId === (tab as TableTabContext).tableId
- ) {
- return true;
- }
- return false;
- });
-
- if (tabCache !== undefined) {
- tab = {
- ...tabCache,
- ...tab,
- id: tabCache.id,
- };
- }
- this.tabState.tabMap.set(tab.id, tab);
-
- if (setAsCurrentTab) {
- this.setCurrentTab(tab.id);
- }
- },
- setCurrentTab(tabId: string) {
- if (isUndefined(this.tabState.tabMap.get(tabId))) {
- this.tabState.currentTabId = undefined;
- } else {
- this.tabState.currentTabId = tabId;
- }
- },
- closeTab(tabId: string) {
- const tabList = Array.from(this.tabState.tabMap.values());
- const tabIndex = tabList.findIndex((tab) => tab.id === tabId);
- // Find next tab for showing.
- if (this.tabState.currentTabId === tabId) {
- let nextTabIndex = -1;
- if (tabIndex === 0) {
- nextTabIndex = 1;
- } else {
- nextTabIndex = tabIndex - 1;
- }
- const nextTab = tabList[nextTabIndex];
- if (nextTab) {
- this.setCurrentTab(nextTab.id);
- } else {
- this.setCurrentTab("");
- }
- }
- this.tabState.tabMap.delete(tabId);
- },
- findTab(databaseId: string, tableId?: string) {
- let tabType = SchemaEditorTabType.TabForDatabase;
- if (tableId !== undefined) {
- tabType = SchemaEditorTabType.TabForTable;
- }
-
- const tab = this.tabList.find((tab) => {
- if (tab.type !== tabType || tab.databaseId !== databaseId) {
- return false;
- }
-
- if (tab.type === SchemaEditorTabType.TabForDatabase) {
- return true;
- } else if (
- tab.type === SchemaEditorTabType.TabForTable &&
- tab.tableId === tableId
- ) {
- return true;
- }
-
- return false;
- });
-
- return tab;
- },
- async fetchDatabaseList(databaseIdList: string[]) {
- const databaseList: ComposedDatabase[] = [];
- for (const id of databaseIdList) {
- const database = cloneDeep(
- await useDatabaseV1Store().getOrFetchDatabaseByUID(id)
- );
- databaseList.push(database);
- this.databaseSchemaById.set(database.uid, {
- database,
- schemaList: [],
- originSchemaList: [],
- });
- }
- return databaseList;
- },
- async fetchSchemaListByDatabaseId(databaseId: string, skipCache = false) {
- const database = useDatabaseV1Store().getDatabaseByUID(databaseId);
- const schemaMetadataList =
- await useDBSchemaV1Store().getOrFetchSchemaList(
- database.name,
- skipCache
- );
- const schemaList = convertSchemaMetadataList(schemaMetadataList);
- if (
- schemaList.length === 0 &&
- database.instanceEntity.engine === Engine.MYSQL
- ) {
- schemaList.push(
- convertSchemaMetadataToSchema(SchemaMetadata.fromPartial({}))
- );
- }
-
- this.databaseSchemaById.set(databaseId, {
- database,
- schemaList: schemaList,
- originSchemaList: cloneDeep(schemaList),
- });
-
- return this.databaseSchemaById.get(databaseId)!.schemaList;
- },
- getSchema(databaseId: string, schemaId: string) {
- return this.databaseSchemaById
- .get(databaseId)
- ?.schemaList.find((schema) => schema.id === schemaId);
- },
- getOriginSchema(databaseId: string, schemaId: string) {
- return this.databaseSchemaById
- .get(databaseId)
- ?.originSchemaList.find((schema) => schema.id === schemaId);
- },
- dropSchema(databaseId: string, schemaId: string) {
- const schema = this.getSchema(databaseId, schemaId);
- if (!schema) {
- return;
- }
-
- if (schema.status === "created") {
- const databaseSchema = this.databaseSchemaById.get(databaseId);
- if (databaseSchema) {
- databaseSchema.schemaList =
- this.databaseSchemaById
- .get(databaseId)
- ?.schemaList.filter((schema) => schema.id !== schemaId) || [];
-
- // Close related tabs.
- for (const tab of this.tabList) {
- if (tab.databaseId !== databaseId) {
- continue;
- }
-
- if (
- tab.type === SchemaEditorTabType.TabForTable &&
- tab.schemaId === schemaId
- ) {
- this.closeTab(tab.id);
- }
- }
- }
- } else {
- schema.status = "dropped";
- }
- },
- restoreSchema(databaseId: string, schemaId: string) {
- const schema = this.getSchema(databaseId, schemaId);
- if (!schema) {
- return;
- }
-
- schema.status = "normal";
- },
- getTable(databaseId: string, schemaId: string, tableId: string) {
- return this.getSchema(databaseId, schemaId)?.tableList.find(
- (table) => table.id === tableId
- );
- },
- getOriginTable(databaseId: string, schemaId: string, tableId: string) {
- return this.getOriginSchema(databaseId, schemaId)?.tableList.find(
- (table) => table.id === tableId
- );
- },
- getTableWithTableTab(tab: TableTabContext) {
- return this.databaseSchemaById
- .get(tab.databaseId)
- ?.schemaList.find((schema) => schema.id === tab.schemaId)
- ?.tableList?.find((table) => table.id === tab.tableId);
- },
- dropTable(databaseId: string, schemaId: string, tableId: string) {
- const table = this.getTable(databaseId, schemaId, tableId);
- if (!table) {
- return;
- }
-
- // Remove table record and close tab for created table.
- if (table.status === "created") {
- const tableList = this.databaseSchemaById
- .get(databaseId)
- ?.schemaList.find((schema) => schema.id === schemaId)
- ?.tableList as Table[];
- const index = tableList.findIndex((item) => item.id === table.id);
- tableList.splice(index, 1);
- const tab = this.findTab(databaseId, table.id);
- if (tab) {
- this.closeTab(tab.id);
- }
- } else {
- table.status = "dropped";
- }
- },
- restoreTable(databaseId: string, schemaId: string, tableId: string) {
- const table = this.getTable(databaseId, schemaId, tableId);
- if (!table) {
- return;
- }
-
- table.status = "normal";
- },
- async postDatabaseEdit(databaseEdit: DatabaseEdit) {
- const resData = (
- await axios.post(
- `/api/database/${databaseEdit.databaseId}/edit`,
- databaseEdit
- )
- ).data;
- const databaseEditResult = convertDatabaseEditResult(resData.data);
- return databaseEditResult;
- },
- },
-});
diff --git a/frontend/src/types/schemaEditor/atomType.ts b/frontend/src/types/schemaEditor/atomType.ts
deleted file mode 100644
index f89014e206..0000000000
--- a/frontend/src/types/schemaEditor/atomType.ts
+++ /dev/null
@@ -1,210 +0,0 @@
-import { v1 as uuidv1 } from "uuid";
-import { isGhostTable } from "@/utils";
-import {
- SchemaMetadata,
- TableMetadata,
- ColumnMetadata,
-} from "../proto/v1/database_service";
-
-type AtomResourceStatus = "normal" | "created" | "dropped";
-
-export interface Column {
- id: string;
- name: string;
- type: string;
- nullable: boolean;
- comment: string;
- userComment: string;
- default?: string;
- status: AtomResourceStatus;
- classification?: string;
-}
-
-export interface PrimaryKey {
- name: string;
- columnIdList: string[];
-}
-
-export interface Table {
- id: string;
- name: string;
- engine: string;
- collation: string;
- rowCount: number;
- dataSize: number;
- comment: string;
- columnList: Column[];
- // Including column id list.
- primaryKey: PrimaryKey;
- status: AtomResourceStatus;
-}
-
-export interface ForeignKey {
- // Should be an unique name.
- name: string;
- tableId: string;
- columnIdList: string[];
- referencedSchemaId: string;
- referencedTableId: string;
- referencedColumnIdList: string[];
-}
-
-export interface Schema {
- id: string;
- // It should be an empty string for MySQL/TiDB.
- name: string;
- tableList: Table[];
- foreignKeyList: ForeignKey[];
- status: AtomResourceStatus;
-}
-
-export const convertColumnMetadataToColumn = (
- columnMetadata: ColumnMetadata
-): Column => {
- return {
- id: uuidv1(),
- name: columnMetadata.name,
- type: columnMetadata.type,
- nullable: columnMetadata.nullable,
- comment: columnMetadata.comment,
- userComment: columnMetadata.userComment,
- default: columnMetadata.default,
- classification: columnMetadata.classification,
- status: "normal",
- };
-};
-
-export const convertTableMetadataToTable = (
- tableMetadata: TableMetadata
-): Table => {
- const table: Table = {
- id: uuidv1(),
- name: tableMetadata.name,
- engine: tableMetadata.engine,
- collation: tableMetadata.collation,
- rowCount: tableMetadata.rowCount,
- dataSize: tableMetadata.dataSize,
- comment: tableMetadata.comment,
- columnList: tableMetadata.columns.map((column) =>
- convertColumnMetadataToColumn(column)
- ),
- primaryKey: {
- name: "",
- columnIdList: [],
- },
- status: "normal",
- };
-
- for (const indexMetadata of tableMetadata.indexes) {
- if (indexMetadata.primary === true) {
- table.primaryKey.name = indexMetadata.name;
- for (const columnName of indexMetadata.expressions) {
- const column = table.columnList.find(
- (column) => column.name === columnName
- );
- if (column) {
- table.primaryKey.columnIdList.push(column.id);
- }
- }
- break;
- }
- }
-
- return table;
-};
-
-export const convertSchemaMetadataToSchema = (
- schemaMetadata: SchemaMetadata
-): Schema => {
- const tableList: Table[] = [];
-
- for (const tableMetadata of schemaMetadata.tables) {
- // Don't display ghost table in Schema Editor.
- if (isGhostTable(tableMetadata)) {
- continue;
- }
-
- const table = convertTableMetadataToTable(tableMetadata);
- tableList.push(table);
- }
-
- return {
- id: uuidv1(),
- name: schemaMetadata.name,
- tableList: tableList,
- foreignKeyList: [],
- status: "normal",
- };
-};
-
-export const convertSchemaMetadataList = (
- schemaMetadataList: SchemaMetadata[]
-): Schema[] => {
- // Compose all tables of each schema.
- const schemaList: Schema[] = schemaMetadataList.map((schemaMetadata) =>
- convertSchemaMetadataToSchema(schemaMetadata)
- );
-
- // Build foreign keys for schema and referenced schema.
- for (const schemaMetadata of schemaMetadataList) {
- const schema = schemaList.find(
- (schema) => schema.name === schemaMetadata.name
- );
- if (!schema) {
- continue;
- }
-
- const tableList = schema.tableList;
- const foreignKeyList: ForeignKey[] = [];
- for (const tableMetadata of schemaMetadata.tables) {
- const table = tableList.find(
- (table) => table.name === tableMetadata.name
- );
- if (!table) {
- continue;
- }
-
- for (const foreignKeyMetadata of tableMetadata.foreignKeys) {
- const referencedSchema = schemaList.find(
- (schema) => schema.name === foreignKeyMetadata.referencedSchema
- );
- const referencedTable = referencedSchema?.tableList.find(
- (table) => table.name === foreignKeyMetadata.referencedTable
- );
- if (!referencedSchema || !referencedTable) {
- continue;
- }
-
- const fk: ForeignKey = {
- name: foreignKeyMetadata.name,
- tableId: table.id,
- columnIdList: [],
- referencedSchemaId: referencedSchema.id,
- referencedTableId: referencedTable.id,
- referencedColumnIdList: [],
- };
- for (const columnName of foreignKeyMetadata.columns) {
- const column = table.columnList.find(
- (column) => column.name === columnName
- );
- if (column) {
- fk.columnIdList.push(column.id);
- }
- }
- for (const referencedColumnName of foreignKeyMetadata.referencedColumns) {
- const referencedColumn = referencedTable.columnList.find(
- (column) => column.name === referencedColumnName
- );
- if (referencedColumn) {
- fk.referencedColumnIdList.push(referencedColumn.id);
- }
- }
-
- foreignKeyList.push(fk);
- }
- }
- schema.foreignKeyList = foreignKeyList;
- }
-
- return schemaList;
-};
diff --git a/frontend/src/types/schemaEditor/index.ts b/frontend/src/types/schemaEditor/index.ts
index 86da31b95a..7530b7228a 100644
--- a/frontend/src/types/schemaEditor/index.ts
+++ b/frontend/src/types/schemaEditor/index.ts
@@ -1,50 +1,3 @@
-import { ComposedDatabase } from "../v1";
-import { Schema } from "./atomType";
-
-export * from "./atomType";
-
-export enum SchemaEditorTabType {
- TabForDatabase = "database",
- TabForTable = "table",
-}
-
-// Tab context for editing database.
-export interface DatabaseTabContext {
- id: string;
- type: SchemaEditorTabType.TabForDatabase;
- databaseId: string;
- selectedSchemaId?: string;
- selectedSubtab?: string;
-}
-
-// Tab context for editing table.
-export interface TableTabContext {
- id: string;
- type: SchemaEditorTabType.TabForTable;
- databaseId: string;
- schemaId: string;
- tableId: string;
- selectedSubtab?: string;
-}
-
-export type TabContext = DatabaseTabContext | TableTabContext;
-
-type TabId = string;
-
-export interface DatabaseSchema {
- database: ComposedDatabase;
- schemaList: Schema[];
- originSchemaList: Schema[];
-}
-
-export interface SchemaEditorState {
- tabState: {
- tabMap: Map<TabId, TabContext>;
- currentTabId?: TabId;
- };
- databaseSchemaById: Map<string, DatabaseSchema>;
-}
-
/**
* Type definition for API message.
*/
diff --git a/frontend/src/utils/schemaEditor/diffColumn.test.ts b/frontend/src/utils/schemaEditor/diffColumn.test.ts
index ae789889cc..fa28a21b0a 100644
--- a/frontend/src/utils/schemaEditor/diffColumn.test.ts
+++ b/frontend/src/utils/schemaEditor/diffColumn.test.ts
@@ -5,7 +5,7 @@ import {
ChangeColumnContext,
AlterColumnContext,
} from "@/types";
-import { Column } from "@/types/schemaEditor/atomType";
+import { Column } from "@/types/v1/schemaEditor";
import { diffColumnList } from "./diffColumn";
it("diff add column list", () => {
diff --git a/frontend/src/utils/schemaEditor/diffColumn.ts b/frontend/src/utils/schemaEditor/diffColumn.ts
index e407e4cd91..0e4bc6dc8a 100644
--- a/frontend/src/utils/schemaEditor/diffColumn.ts
+++ b/frontend/src/utils/schemaEditor/diffColumn.ts
@@ -4,8 +4,8 @@ import type {
DropColumnContext,
ChangeColumnContext,
AlterColumnContext,
-} from "@/types";
-import { Column } from "@/types/schemaEditor/atomType";
+} from "@/types/schemaEditor";
+import { Column } from "@/types/v1/schemaEditor";
import {
transformColumnToAddColumnContext,
transformColumnToChangeColumnContext,
diff --git a/frontend/src/utils/schemaEditor/diffSchema.ts b/frontend/src/utils/schemaEditor/diffSchema.ts
index 9b51308528..e33dc46085 100644
--- a/frontend/src/utils/schemaEditor/diffSchema.ts
+++ b/frontend/src/utils/schemaEditor/diffSchema.ts
@@ -8,7 +8,7 @@ import {
DropTableContext,
RenameSchemaContext,
RenameTableContext,
-} from "@/types";
+} from "@/types/schemaEditor";
import { Schema } from "@/types/v1/schemaEditor";
import { diffColumnList } from "./diffColumn";
import { transformTableToCreateTableContext } from "./transform";
diff --git a/frontend/src/utils/schemaEditor/transform.ts b/frontend/src/utils/schemaEditor/transform.ts
index ee4870a41f..14fb9fe5e9 100644
--- a/frontend/src/utils/schemaEditor/transform.ts
+++ b/frontend/src/utils/schemaEditor/transform.ts
@@ -4,7 +4,7 @@ import {
CreateTableContext,
ChangeColumnContext,
} from "@/types";
-import { Column, Table } from "@/types/schemaEditor/atomType";
+import { Column, Table } from "@/types/v1/schemaEditor";
export const transformColumnToAddColumnContext = (
column: Column