Skip to content

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

chore: retire unused (#12031)

Liu Jif3aa28851dfe
diff --git a/frontend/src/components/SchemaEditorV1/Aside/BranchTree.vue b/frontend/src/components/SchemaEditorV1/Aside/BranchTree.vue
deleted file mode 100644
index 967b81642a..0000000000
--- a/frontend/src/components/SchemaEditorV1/Aside/BranchTree.vue
+++ /dev/null
@@ -1,714 +0,0 @@
-<template>
- <div
- class="w-full h-full px-2 flex flex-col gap-y-2 relative overflow-y-hidden"
- >
- <div class="w-full flex pt-2 bg-white z-10 space-x-2">
- <NInput
- v-model:value="searchPattern"
- size="small"
- :placeholder="$t('schema-designer.search-tables')"
- >
- <template #prefix>
- <heroicons-outline:search class="h-auto text-gray-300" />
- </template>
- </NInput>
- <button
- v-if="!readonly"
- class="text-gray-400 hover:text-gray-500 disabled:cursor-not-allowed"
- @click="handleCreateSchemaOrTable"
- >
- <heroicons-outline:plus class="w-4 h-auto" />
- </button>
- </div>
- <div
- ref="treeContainerElRef"
- class="schema-designer-database-tree flex-1 pb-1 text-sm overflow-hidden select-none"
- :data-height="treeContainerHeight"
- >
- <NTree
- v-if="treeContainerHeight > 0"
- ref="treeRef"
- block-line
- virtual-scroll
- :style="{
- height: `${treeContainerHeight}px`,
- }"
- :data="treeDataRef"
- :pattern="searchPattern"
- :render-prefix="renderPrefix"
- :render-label="renderLabel"
- :render-suffix="renderSuffix"
- :node-props="nodeProps"
- :expanded-keys="expandedKeysRef"
- :selected-keys="selectedKeysRef"
- :on-update:expanded-keys="handleExpandedKeysChange"
- :theme-overrides="{ nodeHeight: '28px' }"
- />
- <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"
- :parent-name="state.schemaNameModalContext.parentName"
- @close="state.schemaNameModalContext = undefined"
- />
-
- <TableNameModal
- v-if="state.tableNameModalContext !== undefined"
- :parent-name="state.tableNameModalContext.parentName"
- :schema-id="state.tableNameModalContext.schemaId"
- :table-id="state.tableNameModalContext.tableId"
- @close="state.tableNameModalContext = undefined"
- />
-</template>
-
-<script lang="ts" setup>
-import { useElementSize } from "@vueuse/core";
-import { debounce, escape, head, isUndefined, pick } from "lodash-es";
-import type { TreeOption } from "naive-ui";
-import { NEllipsis, NInput, NDropdown, NTree } from "naive-ui";
-import { v1 as uuidv1 } from "uuid";
-import { computed, watch, ref, h, reactive, nextTick, onMounted } from "vue";
-import { useI18n } from "vue-i18n";
-import DuplicateIcon from "~icons/heroicons-outline/document-duplicate";
-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 { generateUniqueTabId, useSchemaEditorV1Store } from "@/store";
-import type { Branch } from "@/types/proto/v1/branch_service";
-import { Engine } from "@/types/proto/v1/common";
-import type { Table } from "@/types/v1/schemaEditor";
-import type { BranchSchema } from "@/types/v1/schemaEditor";
-import { SchemaEditorTabType } from "@/types/v1/schemaEditor";
-import { getHighlightHTMLByKeyWords, isDescendantOf } from "@/utils";
-import SchemaNameModal from "../Modals/SchemaNameModal.vue";
-import TableNameModal from "../Modals/TableNameModal.vue";
-import { isTableChanged } from "../utils";
-
-interface BaseTreeNode extends TreeOption {
- key: string;
- label: string;
- isLeaf: boolean;
- children?: TreeNode[];
-}
-
-interface TreeNodeForSchema extends BaseTreeNode {
- type: "schema";
- schemaId: string;
-}
-
-interface TreeNodeForTable extends BaseTreeNode {
- type: "table";
- schemaId: string;
- tableId: string;
-}
-
-type TreeNode = TreeNodeForSchema | TreeNodeForTable;
-
-interface TreeContextMenu {
- showDropdown: boolean;
- clientX: number;
- clientY: number;
- treeNode?: TreeNode;
-}
-
-interface LocalState {
- shouldRelocateTreeNode: boolean;
- schemaNameModalContext?: {
- parentName: string;
- };
- tableNameModalContext?: {
- parentName: string;
- schemaId: string;
- tableId?: string;
- };
-}
-
-const { t } = useI18n();
-const schemaEditorV1Store = useSchemaEditorV1Store();
-const state = reactive<LocalState>({
- shouldRelocateTreeNode: false,
-});
-const readonly = computed(() => schemaEditorV1Store.readonly);
-const currentTab = computed(() => schemaEditorV1Store.currentTab);
-
-const treeContainerElRef = ref<HTMLElement>();
-const { height: treeContainerHeight } = useElementSize(
- treeContainerElRef,
- undefined,
- {
- box: "content-box",
- }
-);
-const treeRef = ref<InstanceType<typeof NTree>>();
-const searchPattern = ref("");
-const expandedKeysRef = ref<string[]>([]);
-const selectedKeysRef = ref<string[]>([]);
-const treeDataRef = ref<TreeNode[]>([]);
-const contextMenu = reactive<TreeContextMenu>({
- showDropdown: false,
- clientX: 0,
- clientY: 0,
- treeNode: undefined,
-});
-
-// NOTE: we only support editing one branch for now.
-const branchSchema = computed(
- () =>
- head(
- Array.from(schemaEditorV1Store.resourceMap.branch.values())
- ) as BranchSchema
-);
-const engine = computed(() => {
- return (branchSchema.value.branch as any as Branch).engine;
-});
-
-const schemaList = computed(() =>
- branchSchema.value.schemaList.map((schema) => {
- return {
- ...schema,
- tableList: schema.tableList.map((table) => {
- // Don't watch column changes in database tree.
- return pick(table, ["id", "name", "status"]);
- }),
- };
- })
-);
-const tableList = computed(() =>
- branchSchema.value.schemaList.map((schema) => schema.tableList).flat()
-);
-
-const contextMenuOptions = computed(() => {
- const treeNode = contextMenu.treeNode;
- if (isUndefined(treeNode)) {
- return [];
- }
-
- if (treeNode.type === "schema") {
- const options = [];
- if (engine.value === Engine.POSTGRES) {
- const schema = schemaList.value.find(
- (schema) => schema.id === 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"),
- disabled: readonly.value,
- });
- options.push({
- key: "drop",
- label: t("schema-editor.actions.drop-schema"),
- disabled: readonly.value,
- });
- }
- }
- return options;
- } else if (treeNode.type === "table") {
- const schema = schemaList.value.find(
- (schema) => schema.id === treeNode.schemaId
- );
- if (!schema) {
- return [];
- }
-
- const table = schema.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"),
- disabled: readonly.value,
- });
- }
- return options;
- }
-
- return [];
-});
-
-onMounted(() => {
- if (!branchSchema.value) {
- throw new Error("branch should not be empty");
- }
-
- buildBranchTreeData();
- const firstChildNode = head(treeDataRef.value);
- if (firstChildNode) {
- nextTick(() => {
- // Auto expand the first tree node.
- openTabForTreeNode(firstChildNode);
- });
- }
-});
-
-const buildBranchTreeData = () => {
- const treeNodeList: TreeNode[] = [];
- for (const schema of schemaList.value) {
- const schemaTreeNode: TreeNodeForSchema = {
- type: "schema",
- key: `s-${schema.id}`,
- label: schema.name,
- isLeaf: false,
- schemaId: schema.id,
- children: schema.tableList.map((table) => ({
- type: "table",
- key: `t-${schema.id}-${table.id}`,
- label: table.name,
- children: [],
- isLeaf: true,
- schemaId: schema.id,
- tableId: table.id,
- })),
- };
- if (schemaTreeNode.children!.length === 0) {
- schemaTreeNode.isLeaf = true;
- }
- treeNodeList.push(schemaTreeNode);
- }
- treeDataRef.value = treeNodeList;
-};
-
-watch(() => schemaList.value, debounce(buildBranchTreeData, 250), {
- deep: true,
-});
-
-watch(
- () => currentTab.value,
- () => {
- if (!currentTab.value) {
- selectedKeysRef.value = [];
- return;
- }
-
- if (currentTab.value.type === SchemaEditorTabType.TabForDatabase) {
- if (currentTab.value.selectedSchemaId) {
- const schemaTreeNodeKey = `s-${currentTab.value.selectedSchemaId}`;
- selectedKeysRef.value = [schemaTreeNodeKey];
- }
- } else if (currentTab.value.type === SchemaEditorTabType.TabForTable) {
- const schemaTreeNodeKey = `s-${currentTab.value.schemaId}`;
- if (!expandedKeysRef.value.includes(schemaTreeNodeKey)) {
- expandedKeysRef.value.push(schemaTreeNodeKey);
- }
- const tableTreeNodeKey = `t-${currentTab.value.schemaId}-${currentTab.value.tableId}`;
- selectedKeysRef.value = [tableTreeNodeKey];
- }
-
- if (state.shouldRelocateTreeNode) {
- nextTick(() => {
- treeRef.value?.scrollTo({
- key: selectedKeysRef.value[0],
- });
- });
- }
- }
-);
-
-// Render prefix icons before label text.
-const renderPrefix = ({ option }: { option: TreeOption }) => {
- const treeNode = option as TreeNode;
- 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 }: { option: TreeOption }) => {
- const treeNode = option as TreeNode;
- const additionalClassList: string[] = ["select-none"];
- let label = treeNode.label;
-
- if (treeNode.type === "schema") {
- const schema = schemaList.value.find(
- (schema) => schema.id === treeNode.schemaId
- );
- if (schema) {
- if (engine.value !== Engine.POSTGRES) {
- label = t("db.tables");
- }
- if (schema.status === "created") {
- additionalClassList.push("text-green-700");
- } else if (schema.status === "dropped") {
- additionalClassList.push("text-red-700 line-through");
- } else {
- // To optimize the performance of the comparison, skip check if schema is changed for now.
- }
- }
- } else if (treeNode.type === "table") {
- const table = tableList.value.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(
- branchSchema.value.branch.name,
- treeNode.schemaId,
- treeNode.tableId
- )
- ) {
- additionalClassList.push("text-yellow-700");
- }
- }
- }
-
- return h(
- NEllipsis,
- {
- class: additionalClassList.join(" "),
- },
- () => [
- h("span", {
- innerHTML: getHighlightHTMLByKeyWords(
- escape(label),
- escape(searchPattern.value)
- ),
- }),
- ]
- );
-};
-
-// Render a 'menu' icon in the right of the node
-const renderSuffix = ({ option }: { option: TreeOption }) => {
- if (readonly.value) {
- return null;
- }
-
- const treeNode = option as TreeNode;
- const menuIcon = h(EllipsisIcon, {
- class: "w-4 h-auto text-gray-600",
- onClick: (e) => {
- handleShowDropdown(e, treeNode);
- },
- });
- const duplicateIcon = h(DuplicateIcon, {
- class: "w-4 h-auto mr-2 text-gray-600",
- onClick: (e) => {
- e.preventDefault();
- e.stopPropagation();
- e.stopImmediatePropagation();
-
- const schema = schemaList.value.find(
- (schema) => schema.id === treeNode.schemaId
- );
- if (!schema) {
- return;
- }
- const table = tableList.value.find((t) => t.id === treeNode.tableId);
- if (!table) {
- return;
- }
-
- const matchPattern = new RegExp(
- `^${getOriginalName(table.name)}` + "(_copy[0-9]{0,}){0,1}$"
- );
- const copiedTableNames = tableList.value
- .filter((table) => {
- return matchPattern.test(table.name);
- })
- .sort((t1, t2) => {
- return (
- extractDuplicateNumber(t1.name) - extractDuplicateNumber(t2.name)
- );
- });
- const targetName = copiedTableNames.slice(-1)[0]?.name ?? table.name;
-
- const newTable: Table = {
- ...table,
- id: uuidv1(),
- name: getDuplicateName(targetName),
- status: "created",
- primaryKey: {
- name: "",
- columnIdList: [],
- },
- columnList: table.columnList.map((column) => {
- return {
- ...column,
- id: uuidv1(),
- status: "created",
- };
- }),
- };
-
- for (const primaryKeyId of table.primaryKey.columnIdList) {
- const column = table.columnList.find((col) => col.id === primaryKeyId);
- if (!column) {
- continue;
- }
- const newColumn = newTable.columnList.find(
- (col) => col.name === column.name
- );
- if (!newColumn) {
- continue;
- }
- newTable.primaryKey.columnIdList.push(newColumn.id);
- }
-
- schema.tableList.push(newTable);
- openTabForTreeNode(treeNode);
- },
- });
- if (treeNode.type === "schema") {
- if (engine.value === Engine.POSTGRES) {
- return [menuIcon];
- }
- } else if (treeNode.type === "table") {
- const icons = [menuIcon];
- if (!readonly.value) {
- icons.unshift(duplicateIcon);
- }
- return icons;
- }
- return null;
-};
-
-const getOriginalName = (name: string): string => {
- return name.replace(/_copy[0-9]{0,}$/, "");
-};
-
-const extractDuplicateNumber = (name: string): number => {
- const match = /_copy[0-9]{0,}$/.exec(name);
- if (!match) {
- return -1;
- }
-
- const num = Number(match[0].replace("_copy", "0"));
- if (Number.isNaN(num)) {
- return -1;
- }
- return num;
-};
-
-const getDuplicateName = (name: string): string => {
- const num = extractDuplicateNumber(name);
- if (num < 0) {
- return `${name}_copy`;
- }
- return `${getOriginalName(name)}_copy${num + 1}`;
-};
-
-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];
-};
-
-const handleCreateSchemaOrTable = () => {
- if (engine.value === Engine.MYSQL || engine.value === Engine.TIDB) {
- const schema = schemaList.value[0];
- if (schema) {
- state.tableNameModalContext = {
- parentName: branchSchema.value.branch.name,
- schemaId: schema.id,
- };
- }
- } else if (engine.value === Engine.POSTGRES) {
- state.schemaNameModalContext = {
- parentName: branchSchema.value.branch.name,
- };
- }
-};
-
-// Set event handler to tree nodes.
-const nodeProps = ({ option }: { option: TreeOption }) => {
- const treeNode = option as TreeNode;
- return {
- 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")) {
- openTabForTreeNode(treeNode);
- } else {
- nextTick(() => {
- selectedKeysRef.value = [];
- });
- }
- },
- onContextMenu(e: MouseEvent) {
- handleShowDropdown(e, treeNode);
- },
- };
-};
-
-const openTabForTreeNode = (treeNode: TreeNode) => {
- state.shouldRelocateTreeNode = false;
-
- if (treeNode.type === "table") {
- schemaEditorV1Store.addTab({
- id: generateUniqueTabId(),
- type: SchemaEditorTabType.TabForTable,
- parentName: branchSchema.value.branch.name,
- schemaId: treeNode.schemaId,
- tableId: treeNode.tableId,
- name: treeNode.label,
- });
- } else if (treeNode.type === "schema") {
- const index = expandedKeysRef.value.findIndex(
- (key) => key === treeNode.key
- );
- if (index < 0) {
- expandedKeysRef.value.push(treeNode.key);
- }
- schemaEditorV1Store.addTab({
- id: generateUniqueTabId(),
- type: SchemaEditorTabType.TabForDatabase,
- parentName: branchSchema.value.branch.name,
- selectedSchemaId: treeNode.schemaId,
- name: treeNode.label,
- });
- }
-
- state.shouldRelocateTreeNode = true;
-};
-
-const handleContextMenuDropdownSelect = async (key: string) => {
- const treeNode = contextMenu.treeNode;
- if (!treeNode) {
- return;
- }
-
- if (treeNode.type === "schema") {
- if (key === "create-table") {
- state.tableNameModalContext = {
- parentName: branchSchema.value.branch.name,
- schemaId: treeNode.schemaId,
- };
- } else if (key === "drop") {
- schemaEditorV1Store.dropSchema(
- branchSchema.value.branch.name,
- treeNode.schemaId
- );
- } else if (key === "restore") {
- const schema = schemaEditorV1Store.getSchema(
- branchSchema.value.branch.name,
- treeNode.schemaId
- );
- if (!schema) {
- return;
- }
- schema.status = "normal";
- }
- } else if (treeNode.type === "table") {
- if (key === "rename") {
- state.tableNameModalContext = {
- parentName: branchSchema.value.branch.name,
- schemaId: treeNode.schemaId,
- tableId: treeNode.tableId,
- };
- } else if (key === "drop") {
- schemaEditorV1Store.dropTable(
- branchSchema.value.branch.name,
- treeNode.schemaId,
- treeNode.tableId
- );
- } else if (key === "restore") {
- const table = schemaEditorV1Store.getTable(
- branchSchema.value.branch.name,
- treeNode.schemaId,
- treeNode.tableId
- );
- if (!table) {
- return;
- }
- table.status = "normal";
- }
- }
- 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 lang="postcss" scoped>
-.schema-designer-database-tree :deep(.n-tree-node-wrapper) {
- @apply !p-0;
-}
-.schema-designer-database-tree :deep(.n-tree-node-content) {
- @apply !pl-2 text-sm;
-}
-.schema-designer-database-tree :deep(.n-tree-node-indent) {
- width: 0.25rem;
-}
-.schema-designer-database-tree :deep(.n-tree-node-content__suffix) {
- @apply rounded-sm !hidden hover:opacity-80;
-}
-.schema-designer-database-tree
- :deep(.n-tree-node-wrapper:hover .n-tree-node-content__suffix) {
- @apply !flex;
-}
-.schema-designer-database-tree
- :deep(
- .n-tree-node-wrapper .n-tree-node--selected .n-tree-node-content__suffix
- ) {
- @apply !flex;
-}
-.schema-designer-database-tree :deep(.n-tree-node-switcher) {
- @apply px-0 !w-4 !h-7;
-}
-</style>
diff --git a/frontend/src/components/SchemaEditorV1/Aside/DatabaseTree.vue b/frontend/src/components/SchemaEditorV1/Aside/DatabaseTree.vue
deleted file mode 100644
index f08b358fca..0000000000
--- a/frontend/src/components/SchemaEditorV1/Aside/DatabaseTree.vue
+++ /dev/null
@@ -1,863 +0,0 @@
-<template>
- <div
- class="w-full h-full pl-1 pr-2 flex flex-col gap-y-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
- ref="treeContainerElRef"
- class="schema-editor-database-tree flex-1 pb-1 text-sm overflow-hidden select-none"
- :data-height="treeContainerHeight"
- >
- <NTree
- v-if="treeContainerHeight > 0"
- ref="treeRef"
- block-line
- virtual-scroll
- :style="{
- height: `${treeContainerHeight}px`,
- }"
- :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"
- :theme-overrides="{ nodeHeight: '28px' }"
- />
- <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"
- :parent-name="state.schemaNameModalContext.parentName"
- :schema-id="state.schemaNameModalContext.schemaId"
- @close="state.schemaNameModalContext = undefined"
- />
-
- <TableNameModal
- v-if="state.tableNameModalContext !== undefined"
- :parent-name="state.tableNameModalContext.parentName"
- :schema-id="state.tableNameModalContext.schemaId"
- :table-id="state.tableNameModalContext.tableId"
- @close="state.tableNameModalContext = undefined"
- />
-</template>
-
-<script lang="ts" setup>
-import { useElementSize } from "@vueuse/core";
-import { escape, head, isUndefined, pick } from "lodash-es";
-import type { TreeOption } from "naive-ui";
-import { 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 {
- generateUniqueTabId,
- useInstanceV1Store,
- useDatabaseV1Store,
- useNotificationStore,
- useSchemaEditorV1Store,
-} from "@/store";
-import { Engine } from "@/types/proto/v1/common";
-import { SchemaEditorTabType } from "@/types/v1/schemaEditor";
-import type { Schema, Table } from "@/types/v1/schemaEditor";
-import { getHighlightHTMLByKeyWords, isDescendantOf } from "@/utils";
-import SchemaNameModal from "../Modals/SchemaNameModal.vue";
-import TableNameModal from "../Modals/TableNameModal.vue";
-import { fetchSchemaListByDatabaseName } from "../utils/database";
-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";
- // Resoure name format.
- instance: string;
-}
-
-interface TreeNodeForDatabase extends BaseTreeNode {
- type: "database";
- instance: string;
- // Resoure name format.
- database: string;
-}
-
-interface TreeNodeForSchema extends BaseTreeNode {
- type: "schema";
- instance: string;
- database: string;
- schemaId: string;
-}
-
-interface TreeNodeForTable extends BaseTreeNode {
- type: "table";
- instance: string;
- database: 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?: {
- parentName: string;
- schemaId: string | undefined;
- };
- tableNameModalContext?: {
- parentName: string;
- schemaId: string;
- tableId: string | undefined;
- };
-}
-
-const { t } = useI18n();
-const schemaEditorV1Store = useSchemaEditorV1Store();
-const instanceStore = useInstanceV1Store();
-const databaseStore = useDatabaseV1Store();
-const state = reactive<LocalState>({
- shouldRelocateTreeNode: false,
-});
-const currentTab = computed(() => schemaEditorV1Store.currentTab);
-
-const contextMenu = reactive<TreeContextMenu>({
- showDropdown: false,
- clientX: 0,
- clientY: 0,
- treeNode: undefined,
-});
-const treeContainerElRef = ref<HTMLElement>();
-const { height: treeContainerHeight } = useElementSize(
- treeContainerElRef,
- undefined,
- {
- box: "content-box",
- }
-);
-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(() => schemaEditorV1Store.databaseList);
-const schemaList = computed(() =>
- Array.from(schemaEditorV1Store.resourceMap["database"].values())
- .map((item) => item.schemaList)
- .flat()
- .map((schema) => {
- return {
- ...schema,
- tableList: schema.tableList.map((table) => {
- // Don't watch column changes in database tree.
- return pick(table, ["id", "name", "status"]);
- }),
- };
- })
-);
-const contextMenuOptions = computed(() => {
- const treeNode = contextMenu.treeNode;
- if (isUndefined(treeNode)) {
- return [];
- }
- const instanceEngine = instanceStore.getInstanceByName(
- treeNode.instance
- ).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 = schemaEditorV1Store.getSchema(
- treeNode.database,
- 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 = schemaEditorV1Store.getTable(
- treeNode.database,
- treeNode.schemaId,
- 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.name)) {
- instanceTreeNode = instanceTreeNodeMap.get(
- instance.name
- ) as TreeNodeForInstance;
- } else {
- instanceTreeNode = {
- type: "instance",
- key: `i-${instance.name}`,
- label: instance.title,
- isLeaf: false,
- instance: instance.name,
- children: [],
- };
- instanceTreeNodeMap.set(instance.name, 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.name}`,
- label: database.databaseName,
- isLeaf: false,
- instance: instance.name,
- database: database.name,
- };
- instanceTreeNode.children?.push(databaseTreeNode);
- databaseTreeNodeList.push(databaseTreeNode);
- }
- treeDataRef.value = treeNodeList;
-});
-
-watch(
- [() => schemaList.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.name)) {
- continue;
- }
- const databaseTreeNode = databaseTreeNodeList.find(
- (treeNode) =>
- treeNode.database === database.name &&
- databaseDataLoadedSet.value.has(treeNode.database)
- );
- if (isUndefined(databaseTreeNode)) {
- continue;
- }
- const instance = database.instanceEntity;
- const instanceEngine = instance.engine;
- if (instanceEngine === Engine.MYSQL) {
- const schemaList: Schema[] =
- schemaEditorV1Store.resourceMap["database"].get(database.name)
- ?.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.name}-${table.id}`,
- label: table.name,
- children: [],
- isLeaf: true,
- instance: instance.name,
- database: database.name,
- schemaId: schema.id,
- tableId: table.id,
- };
- });
- }
- } else if (instanceEngine === Engine.POSTGRES) {
- const schemaList: Schema[] =
- schemaEditorV1Store.resourceMap["database"].get(database.name)
- ?.schemaList || [];
- const schemaTreeNodeList: TreeNodeForSchema[] = [];
- for (const schema of schemaList) {
- const schemaTreeNode: TreeNodeForSchema = {
- type: "schema",
- key: `s-${database.name}-${schema.id}`,
- label: schema.name,
- instance: instance.name,
- database: database.name,
- 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.name}-${table.id}`,
- label: table.name,
- children: [],
- isLeaf: true,
- instance: instance.name,
- database: database.name,
- 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(
- () => currentTab.value,
- () => {
- if (!currentTab.value) {
- selectedKeysRef.value = [];
- return;
- }
-
- if (currentTab.value.type === SchemaEditorTabType.TabForDatabase) {
- if (currentTab.value.selectedSchemaId) {
- const key = `s-${currentTab.value.parentName}-${currentTab.value.selectedSchemaId}`;
- selectedKeysRef.value = [key];
- } else {
- const key = `d-${currentTab.value.parentName}`;
- selectedKeysRef.value = [key];
- }
- } else if (currentTab.value.type === SchemaEditorTabType.TabForTable) {
- const databaseTreeNodeKey = `d-${currentTab.value.parentName}`;
- if (!expandedKeysRef.value.includes(databaseTreeNodeKey)) {
- expandedKeysRef.value.push(databaseTreeNodeKey);
- }
- const schemaTreeNodeKey = `s-${currentTab.value.parentName}-${currentTab.value.schemaId}`;
- if (!expandedKeysRef.value.includes(schemaTreeNodeKey)) {
- expandedKeysRef.value.push(schemaTreeNodeKey);
- }
- const tableTreeNodeKey = `t-${currentTab.value.parentName}-${currentTab.value.tableId}`;
- selectedKeysRef.value = [tableTreeNodeKey];
- }
-
- if (state.shouldRelocateTreeNode) {
- nextTick(() => {
- treeRef.value?.scrollTo({
- key: selectedKeysRef.value[0],
- });
- });
- }
- }
-);
-
-watch(
- () => searchPattern.value,
- () => {
- 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 }: { option: TreeOption }) => {
- const treeNode = option as TreeNode;
-
- if (treeNode.type === "instance") {
- const instance = instanceStore.getInstanceByName(treeNode.instance);
- 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") {
- const database = databaseStore.getDatabaseByName(treeNode.database);
- return h("span", { class: "flex items-center gap-x-1" }, [
- h(DatabaseIcon, {
- class: "w-4 h-auto text-gray-400",
- }),
- h(
- "span",
- {
- class: "text-gray-500 text-sm",
- },
- `(${database.effectiveEnvironmentEntity.title})`
- ),
- ]);
- } 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 }: { option: TreeOption }) => {
- const treeNode = option as TreeNode;
- const additionalClassList: string[] = ["select-none"];
-
- if (treeNode.type === "schema") {
- const schema = schemaEditorV1Store.resourceMap["database"]
- .get(treeNode.database)
- ?.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.database, treeNode.schemaId)) {
- additionalClassList.push("text-yellow-700");
- }
- }
- }
- } else if (treeNode.type === "table") {
- const table = schemaEditorV1Store.resourceMap["database"]
- .get(treeNode.database)
- ?.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.database, 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 }: { option: TreeOption }) => {
- const treeNode = option as TreeNode;
- const icon = h(EllipsisIcon, {
- class: "w-4 h-auto text-gray-600",
- onClick: (e) => {
- handleShowDropdown(e, treeNode);
- },
- });
- const instanceEngine = instanceStore.getInstanceByName(
- treeNode.instance
- ).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 (option: TreeOption) => {
- const treeNode = option as TreeNode;
- if (treeNode.type === "database") {
- const databaseName = treeNode.database;
- if (databaseDataLoadedSet.value.has(databaseName)) {
- return;
- }
-
- databaseDataLoadedSet.value.add(databaseName);
- try {
- const schemaList = await fetchSchemaListByDatabaseName({
- database: databaseName,
- });
- 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 }: { option: TreeOption }) => {
- const treeNode = option as 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);
- }
- schemaEditorV1Store.addTab({
- id: generateUniqueTabId(),
- type: SchemaEditorTabType.TabForDatabase,
- parentName: treeNode.database,
- name: treeNode.label,
- });
- } else if (treeNode.type === "schema") {
- const index = expandedKeysRef.value.findIndex(
- (key) => key === treeNode.key
- );
- if (index < 0) {
- expandedKeysRef.value.push(treeNode.key);
- }
- } else if (treeNode.type === "table") {
- schemaEditorV1Store.addTab({
- id: generateUniqueTabId(),
- type: SchemaEditorTabType.TabForTable,
- parentName: treeNode.database,
- schemaId: treeNode.schemaId,
- tableId: treeNode.tableId,
- name: treeNode.label,
- });
- }
-
- nextTick(() => {
- if (treeNode.type === "database") {
- selectedKeysRef.value = [`d-${treeNode.database}`];
- } else if (treeNode.type === "schema") {
- selectedKeysRef.value = [
- `s-${treeNode.database}-${treeNode.schemaId}`,
- ];
- } else if (treeNode.type === "table") {
- selectedKeysRef.value = [
- `t-${treeNode.database}-${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.getInstanceByName(
- treeNode.instance
- ).engine;
- if (instanceEngine === Engine.MYSQL) {
- const schemaList: Schema[] =
- schemaEditorV1Store.resourceMap["database"].get(treeNode.database)
- ?.schemaList || [];
- const schema = head(schemaList);
- if (!schema) {
- return;
- }
- state.tableNameModalContext = {
- parentName: treeNode.database,
- schemaId: schema.id,
- tableId: undefined,
- };
- }
- } else if (key === "create-schema") {
- state.schemaNameModalContext = {
- parentName: treeNode.database,
- schemaId: undefined,
- };
- }
- } else if (treeNode?.type === "schema") {
- if (key === "create-table") {
- await loadSubTree(treeNode);
- state.tableNameModalContext = {
- parentName: treeNode.database,
- schemaId: treeNode.schemaId,
- tableId: undefined,
- };
- } else if (key === "rename") {
- state.schemaNameModalContext = {
- parentName: treeNode.database,
- schemaId: treeNode.schemaId,
- };
- } else if (key === "drop-schema") {
- schemaEditorV1Store.dropSchema(treeNode.database, treeNode.schemaId);
- } else if (key === "restore") {
- schemaEditorV1Store.restoreSchema(treeNode.database, treeNode.schemaId);
- }
- } else if (treeNode?.type === "table") {
- if (key === "rename") {
- state.tableNameModalContext = {
- parentName: treeNode.database,
- schemaId: treeNode.schemaId,
- tableId: treeNode.tableId,
- };
- } else if (key === "drop") {
- schemaEditorV1Store.dropTable(
- treeNode.database,
- treeNode.schemaId,
- treeNode.tableId
- );
- } else if (key === "restore") {
- schemaEditorV1Store.restoreTable(
- treeNode.database,
- 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 lang="postcss" scoped>
-.schema-editor-database-tree :deep(.n-tree-node-wrapper) {
- @apply !p-0;
-}
-.schema-editor-database-tree :deep(.n-tree-node-content) {
- @apply !pl-2 text-sm;
-}
-.schema-editor-database-tree :deep(.n-tree-node-indent) {
- width: 0.25rem;
-}
-.schema-editor-database-tree :deep(.n-tree-node-content__prefix) {
- @apply shrink-0 !mr-1;
-}
-.schema-editor-database-tree
- :deep(.n-tree-node-wrapper:hover .n-tree-node-content__suffix) {
- @apply !flex;
-}
-.schema-editor-database-tree
- :deep(
- .n-tree-node-wrapper .n-tree-node--selected .n-tree-node-content__suffix
- ) {
- @apply !flex;
-}
-.schema-editor-database-tree :deep(.n-tree-node-switcher) {
- @apply px-0 !w-4 !h-7;
-}
-</style>
diff --git a/frontend/src/components/SchemaEditorV1/Aside/index.vue b/frontend/src/components/SchemaEditorV1/Aside/index.vue
deleted file mode 100644
index e5ff8f2d9a..0000000000
--- a/frontend/src/components/SchemaEditorV1/Aside/index.vue
+++ /dev/null
@@ -1,12 +0,0 @@
-<template>
- <BranchTree v-if="schemaEditorV1Store.resourceType === 'branch'" />
- <DatabaseTree v-else-if="schemaEditorV1Store.resourceType === 'database'" />
-</template>
-
-<script lang="ts" setup>
-import { useSchemaEditorV1Store } from "@/store";
-import BranchTree from "./BranchTree.vue";
-import DatabaseTree from "./DatabaseTree.vue";
-
-const schemaEditorV1Store = useSchemaEditorV1Store();
-</script>
diff --git a/frontend/src/components/SchemaEditorV1/Editor.vue b/frontend/src/components/SchemaEditorV1/Editor.vue
deleted file mode 100644
index 6cc47e7dc9..0000000000
--- a/frontend/src/components/SchemaEditorV1/Editor.vue
+++ /dev/null
@@ -1,56 +0,0 @@
-<template>
- <main class="px-2 py-2 w-full h-full flex flex-col overflow-y-hidden">
- <template v-if="currentTab">
- <TabsContainer
- @on-table-search-pattern="handleTableSearchPattern"
- @on-column-search-pattern="handleColumnSearchPattern"
- />
- <div :key="currentTab.id" class="w-full flex-1 relative overflow-hidden">
- <DatabaseEditor
- v-if="currentTab.type === SchemaEditorTabType.TabForDatabase"
- :search-pattern="state.tableSearchPattern"
- />
- <TableEditor
- v-else-if="currentTab.type === SchemaEditorTabType.TabForTable"
- :search-pattern="state.columnSearchPattern"
- />
- </div>
- </template>
- <EmptyTips v-else />
- </main>
-</template>
-
-<script lang="ts" setup>
-import { computed, reactive, watch } from "vue";
-import { useSchemaEditorV1Store } from "@/store/modules/v1/schemaEditor";
-import { SchemaEditorTabType } from "@/types/v1/schemaEditor";
-import DatabaseEditor from "./Panels/DatabaseEditor.vue";
-import TableEditor from "./Panels/TableEditor.vue";
-import TabsContainer from "./TabsContainer.vue";
-
-interface LocalState {
- tableSearchPattern: string;
- columnSearchPattern: string;
-}
-
-const schemaEditorV1Store = useSchemaEditorV1Store();
-const currentTab = computed(() => schemaEditorV1Store.currentTab);
-
-const state = reactive<LocalState>({
- tableSearchPattern: "",
- columnSearchPattern: "",
-});
-
-const handleTableSearchPattern = (tableSearchPattern: string) => {
- state.tableSearchPattern = tableSearchPattern;
-};
-
-const handleColumnSearchPattern = (columnSearchPattern: string) => {
- state.columnSearchPattern = columnSearchPattern;
-};
-
-watch([() => currentTab.value], () => {
- state.tableSearchPattern = "";
- state.columnSearchPattern = "";
-});
-</script>
diff --git a/frontend/src/components/SchemaEditorV1/EmptyTips.vue b/frontend/src/components/SchemaEditorV1/EmptyTips.vue
deleted file mode 100644
index f4b03d6613..0000000000
--- a/frontend/src/components/SchemaEditorV1/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-designer.use-tips") }}
- </div>
-</template>
diff --git a/frontend/src/components/SchemaEditorV1/Modals/ActionConfirmModal.vue b/frontend/src/components/SchemaEditorV1/Modals/ActionConfirmModal.vue
deleted file mode 100644
index ae1e1c2e63..0000000000
--- a/frontend/src/components/SchemaEditorV1/Modals/ActionConfirmModal.vue
+++ /dev/null
@@ -1,65 +0,0 @@
-<template>
- <BBModal
- :title="props.title"
- :show="show"
- 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 gap-x-3">
- <NButton v-bind="negativeButtonProps" @click="dismissModal">
- {{ $t("common.cancel") }}
- </NButton>
- <NButton v-bind="positiveButtonProps" @click="handleConfirmButtonClick">
- {{ $t("common.confirm") }}
- </NButton>
- </div>
- </BBModal>
-</template>
-
-<script lang="ts" setup>
-import type { ButtonProps } from "naive-ui";
-import { NButton } from "naive-ui";
-import type { PropType } from "vue";
-
-const props = defineProps({
- show: {
- type: Boolean,
- default: true,
- },
- title: {
- type: String,
- default: "",
- },
- description: {
- type: String,
- default: "",
- },
- negativeButtonProps: {
- type: Object as PropType<ButtonProps>,
- default: () => ({ quaternary: true }),
- },
- positiveButtonProps: {
- type: Object as PropType<ButtonProps>,
- default: () => ({ type: "primary" }),
- },
-});
-
-const emit = defineEmits<{
- (event: "close"): void;
- (event: "confirm"): void;
- (event: "update:show", show: boolean): void;
-}>();
-
-const handleConfirmButtonClick = async () => {
- emit("confirm");
- emit("update:show", false);
-};
-
-const dismissModal = () => {
- emit("close");
- emit("update:show", false);
-};
-</script>
diff --git a/frontend/src/components/SchemaEditorV1/Modals/ColumnDefaultValueExpressionModal.vue b/frontend/src/components/SchemaEditorV1/Modals/ColumnDefaultValueExpressionModal.vue
deleted file mode 100644
index 5b7773e0c0..0000000000
--- a/frontend/src/components/SchemaEditorV1/Modals/ColumnDefaultValueExpressionModal.vue
+++ /dev/null
@@ -1,72 +0,0 @@
-<template>
- <BBModal
- :title="$t('schema-editor.default.expression')"
- class="shadow-inner outline outline-gray-200"
- @close="dismissModal"
- >
- <div class="w-72">
- <NInput
- ref="inputRef"
- v-model:value="state.expression"
- class="my-2"
- :autofocus="true"
- />
- </div>
- <div class="w-full flex items-center justify-end mt-2 space-x-3">
- <NButton @click="dismissModal">
- {{ $t("common.cancel") }}
- </NButton>
- <NButton type="primary" @click="handleConfirmButtonClick">
- {{ $t("common.save") }}
- </NButton>
- </div>
- </BBModal>
-</template>
-
-<script lang="ts" setup>
-import type { InputInst } from "naive-ui";
-import { NButton, NInput } from "naive-ui";
-import { onMounted, reactive, ref } from "vue";
-import { useNotificationStore } from "@/store";
-
-interface LocalState {
- expression: string;
-}
-
-const props = defineProps<{
- expression?: string;
-}>();
-
-const emit = defineEmits<{
- (event: "close"): void;
- (event: "update:expression", value: string): void;
-}>();
-
-const inputRef = ref<InputInst>();
-const notificationStore = useNotificationStore();
-const state = reactive<LocalState>({
- expression: props.expression || "",
-});
-
-const handleConfirmButtonClick = async () => {
- if (!state.expression) {
- notificationStore.pushNotification({
- module: "bytebase",
- style: "CRITICAL",
- title: "Expression cannot be empty",
- });
- return;
- }
-
- emit("update:expression", state.expression);
- dismissModal();
-};
-
-const dismissModal = () => {
- emit("close");
-};
-
-onMounted(() => {
- inputRef.value?.focus();
-});
-</script>
diff --git a/frontend/src/components/SchemaEditorV1/Modals/EditColumnForeignKeyModal.vue b/frontend/src/components/SchemaEditorV1/Modals/EditColumnForeignKeyModal.vue
deleted file mode 100644
index 3c8e7eb8a3..0000000000
--- a/frontend/src/components/SchemaEditorV1/Modals/EditColumnForeignKeyModal.vue
+++ /dev/null
@@ -1,241 +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>
- <NSelect
- v-model:value="state.referencedSchemaId"
- :placeholder="$t('schema-editor.schema.select')"
- :options="schemas.map((item) => ({ value: item.id, label: item.name }))"
- />
- </div>
- <div class="w-72">
- <p class="mt-4 mb-2">{{ $t("schema-editor.select-reference-table") }}</p>
- <NSelect
- v-model:value="state.referencedTableId"
- :placeholder="$t('schema-editor.table.select')"
- :options="
- tableList.map((item) => ({ value: item.id, label: item.name }))
- "
- />
- </div>
- <div class="w-72">
- <p class="mt-4 mb-2">{{ $t("schema-editor.select-reference-column") }}</p>
- <NSelect
- v-model:value="state.referencedColumnId"
- :placeholder="$t('schema-editor.column.select')"
- :options="
- columnList.map((item) => ({ value: item.id, label: item.name }))
- "
- />
- </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"
- >
- {{ $t("common.delete") }}
- </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 { NSelect } from "naive-ui";
-import { computed, onMounted, reactive, watch } from "vue";
-import { BBModal } from "@/bbkit";
-import { useSchemaEditorV1Store } from "@/store";
-import { Engine } from "@/types/proto/v1/common";
-import type { Column, ForeignKey } from "@/types/v1/schemaEditor";
-
-interface LocalState {
- referencedSchemaId?: string;
- referencedTableId?: string;
- referencedColumnId?: string;
-}
-
-const props = defineProps<{
- parentName: string;
- schemaId: string;
- tableId: string;
- columnId: string;
-}>();
-
-const emit = defineEmits<{
- (event: "close"): void;
-}>();
-
-const schemaEditorV1Store = useSchemaEditorV1Store();
-const state = reactive<LocalState>({
- referencedSchemaId: props.schemaId,
-});
-
-const engine = computed(() => {
- return schemaEditorV1Store.getCurrentEngine(props.parentName);
-});
-
-const parentResource = computed(() => {
- return schemaEditorV1Store.resourceMap[schemaEditorV1Store.resourceType].get(
- props.parentName
- );
-});
-
-const schemas = computed(() => {
- return parentResource.value?.schemaList || [];
-});
-
-const schema = computed(() => {
- return schemaEditorV1Store.getSchema(props.parentName, props.schemaId);
-});
-
-const table = computed(() => {
- return schema.value?.tableList.find((item) => item.id === props.tableId);
-});
-
-const propsColumn = computed(() => {
- return table.value?.columnList.find((item) => item.id === props.columnId);
-});
-
-const foreignKeyList = computed(() => {
- return table.value?.foreignKeyList || [];
-});
-
-const shouldShowSchemaSelector = computed(() => {
- return engine.value === Engine.POSTGRES;
-});
-
-const selectedSchema = computed(() => {
- return parentResource.value?.schemaList.find(
- (schema) => schema.id === state.referencedSchemaId
- );
-});
-
-const tableList = computed(() => {
- return selectedSchema.value?.tableList || [];
-});
-
-const selectedTable = computed(() => {
- return tableList.value.find((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()
- );
-});
-
-const foreignKey = computed(() => {
- for (const fk of foreignKeyList.value) {
- const foundIndex = fk.columnIdList.findIndex((id) => id === props.columnId);
- if (foundIndex > -1) {
- return fk;
- }
- }
- return undefined;
-});
-
-onMounted(() => {
- if (foreignKey.value) {
- const foundIndex = foreignKey.value.columnIdList.findIndex(
- (id) => id === 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(
- (id) => id === 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 = {
- // NOTE: keep it empty, we will generate a formated name in `mergeSchemaEditToMetadata`.
- name: "",
- tableId: props.tableId,
- columnIdList: [column.id],
- referencedSchemaId: state.referencedSchemaId,
- referencedTableId: state.referencedTableId,
- referencedColumnIdList: [state.referencedColumnId],
- };
- table.value?.foreignKeyList.push(fk);
- } else {
- const index = foreignKey.value.columnIdList.findIndex(
- (id) => id === 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/SchemaEditorV1/Modals/SchemaNameModal.vue b/frontend/src/components/SchemaEditorV1/Modals/SchemaNameModal.vue
deleted file mode 100644
index 25f73b2927..0000000000
--- a/frontend/src/components/SchemaEditorV1/Modals/SchemaNameModal.vue
+++ /dev/null
@@ -1,88 +0,0 @@
-<template>
- <BBModal
- :title="$t('schema-editor.actions.create-schema')"
- class="shadow-inner outline outline-gray-200"
- @close="dismissModal"
- >
- <div class="w-72">
- <p>{{ $t("schema-editor.schema.name") }}</p>
- <BBTextField
- v-model:value="state.schemaName"
- class="my-2 w-full"
- :required="true"
- :focus-on-mount="true"
- />
- </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">
- {{ $t("common.create") }}
- </button>
- </div>
- </BBModal>
-</template>
-
-<script lang="ts" setup>
-import { reactive } from "vue";
-import { useI18n } from "vue-i18n";
-import { useNotificationStore, useSchemaEditorV1Store } from "@/store";
-import { SchemaMetadata } from "@/types/proto/v1/database_service";
-import { convertSchemaMetadataToSchema } from "@/types/v1/schemaEditor";
-
-const schemaNameFieldRegexp = /^\S+$/;
-
-interface LocalState {
- schemaName: string;
-}
-
-const props = defineProps<{
- parentName: string;
-}>();
-
-const emit = defineEmits<{
- (event: "close"): void;
-}>();
-
-const { t } = useI18n();
-const schemaEditorV1Store = useSchemaEditorV1Store();
-const notificationStore = useNotificationStore();
-const state = reactive<LocalState>({
- schemaName: "",
-});
-
-const handleConfirmButtonClick = async () => {
- if (!schemaNameFieldRegexp.test(state.schemaName)) {
- notificationStore.pushNotification({
- module: "bytebase",
- style: "CRITICAL",
- title: t("schema-editor.message.invalid-schema-name"),
- });
- return;
- }
-
- const parentResource = schemaEditorV1Store.resourceMap[
- schemaEditorV1Store.resourceType
- ].get(props.parentName);
- if (!parentResource) {
- throw new Error(
- `Failed to find parent resource ${props.parentName} of type ${schemaEditorV1Store.resourceType}`
- );
- }
-
- const schema = convertSchemaMetadataToSchema(
- SchemaMetadata.fromPartial({
- name: state.schemaName,
- }),
- "created"
- );
- parentResource.schemaList.push(schema);
- // TODO(steven): Open the schema tab.
- dismissModal();
-};
-
-const dismissModal = () => {
- emit("close");
-};
-</script>
diff --git a/frontend/src/components/SchemaEditorV1/Modals/TableNameModal.vue b/frontend/src/components/SchemaEditorV1/Modals/TableNameModal.vue
deleted file mode 100644
index 382f4dfae7..0000000000
--- a/frontend/src/components/SchemaEditorV1/Modals/TableNameModal.vue
+++ /dev/null
@@ -1,158 +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>
- <NInput
- ref="inputRef"
- v-model:value="state.tableName"
- class="my-2"
- :autofocus="true"
- />
- </div>
- <div class="w-full flex items-center justify-end mt-2 space-x-3">
- <NButton @click="dismissModal">
- {{ $t("common.cancel") }}
- </NButton>
- <NButton type="primary" @click="handleConfirmButtonClick">
- {{ isCreatingTable ? $t("common.create") : $t("common.save") }}
- </NButton>
- </div>
- </BBModal>
-</template>
-
-<script lang="ts" setup>
-import type { InputInst } from "naive-ui";
-import { NButton, NInput } from "naive-ui";
-import { computed, onMounted, reactive, ref } from "vue";
-import { useI18n } from "vue-i18n";
-import {
- generateUniqueTabId,
- useNotificationStore,
- useSchemaEditorV1Store,
-} from "@/store";
-import { Engine } from "@/types/proto/v1/common";
-import {
- ColumnMetadata,
- TableMetadata,
-} from "@/types/proto/v1/database_service";
-import {
- SchemaEditorTabType,
- convertTableMetadataToTable,
-} from "@/types/v1/schemaEditor";
-
-// Table name must start with a non-space character, end with a non-space character, and can contain space in between.
-const tableNameFieldRegexp = /^\S[\S ]*\S?$/;
-
-interface LocalState {
- tableName: string;
-}
-
-const props = defineProps<{
- parentName: string;
- schemaId: string;
- tableId?: string;
-}>();
-
-const emit = defineEmits<{
- (event: "close"): void;
-}>();
-
-const { t } = useI18n();
-const inputRef = ref<InputInst>();
-const schemaEditorV1Store = useSchemaEditorV1Store();
-const notificationStore = useNotificationStore();
-const state = reactive<LocalState>({
- tableName: "",
-});
-
-const engine = computed(() => {
- return schemaEditorV1Store.getCurrentEngine(props.parentName);
-});
-
-const isCreatingTable = computed(() => {
- return props.tableId === undefined;
-});
-
-const handleConfirmButtonClick = async () => {
- if (!tableNameFieldRegexp.test(state.tableName)) {
- notificationStore.pushNotification({
- module: "bytebase",
- style: "CRITICAL",
- title: t("schema-editor.message.invalid-table-name"),
- });
- return;
- }
-
- const schema = schemaEditorV1Store.getSchema(
- props.parentName,
- props.schemaId
- );
- if (!schema) {
- notificationStore.pushNotification({
- module: "bytebase",
- style: "CRITICAL",
- title: t("schema-editor.message.schema-not-found"),
- });
- return;
- }
- 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 column = ColumnMetadata.fromPartial({});
- column.name = "id";
- if (engine.value === Engine.POSTGRES) {
- column.type = "INTEGER";
- } else {
- column.type = "INT";
- }
- column.comment = "ID";
- const table = TableMetadata.fromPartial({
- name: state.tableName,
- columns: [column],
- });
- const tableEdit = convertTableMetadataToTable(table, "created");
- tableEdit.primaryKey.columnIdList.push(
- ...tableEdit.columnList.map((col) => col.id)
- );
- schema.tableList.push(tableEdit);
- schemaEditorV1Store.addTab({
- id: generateUniqueTabId(),
- type: SchemaEditorTabType.TabForTable,
- parentName: props.parentName,
- schemaId: props.schemaId,
- tableId: tableEdit.id,
- name: state.tableName,
- });
- } else {
- const table = schema.tableList.find((table) => table.id === props.tableId);
- if (table) {
- table.name = state.tableName;
- }
- }
- dismissModal();
-};
-
-const dismissModal = () => {
- emit("close");
-};
-
-onMounted(() => {
- inputRef.value?.focus();
-});
-</script>
diff --git a/frontend/src/components/SchemaEditorV1/Panels/DatabaseEditor.vue b/frontend/src/components/SchemaEditorV1/Panels/DatabaseEditor.vue
deleted file mode 100644
index 064a6ab94f..0000000000
--- a/frontend/src/components/SchemaEditorV1/Panels/DatabaseEditor.vue
+++ /dev/null
@@ -1,373 +0,0 @@
-<template>
- <div class="flex flex-col w-full h-full overflow-y-hidden">
- <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 space-x-3">
- <div
- v-if="shouldShowSchemaSelector"
- class="ml-2 flex flex-row justify-start items-center text-sm"
- >
- <span class="mr-1">Schema:</span>
- <n-select
- v-model:value="state.selectedSchemaId"
- class="min-w-[8rem]"
- :options="schemaSelectorOptionList"
- />
- </div>
- <button
- v-if="!readonly"
- 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 whitespace-nowrap"
- :disabled="!allowCreateTable"
- @click="handleCreateNewTable"
- >
- <heroicons-outline:plus class="w-4 h-auto mr-1 text-gray-400" />
- {{ $t("schema-editor.actions.create-table") }}
- </button>
- <button
- v-if="!readonly"
- 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 whitespace-nowrap"
- :disabled="!allowCreateTable"
- @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>
- </div>
- </div>
- </div>
- <div class="flex justify-end items-center">
- <div
- class="flex flex-row justify-end items-center bg-gray-100 p-1 rounded whitespace-nowrap"
- >
- <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 === 'schema-diagram' &&
- 'bg-gray-200 text-gray-800'
- "
- @click="handleChangeTab('schema-diagram')"
- >
- <SchemaDiagramIcon class="mr-1" />
- {{ $t("schema-diagram.self") }}
- </button>
- </div>
- </div>
- </div>
-
- <div class="flex-1 overflow-y-hidden">
- <!-- List view -->
- <template v-if="state.selectedSubtab === 'table-list'">
- <TableList
- :schema-id="selectedSchema?.id || ''"
- :table-list="shownTableList"
- />
- </template>
- <template v-else-if="state.selectedSubtab === 'schema-diagram'">
- <SchemaDiagram
- :key="currentTab.parentName"
- :database="databaseV1"
- :database-metadata="databaseMetadata"
- :schema-status="schemaStatus"
- :table-status="tableStatus"
- :column-status="columnStatus"
- :editable="true"
- @edit-table="tryEditTable"
- @edit-column="tryEditColumn"
- />
- </template>
- </div>
- </div>
-
- <TableNameModal
- v-if="state.tableNameModalContext !== undefined"
- :parent-name="state.tableNameModalContext.parentName"
- :schema-id="state.tableNameModalContext.schemaId"
- :table-name="state.tableNameModalContext.tableName"
- @close="state.tableNameModalContext = undefined"
- />
-
- <Drawer
- :show="state.showSchemaTemplateDrawer"
- @close="state.showSchemaTemplateDrawer = false"
- >
- <DrawerContent :title="$t('schema-template.table-template.self')">
- <div class="w-[calc(100vw-36rem)] min-w-[64rem] max-w-[calc(100vw-8rem)]">
- <TableTemplates
- :engine="engine"
- :readonly="true"
- @apply="handleApplyTemplate"
- />
- </div>
- </DrawerContent>
- </Drawer>
-
- <FeatureModal
- feature="bb.feature.schema-template"
- :open="state.showFeatureModal"
- @cancel="state.showFeatureModal = false"
- />
-</template>
-
-<script lang="ts" setup>
-import { head } from "lodash-es";
-import scrollIntoView from "scroll-into-view-if-needed";
-import { computed, nextTick, reactive, watch } from "vue";
-import { SchemaDiagram, SchemaDiagramIcon } from "@/components/SchemaDiagram";
-import { Drawer, DrawerContent } from "@/components/v2";
-import {
- hasFeature,
- generateUniqueTabId,
- useSchemaEditorV1Store,
-} from "@/store";
-import { Engine } from "@/types/proto/v1/common";
-import type {
- ColumnMetadata,
- SchemaMetadata,
- TableMetadata,
-} from "@/types/proto/v1/database_service";
-import type { SchemaTemplateSetting_TableTemplate } from "@/types/proto/v1/setting_service";
-import { emptyDatabase } from "@/types/v1/database";
-import type {
- Table,
- DatabaseTabContext,
- DatabaseSchema,
-} from "@/types/v1/schemaEditor";
-import {
- SchemaEditorTabType,
- convertTableMetadataToTable,
-} from "@/types/v1/schemaEditor";
-import TableTemplates from "@/views/SchemaTemplate/TableTemplates.vue";
-import TableNameModal from "../Modals/TableNameModal.vue";
-import { useMetadataForDiagram } from "../utils/useMetadataForDiagram";
-import TableList from "./TableList";
-
-const props = withDefaults(
- defineProps<{
- searchPattern: string;
- }>(),
- {
- searchPattern: "",
- }
-);
-
-type SubtabType = "table-list" | "schema-diagram";
-
-interface LocalState {
- selectedSubtab: SubtabType;
- selectedSchemaId: string;
- showFeatureModal: boolean;
- showSchemaTemplateDrawer: boolean;
- tableNameModalContext?: {
- parentName: string;
- schemaId: string;
- tableName: string | undefined;
- };
- activeTableId?: string;
-}
-
-const editorStore = useSchemaEditorV1Store();
-const currentTab = computed(() => editorStore.currentTab as DatabaseTabContext);
-const state = reactive<LocalState>({
- selectedSubtab: "table-list",
- selectedSchemaId: currentTab.value?.selectedSchemaId ?? "",
- showFeatureModal: false,
- showSchemaTemplateDrawer: false,
-});
-const databaseV1 = computed(
- () => editorStore.currentDatabase ?? emptyDatabase()
-);
-const readonly = computed(() => editorStore.readonly);
-const engine = computed(() => {
- return editorStore.getCurrentEngine(currentTab.value.parentName);
-});
-const schemaList = computed(() => {
- return editorStore.currentSchemaList;
-});
-const databaseSchema = computed((): DatabaseSchema => {
- return {
- database: databaseV1.value,
- schemaList: schemaList.value,
- originSchemaList: [],
- };
-});
-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(props.searchPattern.trim())
- );
-});
-const shouldShowSchemaSelector = computed(() => {
- return engine.value === Engine.POSTGRES;
-});
-
-const allowCreateTable = computed(() => {
- if (engine.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;
-});
-
-watch(
- [() => currentTab.value],
- () => {
- 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,
- }
-);
-
-const handleChangeTab = (tab: SubtabType) => {
- state.selectedSubtab = tab;
-};
-
-const handleCreateNewTable = () => {
- const selectedSchema = schemaList.value.find(
- (schema) => schema.id === state.selectedSchemaId
- );
- if (selectedSchema) {
- state.tableNameModalContext = {
- parentName: currentTab.value.parentName,
- schemaId: selectedSchema.id,
- tableName: undefined,
- };
- }
-};
-
-const handleTableItemClick = (table: Table) => {
- editorStore.addTab({
- id: generateUniqueTabId(),
- type: SchemaEditorTabType.TabForTable,
- parentName: currentTab.value.parentName,
- schemaId: state.selectedSchemaId,
- tableId: table.id,
- name: table.name,
- });
-};
-
-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);
- }
- }
-};
-
-const handleApplyTemplate = (template: SchemaTemplateSetting_TableTemplate) => {
- state.showSchemaTemplateDrawer = false;
- if (!hasFeature("bb.feature.schema-template")) {
- state.showFeatureModal = true;
- return;
- }
- if (!template.table || template.engine !== engine.value) {
- return;
- }
-
- const tableEdit = convertTableMetadataToTable(
- template.table,
- "created",
- template.config
- );
-
- const selectedSchema = schemaList.value.find(
- (schema) => schema.id === state.selectedSchemaId
- );
- if (selectedSchema) {
- selectedSchema.tableList.push(tableEdit);
- editorStore.addTab({
- id: generateUniqueTabId(),
- type: SchemaEditorTabType.TabForTable,
- parentName: currentTab.value.parentName,
- schemaId: state.selectedSchemaId,
- tableId: tableEdit.id,
- name: template.table.name,
- });
- }
-};
-</script>
diff --git a/frontend/src/components/SchemaEditorV1/Panels/TableColumnEditor/TableColumnEditor.vue b/frontend/src/components/SchemaEditorV1/Panels/TableColumnEditor/TableColumnEditor.vue
deleted file mode 100644
index 7d9dd31060..0000000000
--- a/frontend/src/components/SchemaEditorV1/Panels/TableColumnEditor/TableColumnEditor.vue
+++ /dev/null
@@ -1,550 +0,0 @@
-<template>
- <div
- ref="containerElRef"
- class="w-full h-full"
- :data-height="containerHeight"
- :data-table-header-height="tableHeaderHeight"
- :data-table-body-height="tableBodyHeight"
- >
- <NDataTable
- v-bind="$attrs"
- size="small"
- :row-key="(column: Column) => column.id"
- :columns="columns"
- :data="layoutReady ? shownColumnList : []"
- :row-class-name="classesForRow"
- :max-height="tableBodyHeight"
- :virtual-scroll="true"
- :striped="true"
- :bordered="true"
- :bottom-bordered="true"
- class="schema-editor-table-column-editor"
- />
- </div>
-
- <ColumnDefaultValueExpressionModal
- v-if="editColumnDefaultValueExpressionContext"
- :expression="editColumnDefaultValueExpressionContext.defaultExpression"
- @close="editColumnDefaultValueExpressionContext = undefined"
- @update:expression="handleSelectColumnDefaultValueExpression"
- />
-
- <SemanticTypesDrawer
- v-if="state.pendingUpdateColumn"
- :show="state.showSemanticTypesDrawer"
- :semantic-type-list="semanticTypeList"
- @dismiss="state.showSemanticTypesDrawer = false"
- @apply="onSemanticTypeApply($event)"
- />
-
- <LabelEditorDrawer
- v-if="state.pendingUpdateColumn"
- :show="state.showLabelsDrawer"
- :readonly="false"
- :title="
- $t('db.labels-for-resource', {
- resource: `'${state.pendingUpdateColumn.name}'`,
- })
- "
- :labels="[state.pendingUpdateColumn.config.labels]"
- @dismiss="state.showLabelsDrawer = false"
- @apply="onLabelsApply"
- />
-</template>
-
-<script lang="ts" setup>
-import { useElementSize } from "@vueuse/core";
-import { flatten } from "lodash-es";
-import type { DataTableColumn } from "naive-ui";
-import { NCheckbox, NDataTable } from "naive-ui";
-import { computed, h, reactive, ref } from "vue";
-import { useI18n } from "vue-i18n";
-import ClassificationCell from "@/components/ColumnDataTable/ClassificationCell.vue";
-import LabelEditorDrawer from "@/components/LabelEditorDrawer.vue";
-import SemanticTypesDrawer from "@/components/SensitiveData/components/SemanticTypesDrawer.vue";
-import { InlineInput } from "@/components/v2";
-import { useSettingV1Store, useSubscriptionV1Store } from "@/store/modules";
-import type { Engine } from "@/types/proto/v1/common";
-import { ColumnConfig } from "@/types/proto/v1/database_service";
-import { DataClassificationSetting_DataClassificationConfig as DataClassificationConfig } from "@/types/proto/v1/setting_service";
-import type { Table, Column, ForeignKey } from "@/types/v1/schemaEditor";
-import ColumnDefaultValueExpressionModal from "../../Modals/ColumnDefaultValueExpressionModal.vue";
-import {
- getDefaultValueByKey,
- isTextOfColumnType,
-} from "../../utils/columnDefaultValue";
-import {
- DataTypeCell,
- ForeignKeyCell,
- OperationCell,
- ReorderCell,
- SemanticTypeCell,
-} from "./components";
-import DefaultValueCell from "./components/DefaultValueCell.vue";
-import LabelsCell from "./components/LabelsCell.vue";
-
-interface LocalState {
- pendingUpdateColumn?: Column;
- showSemanticTypesDrawer: boolean;
- showLabelsDrawer: boolean;
-}
-
-const props = withDefaults(
- defineProps<{
- readonly: boolean;
- showForeignKey?: boolean;
- table: Table;
- engine: Engine;
- foreignKeyList?: ForeignKey[];
- classificationConfigId?: string;
- disableChangeTable?: boolean;
- allowReorderColumns?: boolean;
- maxBodyHeight?: number;
- filterColumn?: (column: Column) => boolean;
- disableAlterColumn?: (column: Column) => boolean;
- getReferencedForeignKeyName?: (column: Column) => string;
- getColumnItemComputedClassList?: (column: Column) => string;
- }>(),
- {
- showForeignKey: true,
- disableChangeTable: false,
- allowReorderColumns: false,
- maxBodyHeight: undefined,
- foreignKeyList: () => [],
- classificationConfigId: "",
- filterColumn: (_: Column) => true,
- disableAlterColumn: (_: Column) => false,
- getReferencedForeignKeyName: (_: Column) => "",
- getColumnItemComputedClassList: (_: Column) => "",
- }
-);
-
-const emit = defineEmits<{
- (event: "drop", column: Column): void;
- (event: "restore", column: Column): void;
- (event: "reorder", column: Column, index: number, delta: -1 | 1): void;
- (event: "foreign-key-edit", column: Column): void;
- (event: "foreign-key-click", column: Column): void;
- (event: "primary-key-set", column: Column, isPrimaryKey: boolean): void;
-}>();
-
-const state = reactive<LocalState>({
- showSemanticTypesDrawer: false,
- showLabelsDrawer: false,
-});
-
-const containerElRef = ref<HTMLElement>();
-const tableHeaderElRef = computed(
- () =>
- containerElRef.value?.querySelector("thead.n-data-table-thead") as
- | HTMLElement
- | undefined
-);
-const { height: containerHeight } = useElementSize(containerElRef);
-const { height: tableHeaderHeight } = useElementSize(tableHeaderElRef);
-const tableBodyHeight = computed(() => {
- const bodyHeight = containerHeight.value - tableHeaderHeight.value - 2;
- const { maxBodyHeight = 0 } = props;
- if (maxBodyHeight > 0) {
- return Math.min(maxBodyHeight, bodyHeight);
- }
- return bodyHeight;
-});
-// Use this to avoid unnecessary initial rendering
-const layoutReady = computed(() => tableHeaderHeight.value > 0);
-const { t } = useI18n();
-const subscriptionV1Store = useSubscriptionV1Store();
-const settingStore = useSettingV1Store();
-const editColumnDefaultValueExpressionContext = ref<Column>();
-
-const semanticTypeList = computed(() => {
- return (
- settingStore.getSettingByName("bb.workspace.semantic-types")?.value
- ?.semanticTypeSettingValue?.types ?? []
- );
-});
-
-const showSemanticTypeColumn = computed(() => {
- return subscriptionV1Store.hasFeature("bb.feature.sensitive-data");
-});
-
-const classificationConfig = computed(() => {
- if (!props.classificationConfigId) {
- return;
- }
- return settingStore.getProjectClassification(props.classificationConfigId);
-});
-
-const columns = computed(() => {
- const columns: (DataTableColumn<Column> & { hide?: boolean })[] = [
- {
- key: "reorder",
- title: "",
- resizable: false,
- width: 44,
- hide: props.readonly || !props.allowReorderColumns,
- className: "!px-0",
- render: (column, index) => {
- return h(ReorderCell, {
- column,
- allowMoveUp: index > 0,
- allowMoveDown: index < shownColumnList.value.length - 1,
- disabled: props.disableChangeTable,
- onReorder: (delta) => emit("reorder", column, index, delta),
- });
- },
- },
- {
- key: "name",
- title: t("schema-editor.column.name"),
- resizable: true,
- width: 100,
- className: "input-cell",
- render: (column) => {
- return h(InlineInput, {
- value: column.name,
- disabled: props.readonly || props.disableAlterColumn(column),
- placeholder: "column name",
- style: {
- "--n-padding-left": "6px",
- "--n-padding-right": "4px",
- "--n-text-color-disabled": "rgb(var(--color-main))",
- },
- "onUpdate:value": (value) => (column.name = value),
- });
- },
- },
- {
- key: "semantic-types",
- title: t("settings.sensitive-data.semantic-types.self"),
- resizable: true,
- width: 140,
- hide: !showSemanticTypeColumn.value,
- render: (column) => {
- return h(SemanticTypeCell, {
- column,
- readonly: props.readonly,
- disabled: props.disableChangeTable,
- semanticTypeList: semanticTypeList.value,
- disableAlterColumn: props.disableAlterColumn,
- onRemove: () => onSemanticTypeRemove(column),
- onEdit: () => openSemanticTypeDrawer(column),
- });
- },
- },
- {
- key: "classification",
- title: t("schema-editor.column.classification"),
- hide: !classificationConfig.value,
- resizable: true,
- width: 140,
- render: (column) => {
- return h(ClassificationCell, {
- classification: column.config.classificationId,
- readonly: props.readonly,
- disabled: props.disableChangeTable,
- classificationConfig:
- classificationConfig.value ??
- DataClassificationConfig.fromPartial({}),
- onApply: (id: string) => {
- column.config.classificationId = id;
- },
- });
- },
- },
- {
- key: "type",
- title: t("schema-editor.column.type"),
- resizable: true,
- width: 140,
- className: "input-cell",
- render: (column) => {
- return h(DataTypeCell, {
- column,
- disabled: props.readonly || props.disableAlterColumn(column),
- schemaTemplateColumnTypes: schemaTemplateColumnTypes.value,
- engine: props.engine,
- "onUpdate:value": (value) => (column.type = value),
- });
- },
- },
- {
- key: "default-value",
- title: t("schema-editor.column.default"),
- resizable: true,
- width: 140,
- className: "input-cell",
- render: (column) => {
- return h(DefaultValueCell, {
- column,
- disabled: props.readonly || props.disableAlterColumn(column),
- schemaTemplateColumnTypes: schemaTemplateColumnTypes.value,
- engine: props.engine,
- onInput: (value) => handleColumnDefaultInput(column, value),
- onSelect: (option) => handleColumnDefaultSelect(column, option.key),
- });
- },
- },
- {
- key: "comment",
- title: t("schema-editor.column.comment"),
- resizable: true,
- width: 140,
- className: "input-cell",
- render: (column) => {
- return h(InlineInput, {
- value: column.userComment,
- disabled: props.readonly || props.disableAlterColumn(column),
- placeholder: "comment",
- style: {
- "--n-padding-left": "6px",
- "--n-padding-right": "4px",
- "--n-text-color-disabled": "rgb(var(--color-main))",
- },
- "onUpdate:value": (value) => (column.userComment = value),
- });
- },
- },
- {
- key: "not-null",
- title: t("schema-editor.column.not-null"),
- resizable: true,
- width: 80,
- className: "checkbox-cell",
- render: (column) => {
- return h(NCheckbox, {
- checked: !column.nullable,
- disabled:
- props.readonly ||
- props.disableAlterColumn(column) ||
- isColumnPrimaryKey(column),
- "onUpdate:checked": (checked: boolean) =>
- (column.nullable = !checked),
- });
- },
- },
- {
- key: "primary",
- title: t("schema-editor.column.primary"),
- resizable: true,
- width: 80,
- className: "checkbox-cell",
- render: (column) => {
- return h(NCheckbox, {
- checked: isColumnPrimaryKey(column),
- disabled: props.readonly || props.disableAlterColumn(column),
- "onUpdate:checked": (checked: boolean) =>
- emit("primary-key-set", column, checked),
- });
- },
- },
- {
- key: "foreign-key",
- title: t("schema-editor.column.foreign-key"),
- hide: !props.showForeignKey,
- resizable: true,
- width: 140,
- className: "text-cell",
- render: (column) => {
- return h(ForeignKeyCell, {
- column,
- readonly: props.readonly,
- disabled: props.readonly || props.disableAlterColumn(column),
- hasForeignKey: checkColumnHasForeignKey(column),
- referencedForeignKeyName: props.getReferencedForeignKeyName(column),
- onClick: () => emit("foreign-key-click", column),
- onEdit: () => emit("foreign-key-edit", column),
- });
- },
- },
- {
- key: "labels",
- title: t("common.labels"),
- resizable: true,
- width: 140,
- render: (column) => {
- return h(LabelsCell, {
- column,
- readonly: props.readonly,
- disabled: props.disableChangeTable,
- onEdit: () => openLabelsDrawer(column),
- });
- },
- },
- {
- key: "operations",
- title: "",
- resizable: false,
- width: 30,
- hide: props.readonly,
- className: "!px-0",
- render: (column) => {
- return h(OperationCell, {
- column,
- dropped: isDroppedColumn(column),
- disabled: props.disableChangeTable,
- onDrop: () => emit("drop", column),
- onRestore: () => emit("restore", column),
- });
- },
- },
- ];
- return columns.filter((header) => !header.hide);
-});
-
-const shownColumnList = computed(() => {
- return props.table.columnList.filter(props.filterColumn);
-});
-
-const isColumnPrimaryKey = (column: Column): boolean => {
- return props.table.primaryKey.columnIdList.includes(column.id);
-};
-
-const checkColumnHasForeignKey = (column: Column): boolean => {
- const columnIdList = flatten(
- props.foreignKeyList.map((fk) => fk.columnIdList)
- );
- return columnIdList.includes(column.id);
-};
-
-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 === props.engine
- );
- if (columnType && columnType.enabled) {
- return columnType.types;
- }
- }
- return [];
-});
-
-const handleColumnDefaultInput = (column: Column, value: string) => {
- column.hasDefault = true;
- column.defaultNull = undefined;
- // If column is text type or has default string, we will treat user's input as string.
- if (
- isTextOfColumnType(props.engine, column.type) ||
- column.defaultString !== undefined
- ) {
- column.defaultString = value;
- column.defaultExpression = undefined;
- return;
- }
- // Otherwise we will treat user's input as expression.
- column.defaultExpression = value;
-};
-
-const handleColumnDefaultSelect = (column: Column, key: string) => {
- if (key === "expression") {
- editColumnDefaultValueExpressionContext.value = column;
- return;
- }
-
- const defaultValue = getDefaultValueByKey(key);
- if (!defaultValue) {
- return;
- }
-
- column.hasDefault = defaultValue.hasDefault;
- column.defaultNull = defaultValue.defaultNull;
- column.defaultString = defaultValue.defaultString;
- column.defaultExpression = defaultValue.defaultExpression;
- if (column.hasDefault && column.defaultNull) {
- column.nullable = true;
- }
-};
-
-const handleSelectColumnDefaultValueExpression = (expression: string) => {
- const column = editColumnDefaultValueExpressionContext.value;
- if (!column) {
- return;
- }
- column.hasDefault = true;
- column.defaultNull = undefined;
- column.defaultString = undefined;
- column.defaultExpression = expression;
-};
-
-const openSemanticTypeDrawer = (column: Column) => {
- state.pendingUpdateColumn = column;
- state.showSemanticTypesDrawer = true;
-};
-
-const openLabelsDrawer = (column: Column) => {
- state.pendingUpdateColumn = column;
- state.showLabelsDrawer = true;
-};
-
-const onSemanticTypeApply = async (semanticTypeId: string) => {
- if (!state.pendingUpdateColumn) {
- return;
- }
-
- state.pendingUpdateColumn.config = ColumnConfig.fromPartial({
- ...state.pendingUpdateColumn.config,
- semanticTypeId,
- });
-};
-
-const onLabelsApply = (labelsList: { [key: string]: string }[]) => {
- if (!state.pendingUpdateColumn) {
- return;
- }
- state.pendingUpdateColumn.config = ColumnConfig.fromPartial({
- ...state.pendingUpdateColumn.config,
- labels: labelsList[0],
- });
-};
-
-const onSemanticTypeRemove = async (column: Column) => {
- column.config = ColumnConfig.fromPartial({
- ...column.config,
- semanticTypeId: "",
- });
-};
-
-const classesForRow = (column: Column, index: number) => {
- return props.getColumnItemComputedClassList(column);
-};
-
-const isDroppedColumn = (column: Column): boolean => {
- return column.status === "dropped";
-};
-</script>
-
-<style lang="postcss" scoped>
-.schema-editor-table-column-editor
- :deep(.n-data-table-th .n-data-table-resize-button::after) {
- @apply bg-control-bg h-2/3;
-}
-.schema-editor-table-column-editor :deep(.n-data-table-td.input-cell) {
- @apply pl-0.5 pr-1 py-0;
-}
-.schema-editor-table-column-editor
- :deep(.n-data-table-td.input-cell .n-input__placeholder),
-.schema-editor-table-column-editor
- :deep(.n-data-table-td.input-cell .n-base-selection-placeholder) {
- @apply italic;
-}
-.schema-editor-table-column-editor :deep(.n-data-table-td.checkbox-cell) {
- @apply pr-1 py-0;
-}
-.schema-editor-table-column-editor :deep(.n-data-table-td.text-cell) {
- @apply pr-1 py-0;
-}
-.schema-editor-table-column-editor
- :deep(.n-data-table-tr.created .n-data-table-td) {
- @apply text-green-700 !bg-green-50;
-}
-.schema-editor-table-column-editor
- :deep(.n-data-table-tr.dropped .n-data-table-td) {
- @apply text-red-700 cursor-not-allowed !bg-red-50 opacity-70;
-}
-.schema-editor-table-column-editor
- :deep(.n-data-table-tr.updated .n-data-table-td) {
- @apply text-yellow-700 !bg-yellow-50;
-}
-</style>
diff --git a/frontend/src/components/SchemaEditorV1/Panels/TableColumnEditor/components/DataTypeCell.vue b/frontend/src/components/SchemaEditorV1/Panels/TableColumnEditor/components/DataTypeCell.vue
deleted file mode 100644
index 78e2831ecb..0000000000
--- a/frontend/src/components/SchemaEditorV1/Panels/TableColumnEditor/components/DataTypeCell.vue
+++ /dev/null
@@ -1,99 +0,0 @@
-<template>
- <DropdownInput
- :value="column.type || null"
- :allow-input-value="allowInputValue"
- :options="columnTypeOptions"
- :consistent-menu-width="true"
- :allow-filter="allowFilter"
- :style="style"
- suffix-style="right: 3px"
- placeholder="column type"
- class="bb-schema-editor--column-data-type-select"
- @focus="focused = true"
- @blur="focused = false"
- @update:value="$emit('update:value', $event)"
- />
-</template>
-
-<script lang="ts" setup>
-import type { SelectOption } from "naive-ui";
-import type { CSSProperties } from "vue";
-import { computed, ref, onMounted } from "vue";
-import { DropdownInput } from "@/components/v2";
-import type { Engine } from "@/types/proto/v1/common";
-import type { Column } from "@/types/v1/schemaEditor";
-import { getDataTypeSuggestionList } from "@/utils";
-
-const props = defineProps<{
- column: Column;
- readonly?: boolean;
- engine: Engine;
- schemaTemplateColumnTypes: string[];
-}>();
-defineEmits<{
- (event: "update:value", value: string): void;
-}>();
-
-const focused = ref(false);
-const originalType = ref("");
-
-onMounted(() => (originalType.value = props.column.type));
-
-const allowFilter = computed(() => {
- return !props.column.type || originalType.value !== props.column.type;
-});
-
-const allowInputValue = computed(() => {
- return props.schemaTemplateColumnTypes.length === 0;
-});
-
-const columnTypeOptions = computed(() => {
- const { schemaTemplateColumnTypes, engine } = props;
- if (allowInputValue.value) {
- return getDataTypeSuggestionList(engine).map<SelectOption>((dataType) => {
- return {
- value: dataType,
- label: dataType,
- };
- });
- }
- return schemaTemplateColumnTypes.map<SelectOption>((columnType) => {
- return {
- value: columnType,
- label: columnType,
- };
- });
-});
-
-const style = computed(() => {
- const style: CSSProperties = {
- "--n-padding-left": "6px",
- "--n-padding-right": "16px",
- "--n-color": "transparent",
- "--n-color-disabled": "transparent",
- "--n-text-color-disabled": "rgb(var(--color-main))",
- cursor: "default",
- };
- const border = focused.value
- ? "1px solid rgb(var(--color-control-border))"
- : "none";
- style["--n-border"] = border;
- style["--n-border-disabled"] = border;
-
- return style;
-});
-</script>
-
-<style lang="postcss" scoped>
-.bb-schema-editor--column-data-type-select :deep(.n-base-selection) {
- --n-padding-single: 0 16px 0 6px !important;
- --n-color: transparent !important;
- --n-color-disabled: transparent !important;
- --n-border: none !important;
- --n-text-color-disabled: rgb(var(--color-main)) !important;
-}
-.bb-schema-editor--column-data-type-select
- :deep(.n-base-selection .n-base-suffix) {
- right: 4px;
-}
-</style>
diff --git a/frontend/src/components/SchemaEditorV1/Panels/TableColumnEditor/components/DefaultValueCell.vue b/frontend/src/components/SchemaEditorV1/Panels/TableColumnEditor/components/DefaultValueCell.vue
deleted file mode 100644
index b38f0376ad..0000000000
--- a/frontend/src/components/SchemaEditorV1/Panels/TableColumnEditor/components/DefaultValueCell.vue
+++ /dev/null
@@ -1,101 +0,0 @@
-<template>
- <DropdownInput
- :value="value"
- :options="options"
- :placeholder="placeholder"
- :consistent-menu-width="false"
- :style="style"
- suffix-style="right: 3px"
- class="bb-schema-editor--column-default-value-select"
- @focus="focused = true"
- @blur="focused = false"
- @update:value="handleUpdateValue"
- />
-</template>
-
-<script lang="ts" setup>
-import type { SelectOption } from "naive-ui";
-import type { CSSProperties } from "vue";
-import { computed, ref } from "vue";
-import type { DefaultValueOption } from "@/components/SchemaEditorV1/utils/columnDefaultValue";
-import {
- getColumnDefaultDisplayString,
- getColumnDefaultValueOptions,
- getColumnDefaultValuePlaceholder,
- getDefaultValueByKey,
-} from "@/components/SchemaEditorV1/utils/columnDefaultValue";
-import { DropdownInput } from "@/components/v2";
-import type { Engine } from "@/types/proto/v1/common";
-import type { Column } from "@/types/v1/schemaEditor";
-
-const props = defineProps<{
- column: Column;
- engine: Engine;
-}>();
-const emit = defineEmits<{
- (event: "input", value: string): void;
- (event: "select", option: DefaultValueOption): void;
-}>();
-const focused = ref(false);
-
-const value = computed(() => {
- return getColumnDefaultDisplayString(props.column) ?? null;
-});
-
-const placeholder = computed(() => {
- return getColumnDefaultValuePlaceholder(props.column);
-});
-
-const options = computed(() => {
- return getColumnDefaultValueOptions(
- props.engine,
- props.column.type
- ).map<SelectOption>((opt) => ({
- value: opt.key,
- label: opt.label as string,
- defaultValue: opt.value,
- }));
-});
-
-const handleUpdateValue = (key: string) => {
- const value = getDefaultValueByKey(key);
- if (value) {
- emit("select", { key, value });
- return;
- }
-
- emit("input", key);
-};
-
-const style = computed(() => {
- const style: CSSProperties = {
- "--n-padding-left": "6px",
- "--n-padding-right": "16px",
- "--n-color": "transparent",
- "--n-color-disabled": "transparent",
- "--n-text-color-disabled": "rgb(var(--color-main))",
- cursor: "default",
- };
- const border = focused.value
- ? "1px solid rgb(var(--color-control-border))"
- : "none";
- style["--n-border"] = border;
- style["--n-border-disabled"] = border;
-
- return style;
-});
-</script>
-
-<style lang="postcss" scoped>
-.bb-schema-editor--column-default-value-select :deep(.n-base-selection) {
- --n-padding-single: 0 16px 0 6px !important;
- --n-color: transparent !important;
- --n-color-disabled: transparent !important;
- --n-border: none !important;
- --n-text-color-disabled: rgb(var(--color-main)) !important;
-}
-.bb-schema-editor--column-default-value-select
- :deep(.n-base-selection .n-base-suffix) {
- right: 4px;
-}
-</style>
diff --git a/frontend/src/components/SchemaEditorV1/Panels/TableColumnEditor/components/ForeignKeyCell.vue b/frontend/src/components/SchemaEditorV1/Panels/TableColumnEditor/components/ForeignKeyCell.vue
deleted file mode 100644
index 0d868a4e48..0000000000
--- a/frontend/src/components/SchemaEditorV1/Panels/TableColumnEditor/components/ForeignKeyCell.vue
+++ /dev/null
@@ -1,34 +0,0 @@
-<template>
- <div class="flex flex-row flex-wrap items-center break-all">
- <span v-if="hasForeignKey" @click="$emit('click')">
- {{ referencedForeignKeyName }}
- </span>
- <span v-else class="italic text-control-placeholder">EMPTY</span>
-
- <MiniActionButton
- v-if="!readonly"
- :disabled="disabled"
- @click="$emit('edit')"
- >
- <PenSquareIcon class="w-4 h-4" />
- </MiniActionButton>
- </div>
-</template>
-
-<script lang="ts" setup>
-import { PenSquareIcon } from "lucide-vue-next";
-import { MiniActionButton } from "@/components/v2";
-import type { Column } from "@/types/v1/schemaEditor";
-
-defineProps<{
- column: Column;
- readonly?: boolean;
- disabled: boolean;
- hasForeignKey: boolean;
- referencedForeignKeyName: string;
-}>();
-defineEmits<{
- (event: "click"): void;
- (event: "edit"): void;
-}>();
-</script>
diff --git a/frontend/src/components/SchemaEditorV1/Panels/TableColumnEditor/components/LabelsCell.vue b/frontend/src/components/SchemaEditorV1/Panels/TableColumnEditor/components/LabelsCell.vue
deleted file mode 100644
index d660f5d576..0000000000
--- a/frontend/src/components/SchemaEditorV1/Panels/TableColumnEditor/components/LabelsCell.vue
+++ /dev/null
@@ -1,24 +0,0 @@
-<template>
- <div class="flex justify-start items-center">
- <DatabaseLabelsCell :labels="column.config.labels" :show-count="1" />
- <MiniActionButton v-if="!readonly && !disabled" @click="$emit('edit')">
- <PencilIcon class="w-3 h-3" />
- </MiniActionButton>
- </div>
-</template>
-
-<script lang="ts" setup>
-import { PencilIcon } from "lucide-vue-next";
-import { MiniActionButton } from "@/components/v2";
-import { DatabaseLabelsCell } from "@/components/v2/Model/DatabaseV1Table/cells";
-import type { Column } from "@/types/v1/schemaEditor";
-
-defineProps<{
- column: Column;
- readonly?: boolean;
- disabled?: boolean;
-}>();
-defineEmits<{
- (event: "edit"): void;
-}>();
-</script>
diff --git a/frontend/src/components/SchemaEditorV1/Panels/TableColumnEditor/components/OperationCell.vue b/frontend/src/components/SchemaEditorV1/Panels/TableColumnEditor/components/OperationCell.vue
deleted file mode 100644
index 295ff15cd7..0000000000
--- a/frontend/src/components/SchemaEditorV1/Panels/TableColumnEditor/components/OperationCell.vue
+++ /dev/null
@@ -1,40 +0,0 @@
-<template>
- <div class="flex justify-start items-center">
- <NTooltip v-if="!dropped" trigger="hover" to="body">
- <template #trigger>
- <MiniActionButton tag="div" :disabled="disabled" @click="$emit('drop')">
- <TrashIcon class="w-4 h-4" />
- </MiniActionButton>
- </template>
- <span>{{ $t("schema-editor.actions.drop-table") }}</span>
- </NTooltip>
- <NTooltip v-else trigger="hover" to="body">
- <template #trigger>
- <MiniActionButton
- tag="div"
- :disabled="disabled"
- @click="$emit('restore')"
- >
- <Undo2Icon class="w-4 h-4" />
- </MiniActionButton>
- </template>
- <span>{{ $t("schema-editor.actions.restore") }}</span>
- </NTooltip>
- </div>
-</template>
-
-<script lang="ts" setup>
-import { TrashIcon, Undo2Icon } from "lucide-vue-next";
-import { MiniActionButton } from "@/components/v2";
-import type { Column } from "@/types/v1/schemaEditor";
-
-defineProps<{
- column: Column;
- dropped?: boolean;
- disabled?: boolean;
-}>();
-defineEmits<{
- (event: "drop"): void;
- (event: "restore"): void;
-}>();
-</script>
diff --git a/frontend/src/components/SchemaEditorV1/Panels/TableColumnEditor/components/ReorderCell.vue b/frontend/src/components/SchemaEditorV1/Panels/TableColumnEditor/components/ReorderCell.vue
deleted file mode 100644
index 3f58633869..0000000000
--- a/frontend/src/components/SchemaEditorV1/Panels/TableColumnEditor/components/ReorderCell.vue
+++ /dev/null
@@ -1,31 +0,0 @@
-<template>
- <div class="flex justify-start items-center">
- <MiniActionButton
- :disabled="disabled || !allowMoveUp"
- @click="$emit('reorder', -1)"
- >
- <ChevronUpIcon class="w-4 h-4" />
- </MiniActionButton>
- <MiniActionButton
- :disabled="disabled || !allowMoveDown"
- @click="$emit('reorder', 1)"
- >
- <ChevronDownIcon class="w-4 h-4" />
- </MiniActionButton>
- </div>
-</template>
-<script setup lang="ts">
-import { ChevronDownIcon, ChevronUpIcon } from "lucide-vue-next";
-import { MiniActionButton } from "@/components/v2";
-import type { Column } from "@/types/v1/schemaEditor";
-
-defineProps<{
- column: Column;
- allowMoveUp?: boolean;
- allowMoveDown?: boolean;
- disabled?: boolean;
-}>();
-defineEmits<{
- (event: "reorder", delta: -1 | 1): void;
-}>();
-</script>
diff --git a/frontend/src/components/SchemaEditorV1/Panels/TableColumnEditor/components/SemanticTypeCell.vue b/frontend/src/components/SchemaEditorV1/Panels/TableColumnEditor/components/SemanticTypeCell.vue
deleted file mode 100644
index 0533ee6cce..0000000000
--- a/frontend/src/components/SchemaEditorV1/Panels/TableColumnEditor/components/SemanticTypeCell.vue
+++ /dev/null
@@ -1,50 +0,0 @@
-<template>
- <div class="flex flex-row flex-wrap whitespace-nowrap">
- {{ semanticType?.title }}
- <template v-if="!readonly && !disabled">
- <MiniActionButton
- v-if="semanticType"
- :disabled="disableAlterColumn(column)"
- @click.prevent="$emit('remove')"
- >
- <XIcon class="w-3 h-3" />
- </MiniActionButton>
- <MiniActionButton
- :disabled="disableAlterColumn(column)"
- @click.prevent="$emit('edit')"
- >
- <PencilIcon class="w-3 h-3" />
- </MiniActionButton>
- </template>
- </div>
-</template>
-
-<script lang="ts" setup>
-import { PencilIcon, XIcon } from "lucide-vue-next";
-import { computed } from "vue";
-import { MiniActionButton } from "@/components/v2";
-import type { SemanticTypeSetting_SemanticType as SemanticType } from "@/types/proto/v1/setting_service";
-import type { Column } from "@/types/v1/schemaEditor";
-
-const props = defineProps<{
- column: Column;
- readonly?: boolean;
- disabled?: boolean;
- semanticTypeList: SemanticType[];
- disableAlterColumn: (column: Column) => boolean;
-}>();
-defineEmits<{
- (event: "edit"): void;
- (event: "remove"): void;
-}>();
-
-const semanticType = computed(() => {
- const { column, semanticTypeList } = props;
- if (!column.config.semanticTypeId) {
- return;
- }
- return semanticTypeList.find(
- (data) => data.id === column.config.semanticTypeId
- );
-});
-</script>
diff --git a/frontend/src/components/SchemaEditorV1/Panels/TableColumnEditor/components/index.ts b/frontend/src/components/SchemaEditorV1/Panels/TableColumnEditor/components/index.ts
deleted file mode 100644
index 1c5993ab50..0000000000
--- a/frontend/src/components/SchemaEditorV1/Panels/TableColumnEditor/components/index.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import DataTypeCell from "./DataTypeCell.vue";
-import DefaultValueCell from "./DefaultValueCell.vue";
-import ForeignKeyCell from "./ForeignKeyCell.vue";
-import OperationCell from "./OperationCell.vue";
-import ReorderCell from "./ReorderCell.vue";
-import SemanticTypeCell from "./SemanticTypeCell.vue";
-
-export {
- ReorderCell,
- DataTypeCell,
- DefaultValueCell,
- ForeignKeyCell,
- OperationCell,
- SemanticTypeCell,
-};
diff --git a/frontend/src/components/SchemaEditorV1/Panels/TableColumnEditor/index.ts b/frontend/src/components/SchemaEditorV1/Panels/TableColumnEditor/index.ts
deleted file mode 100644
index 17ba45a252..0000000000
--- a/frontend/src/components/SchemaEditorV1/Panels/TableColumnEditor/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import TableColumnEditor from "./TableColumnEditor.vue";
-
-export default TableColumnEditor;
diff --git a/frontend/src/components/SchemaEditorV1/Panels/TableEditor.vue b/frontend/src/components/SchemaEditorV1/Panels/TableEditor.vue
deleted file mode 100644
index 29c9e83dea..0000000000
--- a/frontend/src/components/SchemaEditorV1/Panels/TableEditor.vue
+++ /dev/null
@@ -1,427 +0,0 @@
-<template>
- <div class="flex flex-col pt-2 gap-y-2 w-full h-full overflow-y-hidden">
- <div
- v-if="!readonly"
- class="w-full flex flex-row justify-between items-center"
- >
- <div>
- <div class="w-full flex justify-between items-center space-x-2">
- <NButton
- size="small"
- :disabled="disableChangeTable"
- @click="handleAddColumn"
- >
- <heroicons-outline:plus class="w-4 h-auto mr-1 text-gray-400" />
- {{ $t("schema-editor.actions.add-column") }}
- </NButton>
- <NButton
- size="small"
- :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") }}
- </NButton>
- </div>
- </div>
- </div>
-
- <div class="flex-1 overflow-y-hidden">
- <TableColumnEditor
- :readonly="readonly"
- :show-foreign-key="true"
- :table="table"
- :engine="engine"
- :foreign-key-list="foreignKeyList"
- :classification-config-id="project.dataClassificationConfigId"
- :disable-change-table="disableChangeTable"
- :allow-reorder-columns="allowReorderColumns"
- :filter-column="
- (column: Column) => column.name.includes(props.searchPattern.trim())
- "
- :disable-alter-column="disableAlterColumn"
- :get-referenced-foreign-key-name="getReferencedForeignKeyName"
- :get-column-item-computed-class-list="getColumnItemComputedClassList"
- @drop="handleDropColumn"
- @restore="handleRestoreColumn"
- @reorder="handleReorderColumn"
- @primary-key-set="setColumnPrimaryKey"
- @foreign-key-edit="handleEditColumnForeignKey"
- @foreign-key-click="gotoForeignKeyReferencedTable"
- />
- </div>
- </div>
-
- <EditColumnForeignKeyModal
- v-if="state.showEditColumnForeignKeyModal && editForeignKeyColumn"
- :parent-name="currentTab.parentName"
- :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
- :engine="engine"
- :readonly="true"
- @apply="handleApplyColumnTemplate"
- />
- </div>
- </DrawerContent>
- </Drawer>
- <FeatureModal
- feature="bb.feature.schema-template"
- :open="state.showFeatureModal"
- @cancel="state.showFeatureModal = false"
- />
-</template>
-
-<script lang="ts" setup>
-import { isUndefined, flatten } from "lodash-es";
-import scrollIntoView from "scroll-into-view-if-needed";
-import { computed, nextTick, reactive, ref } from "vue";
-import { useI18n } from "vue-i18n";
-import { Drawer, DrawerContent } from "@/components/v2";
-import {
- hasFeature,
- generateUniqueTabId,
- useSchemaEditorV1Store,
- pushNotification,
-} from "@/store/modules";
-import { Engine } from "@/types/proto/v1/common";
-import { ColumnMetadata } from "@/types/proto/v1/database_service";
-import type { SchemaTemplateSetting_FieldTemplate } from "@/types/proto/v1/setting_service";
-import type {
- Column,
- Table,
- Schema,
- ForeignKey,
-} from "@/types/v1/schemaEditor";
-import {
- convertColumnMetadataToColumn,
- SchemaEditorTabType,
-} from "@/types/v1/schemaEditor";
-import type { TableTabContext } from "@/types/v1/schemaEditor";
-import { arraySwap, instanceV1AllowsReorderColumns } from "@/utils";
-import FieldTemplates from "@/views/SchemaTemplate/FieldTemplates.vue";
-import EditColumnForeignKeyModal from "../Modals/EditColumnForeignKeyModal.vue";
-import { isColumnChanged } from "../utils";
-import TableColumnEditor from "./TableColumnEditor";
-
-const props = withDefaults(
- defineProps<{
- searchPattern: string;
- }>(),
- {
- searchPattern: "",
- }
-);
-
-interface LocalState {
- showEditColumnForeignKeyModal: boolean;
- showSchemaTemplateDrawer: boolean;
- showFeatureModal: boolean;
-}
-
-const { t } = useI18n();
-const schemaEditorV1Store = useSchemaEditorV1Store();
-const currentTab = computed(
- () => schemaEditorV1Store.currentTab as TableTabContext
-);
-
-const parentResource = computed(() => {
- return schemaEditorV1Store.resourceMap[schemaEditorV1Store.resourceType].get(
- currentTab.value.parentName
- )!;
-});
-const engine = computed(() => {
- return schemaEditorV1Store.getCurrentEngine(currentTab.value.parentName);
-});
-const readonly = computed(() => schemaEditorV1Store.readonly);
-const project = computed(() => schemaEditorV1Store.project);
-const state = reactive<LocalState>({
- showEditColumnForeignKeyModal: false,
- showSchemaTemplateDrawer: false,
- showFeatureModal: false,
-});
-
-const schema = computed(() => {
- return schemaEditorV1Store.getSchema(
- currentTab.value.parentName,
- currentTab.value.schemaId
- ) as Schema;
-});
-const table = computed(
- () =>
- schema.value.tableList.find(
- (table) => table.id === currentTab.value.tableId
- ) as Table
-);
-const foreignKeyList = computed(() => {
- return table.value.foreignKeyList.filter(
- (pk) => pk.tableId === currentTab.value.tableId
- ) as ForeignKey[];
-});
-
-const editForeignKeyColumn = ref<Column>();
-
-const isDroppedSchema = computed(() => {
- return schema.value.status === "dropped";
-});
-
-const isDroppedTable = computed(() => {
- return table.value.status === "dropped";
-});
-
-const getColumnItemComputedClassList = (column: Column): string => {
- if (column.status === "dropped") {
- return "dropped";
- } else if (column.status === "created") {
- return "created";
- } else if (
- isColumnChanged(
- currentTab.value.parentName,
- currentTab.value.schemaId,
- currentTab.value.tableId,
- column.id
- )
- ) {
- return "updated";
- }
- return "";
-};
-
-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 = parentResource.value.schemaList.find(
- (schema) => schema.id === fk.referencedSchemaId
- );
- const referencedTable = referencedSchema?.tableList.find(
- (table) => table.id === fk.referencedTableId
- );
- if (!referencedTable) {
- return "";
- }
- const referColumn = referencedTable.columnList.find(
- (column) => column.id === fk.referencedColumnIdList[index]
- );
- if (engine.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 allowReorderColumns = computed(() => {
- if (props.searchPattern.trim().length !== 0) {
- // The column keyword filter will break the original indexes of columns
- return false;
- }
-
- return (
- instanceV1AllowsReorderColumns(engine.value) &&
- table.value.status === "created"
- );
-});
-
-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 handleAddColumn = () => {
- const column = convertColumnMetadataToColumn(
- ColumnMetadata.fromPartial({}),
- "created"
- );
- table.value.columnList.push(column);
- nextTick(() => {
- const container = document.querySelector("#table-editor-container");
- (
- container?.querySelector(
- `.column-${column.id} .column-name-input`
- ) as HTMLInputElement
- )?.focus();
- });
-};
-
-const handleApplyColumnTemplate = (
- template: SchemaTemplateSetting_FieldTemplate
-) => {
- state.showSchemaTemplateDrawer = false;
- if (!hasFeature("bb.feature.schema-template")) {
- state.showFeatureModal = true;
- return;
- }
- if (template.engine !== engine.value || !template.column) {
- return;
- }
- const column = convertColumnMetadataToColumn(
- template.column,
- "created",
- template.config
- );
- table.value.columnList.push(column);
-};
-
-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 = parentResource.value.schemaList.find(
- (schema) => schema.id === fk.referencedSchemaId
- );
- const referencedTable = referencedSchema?.tableList.find(
- (table) => table.id === fk.referencedTableId
- );
- if (!referencedTable) {
- return;
- }
- const referColumn = referencedTable?.columnList.find(
- (column) => column.id === fk.referencedColumnIdList[index]
- );
- if (!referencedSchema || !referencedTable || !referColumn) {
- return;
- }
-
- schemaEditorV1Store.addTab({
- id: generateUniqueTabId(),
- type: SchemaEditorTabType.TabForTable,
- parentName: currentTab.value.parentName,
- schemaId: referencedSchema.id,
- tableId: referencedTable.id,
- name: referencedTable.name,
- });
-
- 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) => {
- // Disallow to drop the last column.
- if (
- table.value.columnList.filter((column) => column.status !== "dropped")
- .length === 1
- ) {
- pushNotification({
- module: "bytebase",
- style: "CRITICAL",
- title: t("schema-editor.message.cannot-drop-the-last-column"),
- });
- return;
- }
-
- 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 = table.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 handleReorderColumn = (column: Column, index: number, delta: -1 | 1) => {
- const target = index + delta;
- const { columnList } = table.value;
- if (target < 0) return;
- if (target >= columnList.length) return;
-
- arraySwap(columnList, index, target);
-};
-</script>
diff --git a/frontend/src/components/SchemaEditorV1/Panels/TableList/TableList.vue b/frontend/src/components/SchemaEditorV1/Panels/TableList/TableList.vue
deleted file mode 100644
index d6d2eb0401..0000000000
--- a/frontend/src/components/SchemaEditorV1/Panels/TableList/TableList.vue
+++ /dev/null
@@ -1,346 +0,0 @@
-<template>
- <div
- ref="containerElRef"
- class="w-full h-full"
- :data-height="containerHeight"
- :data-table-header-height="tableHeaderHeight"
- :data-table-body-height="tableBodyHeight"
- >
- <NDataTable
- v-bind="$attrs"
- size="small"
- :row-key="(table: Table) => table.id"
- :columns="columns"
- :data="layoutReady ? tableList : []"
- :row-class-name="classesForRow"
- :max-height="tableBodyHeight"
- :virtual-scroll="true"
- :striped="true"
- :bordered="true"
- :bottom-bordered="true"
- class="schema-editor-table-list"
- />
- </div>
-
- <TableNameModal
- v-if="state.tableNameModalContext !== undefined"
- :parent-name="state.tableNameModalContext.parentName"
- :schema-id="state.tableNameModalContext.schemaId"
- :table-name="state.tableNameModalContext.tableName"
- @close="state.tableNameModalContext = undefined"
- />
-
- <Drawer
- :show="state.showSchemaTemplateDrawer"
- @close="state.showSchemaTemplateDrawer = false"
- >
- <DrawerContent :title="$t('schema-template.table-template.self')">
- <div class="w-[calc(100vw-36rem)] min-w-[64rem] max-w-[calc(100vw-8rem)]">
- <TableTemplates
- :engine="engine"
- :readonly="true"
- @apply="handleApplyTemplate"
- />
- </div>
- </DrawerContent>
- </Drawer>
-
- <FeatureModal
- feature="bb.feature.schema-template"
- :open="state.showFeatureModal"
- @cancel="state.showFeatureModal = false"
- />
-</template>
-
-<script lang="ts" setup>
-import { useElementSize } from "@vueuse/core";
-import type { DataTableColumn } from "naive-ui";
-import { NDataTable } from "naive-ui";
-import { computed, h, reactive, ref } from "vue";
-import { useI18n } from "vue-i18n";
-import ClassificationCell from "@/components/ColumnDataTable/ClassificationCell.vue";
-import FeatureModal from "@/components/FeatureGuard/FeatureModal.vue";
-import { Drawer, DrawerContent } from "@/components/v2";
-import {
- hasFeature,
- generateUniqueTabId,
- useSettingV1Store,
- useSchemaEditorV1Store,
-} from "@/store";
-import type { SchemaTemplateSetting_TableTemplate } from "@/types/proto/v1/setting_service";
-import { DataClassificationSetting_DataClassificationConfig as DataClassificationConfig } from "@/types/proto/v1/setting_service";
-import type { Table, DatabaseTabContext } from "@/types/v1/schemaEditor";
-import {
- SchemaEditorTabType,
- convertTableMetadataToTable,
-} from "@/types/v1/schemaEditor";
-import { bytesToString } from "@/utils";
-import TableTemplates from "@/views/SchemaTemplate/TableTemplates.vue";
-import TableNameModal from "../../Modals/TableNameModal.vue";
-import { isTableChanged } from "../../utils";
-import { NameCell, OperationCell } from "./components";
-
-const props = defineProps<{
- schemaId: string;
- tableList: Table[];
-}>();
-
-interface LocalState {
- showFeatureModal: boolean;
- showSchemaTemplateDrawer: boolean;
- tableNameModalContext?: {
- parentName: string;
- schemaId: string;
- tableName: string | undefined;
- };
- activeTableId?: string;
-}
-
-const { t } = useI18n();
-const containerElRef = ref<HTMLElement>();
-const tableHeaderElRef = computed(
- () =>
- containerElRef.value?.querySelector("thead.n-data-table-thead") as
- | HTMLElement
- | undefined
-);
-const { height: containerHeight } = useElementSize(containerElRef);
-const { height: tableHeaderHeight } = useElementSize(tableHeaderElRef);
-const tableBodyHeight = computed(() => {
- return containerHeight.value - tableHeaderHeight.value - 2;
-});
-// Use this to avoid unnecessary initial rendering
-const layoutReady = computed(() => tableHeaderHeight.value > 0);
-const editorStore = useSchemaEditorV1Store();
-const settingStore = useSettingV1Store();
-const currentTab = computed(
- () => (editorStore.currentTab || {}) as DatabaseTabContext
-);
-const state = reactive<LocalState>({
- showFeatureModal: false,
- showSchemaTemplateDrawer: false,
-});
-
-const engine = computed(() => {
- return editorStore.getCurrentEngine(currentTab.value.parentName);
-});
-const readonly = computed(() => editorStore.readonly);
-
-const schemaList = computed(() => {
- return editorStore.currentSchemaList;
-});
-const tableList = computed(() => {
- return props.tableList;
-});
-
-const classificationConfig = computed(() => {
- if (!editorStore.project.dataClassificationConfigId) {
- return;
- }
- return settingStore.getProjectClassification(
- editorStore.project.dataClassificationConfigId
- );
-});
-
-const onClassificationSelect = (classificationId: string) => {
- const table = tableList.value.find(
- (table) => table.id === state.activeTableId
- );
- if (!table) {
- return;
- }
- table.config.classificationId = classificationId;
- state.activeTableId = undefined;
-};
-
-const columns = computed(() => {
- const columns: (DataTableColumn<Table> & { hide?: boolean })[] = [
- {
- key: "name",
- title: t("schema-editor.database.name"),
- resizable: true,
- width: 140,
- className: "truncate",
- render: (table) => {
- return h(NameCell, {
- table,
- onClick: () => handleTableItemClick(table),
- });
- },
- },
- {
- key: "classification",
- title: t("schema-editor.column.classification"),
- resizable: true,
- width: 140,
- hide: !classificationConfig.value,
- render: (table) => {
- return h(ClassificationCell, {
- classification: table.config.classificationId,
- readonly: readonly.value,
- disabled: !disableChangeTable(table),
- classificationConfig:
- classificationConfig.value ??
- DataClassificationConfig.fromPartial({}),
- onApply: (id: string) => {
- state.activeTableId = table.id;
- onClassificationSelect(id);
- },
- });
- },
- },
- {
- key: "rowCount",
- title: t("schema-editor.database.row-count"),
- resizable: true,
- width: 120,
- render: (table) => {
- return table.rowCount.toString();
- },
- },
- {
- key: "dataSize",
- title: t("schema-editor.database.data-size"),
- resizable: true,
- width: 120,
- render: (table) => {
- return bytesToString(table.dataSize.toNumber());
- },
- },
- {
- key: "engine",
- title: t("schema-editor.database.engine"),
- resizable: true,
- width: 120,
- render: (table) => {
- return table.engine;
- },
- },
- {
- key: "collation",
- title: t("schema-editor.database.collation"),
- resizable: true,
- width: 120,
- ellipsis: true,
- ellipsisComponent: "performant-ellipsis",
- },
- {
- key: "comment",
- title: t("schema-editor.database.comment"),
- resizable: true,
- width: 140,
- ellipsis: true,
- ellipsisComponent: "performant-ellipsis",
- },
- {
- key: "operations",
- title: "",
- resizable: false,
- width: 30,
- hide: readonly.value,
- className: "!px-0",
- render: (table) => {
- return h(OperationCell, {
- table,
- dropped: isDroppedTable(table),
- onDrop: () => handleDropTable(table),
- onRestore: () => handleRestoreTable(table),
- });
- },
- },
- ];
- return columns.filter((header) => !header.hide);
-});
-
-const classesForRow = (table: Table, index: number) => {
- if (table.status === "dropped") {
- return "dropped";
- } else if (table.status === "created") {
- return "created";
- } else if (
- isTableChanged(currentTab.value.parentName, props.schemaId, table.id)
- ) {
- return "updated";
- }
- return "";
-};
-
-const handleTableItemClick = (table: Table) => {
- editorStore.addTab({
- id: generateUniqueTabId(),
- type: SchemaEditorTabType.TabForTable,
- parentName: currentTab.value.parentName,
- schemaId: props.schemaId,
- tableId: table.id,
- name: table.name,
- });
-};
-
-const handleDropTable = (table: Table) => {
- editorStore.dropTable(currentTab.value.parentName, props.schemaId, table.id);
-};
-
-const handleRestoreTable = (table: Table) => {
- editorStore.restoreTable(
- currentTab.value.parentName,
- props.schemaId,
- table.id
- );
-};
-
-const handleApplyTemplate = (template: SchemaTemplateSetting_TableTemplate) => {
- state.showSchemaTemplateDrawer = false;
- if (!hasFeature("bb.feature.schema-template")) {
- state.showFeatureModal = true;
- return;
- }
- if (!template.table || template.engine !== engine.value) {
- return;
- }
-
- const tableEdit = convertTableMetadataToTable(
- template.table,
- "created",
- template.config
- );
-
- const selectedSchema = schemaList.value.find(
- (schema) => schema.id === props.schemaId
- );
- if (selectedSchema) {
- selectedSchema.tableList.push(tableEdit);
- editorStore.addTab({
- id: generateUniqueTabId(),
- type: SchemaEditorTabType.TabForTable,
- parentName: currentTab.value.parentName,
- schemaId: props.schemaId,
- tableId: tableEdit.id,
- name: template.table.name,
- });
- }
-};
-
-const disableChangeTable = (table: Table): boolean => {
- return table.status === "dropped";
-};
-const isDroppedTable = (table: Table) => {
- return table.status === "dropped";
-};
-</script>
-
-<style lang="postcss" scoped>
-.schema-editor-table-list
- :deep(.n-data-table-th .n-data-table-resize-button::after) {
- @apply bg-control-bg h-2/3;
-}
-.schema-editor-table-list :deep(.n-data-table-tr.created .n-data-table-td) {
- @apply text-green-700 !bg-green-50;
-}
-.schema-editor-table-list :deep(.n-data-table-tr.dropped .n-data-table-td) {
- @apply text-red-700 !bg-red-50 opacity-70;
-}
-
-.schema-editor-table-list :deep(.n-data-table-tr.updated .n-data-table-td) {
- @apply text-yellow-700 !bg-yellow-50;
-}
-</style>
diff --git a/frontend/src/components/SchemaEditorV1/Panels/TableList/components/NameCell.vue b/frontend/src/components/SchemaEditorV1/Panels/TableList/components/NameCell.vue
deleted file mode 100644
index f5c84f3ee7..0000000000
--- a/frontend/src/components/SchemaEditorV1/Panels/TableList/components/NameCell.vue
+++ /dev/null
@@ -1,21 +0,0 @@
-<template>
- <NPerformantEllipsis
- class="w-full cursor-pointer leading-6 hover:text-accent"
- >
- <span @click="$emit('click')">
- {{ table.name }}
- </span>
- </NPerformantEllipsis>
-</template>
-
-<script lang="ts" setup>
-import { NPerformantEllipsis } from "naive-ui";
-import type { Table } from "@/types/v1/schemaEditor";
-
-defineProps<{
- table: Table;
-}>();
-defineEmits<{
- (event: "click"): void;
-}>();
-</script>
diff --git a/frontend/src/components/SchemaEditorV1/Panels/TableList/components/OperationCell.vue b/frontend/src/components/SchemaEditorV1/Panels/TableList/components/OperationCell.vue
deleted file mode 100644
index 4104f9a28a..0000000000
--- a/frontend/src/components/SchemaEditorV1/Panels/TableList/components/OperationCell.vue
+++ /dev/null
@@ -1,34 +0,0 @@
-<template>
- <div class="flex justify-start items-center">
- <NTooltip v-if="!dropped" trigger="hover" to="body">
- <template #trigger>
- <heroicons:trash
- class="w-4 h-auto text-gray-500 cursor-pointer hover:opacity-80"
- @click="$emit('drop')"
- />
- </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-4 h-auto text-gray-500 cursor-pointer hover:opacity-80"
- @click="$emit('restore')"
- />
- </template>
- <span>{{ $t("schema-editor.actions.restore") }}</span>
- </NTooltip>
- </div>
-</template>
-<script lang="ts" setup>
-import type { Table } from "@/types/v1/schemaEditor";
-
-defineProps<{
- table: Table;
- dropped?: boolean;
-}>();
-defineEmits<{
- (event: "drop"): void;
- (event: "restore"): void;
-}>();
-</script>
diff --git a/frontend/src/components/SchemaEditorV1/Panels/TableList/components/index.ts b/frontend/src/components/SchemaEditorV1/Panels/TableList/components/index.ts
deleted file mode 100644
index bf413e69c5..0000000000
--- a/frontend/src/components/SchemaEditorV1/Panels/TableList/components/index.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-import NameCell from "./NameCell.vue";
-import OperationCell from "./OperationCell.vue";
-
-export { NameCell, OperationCell };
diff --git a/frontend/src/components/SchemaEditorV1/Panels/TableList/index.ts b/frontend/src/components/SchemaEditorV1/Panels/TableList/index.ts
deleted file mode 100644
index 71642de4c4..0000000000
--- a/frontend/src/components/SchemaEditorV1/Panels/TableList/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import TableList from "./TableList.vue";
-
-export default TableList;
diff --git a/frontend/src/components/SchemaEditorV1/TabsContainer.vue b/frontend/src/components/SchemaEditorV1/TabsContainer.vue
deleted file mode 100644
index f3827bb8db..0000000000
--- a/frontend/src/components/SchemaEditorV1/TabsContainer.vue
+++ /dev/null
@@ -1,175 +0,0 @@
-<template>
- <div class="flex justify-between items-center">
- <div
- class="relative flex flex-1 flex-nowrap overflow-hidden overflow bg-gray-100 select-none shrink-0 rounded"
- >
- <div
- ref="tabsContainerRef"
- class="flex flex-nowrap overflow-x-auto max-x-full hide-scrollbar overscroll-none px-1 space-x-1"
- >
- <div
- v-for="tab in tabList"
- ref="tabsContainerRef"
- :key="tab.id"
- :class="[
- `relative px-1 py-1 my-1 rounded w-40 flex flex-row justify-between items-center shrink-0 border border-transparent cursor-pointer`,
- `tab-${tab.id}`,
- tab.id === currentTab?.id && 'bg-white border-gray-200 shadow',
- ]"
- @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-if="tab.type === SchemaEditorTabType.TabForTable"
- class="rounded w-4 h-auto text-gray-400"
- />
- </span>
- <NEllipsis
- class="text-sm w-20 leading-4"
- :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>
- </div>
- </div>
- <div v-if="currentTab" class="pl-2">
- <NInput
- v-model:value="searchPattern"
- class="!w-40"
- :placeholder="searchBoxPlaceholder"
- @input="handleSearchBoxInput"
- >
- <template #prefix>
- <heroicons-outline:search class="w-4 h-auto text-gray-300" />
- </template>
- </NInput>
- </div>
- </div>
-</template>
-
-<script lang="ts" setup>
-import { NEllipsis, NInput } from "naive-ui";
-import scrollIntoView from "scroll-into-view-if-needed";
-import { computed, nextTick, ref, watch } from "vue";
-import { useI18n } from "vue-i18n";
-import { useSchemaEditorV1Store } from "@/store";
-import type { TabContext } from "@/types/v1/schemaEditor";
-import { SchemaEditorTabType } from "@/types/v1/schemaEditor";
-import { isTableChanged } from "./utils";
-
-const emit = defineEmits<{
- (event: "onTableSearchPattern", tableSearchPattern: string): void;
- (event: "onColumnSearchPattern", columnSearchPattern: string): void;
-}>();
-
-const { t } = useI18n();
-const schemaEditorV1Store = useSchemaEditorV1Store();
-const tabsContainerRef = ref();
-const searchPattern = ref("");
-const originalTabContext = ref<TabContext | undefined>(undefined);
-
-const tabList = computed(() => {
- return schemaEditorV1Store.tabList;
-});
-const currentTab = computed(() => {
- return schemaEditorV1Store.currentTab;
-});
-
-const searchBoxPlaceholder = computed(() => {
- return currentTab.value?.type === SchemaEditorTabType.TabForDatabase
- ? t("schema-editor.search-table")
- : currentTab.value?.type === SchemaEditorTabType.TabForTable
- ? t("schema-editor.search-column")
- : "";
-});
-
-const handleSearchBoxInput = (value: string) => {
- if (currentTab.value?.type === SchemaEditorTabType.TabForDatabase) {
- emit("onTableSearchPattern", value);
- } else if (currentTab.value?.type === SchemaEditorTabType.TabForTable) {
- emit("onColumnSearchPattern", value);
- }
-};
-
-watch(
- () => currentTab.value,
- () => {
- if (currentTab.value !== originalTabContext.value) {
- searchPattern.value = "";
- originalTabContext.value = 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 = schemaEditorV1Store.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.parentName, tab.schemaId, tab.tableId)) {
- return ["text-yellow-700"];
- }
- }
- return [];
-};
-
-const getTabName = (tab: TabContext) => {
- if (tab.name) {
- return tab.name;
- }
- if (tab.type === SchemaEditorTabType.TabForDatabase) {
- if (schemaEditorV1Store.resourceType === "branch") {
- return "Tables";
- }
- const database = schemaEditorV1Store.databaseList.find(
- (database) => database.name === tab.parentName
- );
- return database?.databaseName || "Uknown database";
- } else if (tab.type === SchemaEditorTabType.TabForTable) {
- const table = schemaEditorV1Store.getTableWithTableTab(tab);
- return table?.name || "Uknown table";
- } else {
- // Should never reach here.
- return "unknown tab";
- }
-};
-
-const handleSelectTab = (tab: TabContext) => {
- schemaEditorV1Store.setCurrentTab(tab.id);
-};
-
-const handleCloseTab = (tab: TabContext) => {
- schemaEditorV1Store.closeTab(tab.id);
-};
-</script>
diff --git a/frontend/src/components/SchemaEditorV1/index.vue b/frontend/src/components/SchemaEditorV1/index.vue
deleted file mode 100644
index 9d99272c73..0000000000
--- a/frontend/src/components/SchemaEditorV1/index.vue
+++ /dev/null
@@ -1,228 +0,0 @@
-<template>
- <div
- class="w-full h-full border rounded-lg overflow-hidden relative"
- v-bind="$attrs"
- >
- <MaskSpinner v-if="mergedLoading" />
-
- <Splitpanes
- v-if="state.initialized"
- class="default-theme w-full h-full flex flex-row overflow-hidden relative"
- >
- <Pane min-size="15" size="25">
- <Aside />
- </Pane>
- <Pane min-size="60" size="75">
- <Editor />
- </Pane>
- </Splitpanes>
- </div>
-</template>
-
-<script lang="ts" setup>
-import { isEqual } from "lodash-es";
-import { Splitpanes, Pane } from "splitpanes";
-import { onMounted, watch, reactive, computed } from "vue";
-import { useSchemaEditorV1Store, useSettingV1Store } from "@/store";
-import { useBranchStore } from "@/store/modules/branch";
-import type { ComposedProject, ComposedDatabase } from "@/types";
-import type { Branch } from "@/types/proto/v1/branch_service";
-import type { BranchSchema } from "@/types/v1/schemaEditor";
-import { nextAnimationFrame } from "@/utils";
-import MaskSpinner from "../misc/MaskSpinner.vue";
-import Aside from "./Aside/index.vue";
-import Editor from "./Editor.vue";
-import { convertBranchToBranchSchema } from "./utils/branch";
-
-const props = defineProps<{
- project: ComposedProject;
- resourceType: "database" | "branch";
- readonly?: boolean;
- databases?: ComposedDatabase[];
- // NOTE: we only support editing one branch for now.
- branches?: Branch[];
- loading?: boolean;
-}>();
-
-interface LocalState {
- loading: boolean;
- initialized: boolean;
-}
-
-const settingStore = useSettingV1Store();
-const schemaEditorV1Store = useSchemaEditorV1Store();
-const branchStore = useBranchStore();
-const state = reactive<LocalState>({
- loading: false,
- initialized: false,
-});
-
-const mergedLoading = computed(() => {
- return props.loading || state.loading;
-});
-
-const prepareBranchContext = async () => {
- if (props.resourceType !== "branch" || !props.branches) {
- return;
- }
- for (const branch of props.branches) {
- if (branch.parentBranch !== "") {
- // Prepare parent branch for personal draft.
- await branchStore.fetchBranchByName(
- branch.parentBranch,
- true /* useCache */
- );
- }
- }
-};
-
-const batchConvertBranchSchemas = async (branches: Branch[]) => {
- try {
- state.loading = true;
- await nextAnimationFrame();
- return await Promise.all(
- branches.map<Promise<[string, BranchSchema]>>(async (branch) => {
- return [branch.name, await convertBranchToBranchSchema(branch)];
- })
- );
- } finally {
- state.loading = false;
- }
-};
-
-const initialSchemaEditorState = async () => {
- schemaEditorV1Store.setState({
- project: props.project,
- resourceType: props.resourceType,
- // NOTE: this will clear all tabs. We will restore tabs as needed later.
- tabState: {
- tabMap: new Map(),
- },
- readonly: props.readonly || false,
- });
-
- if (props.resourceType === "database") {
- schemaEditorV1Store.setState({
- resourceMap: {
- // NOTE: we will dynamically fetch schema list for each database in database tree view.
- database: new Map(
- (props.databases || []).map((database) => [
- database.name,
- {
- database,
- schemaList: [],
- originSchemaList: [],
- },
- ])
- ),
- branch: new Map(),
- },
- });
- } else {
- schemaEditorV1Store.setState({
- resourceMap: {
- database: new Map(),
- branch: new Map(await batchConvertBranchSchemas(props.branches ?? [])),
- },
- });
- }
-};
-
-// Prepare schema template contexts.
-onMounted(async () => {
- await settingStore.getOrFetchSettingByName("bb.workspace.schema-template");
- await prepareBranchContext();
- await initialSchemaEditorState();
- state.initialized = true;
-});
-
-watch(
- () => props,
- () => {
- schemaEditorV1Store.setState({
- project: props.project,
- resourceType: props.resourceType,
- readonly: props.readonly || false,
- });
- },
- {
- deep: true,
- }
-);
-
-watch(
- [() => props.databases, () => props.branches],
- async ([newDatabases, newBranches], [oldDatabases, oldBranches]) => {
- // Update editor state if needed.
- // * If we update databases/branches, we need to rebuild the editing state.
- // * If we update databases/branches, we need to clear all tabs.
- if (props.resourceType === "database") {
- if (isEqual(newDatabases, oldDatabases)) {
- return;
- }
- schemaEditorV1Store.setState({
- tabState: {
- tabMap: new Map(),
- },
- resourceMap: {
- // NOTE: we will dynamically fetch schema list for each database in database tree view.
- database: new Map(
- (newDatabases || []).map((database) => [
- database.name,
- {
- database,
- schemaList: [],
- originSchemaList: [],
- },
- ])
- ),
- branch: new Map(),
- },
- });
- } else {
- if (isEqual(newBranches, oldBranches)) {
- return;
- }
- schemaEditorV1Store.setState({
- tabState: {
- tabMap: new Map(),
- },
- resourceMap: {
- database: new Map(),
- branch: new Map(await batchConvertBranchSchemas(newBranches ?? [])),
- },
- });
- }
- },
- {
- deep: true,
- }
-);
-</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/SchemaEditorV1/utils/branch.ts b/frontend/src/components/SchemaEditorV1/utils/branch.ts
deleted file mode 100644
index 27e72e13dd..0000000000
--- a/frontend/src/components/SchemaEditorV1/utils/branch.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import { markRaw } from "vue";
-import type { Branch } from "@/types/proto/v1/branch_service";
-import { DatabaseMetadata } from "@/types/proto/v1/database_service";
-import type { BranchSchema } from "@/types/v1/schemaEditor";
-import { convertSchemaMetadataList } from "@/types/v1/schemaEditor";
-import { rebuildEditableSchemas } from "./metadata";
-
-export const convertBranchToBranchSchema = async (
- branch: Branch
-): Promise<BranchSchema> => {
- const baselineMetadata =
- branch.baselineSchemaMetadata || DatabaseMetadata.fromPartial({});
- const originalSchemas = convertSchemaMetadataList(
- baselineMetadata.schemas || [],
- baselineMetadata.schemaConfigs || []
- );
-
- const editableSchemas = rebuildEditableSchemas(
- originalSchemas,
- branch.schemaMetadata?.schemas || [],
- branch.schemaMetadata?.schemaConfigs || []
- );
-
- return {
- branch: markRaw(branch),
- schemaList: editableSchemas,
- originSchemaList: markRaw(originalSchemas),
- };
-};
diff --git a/frontend/src/components/SchemaEditorV1/utils/column.ts b/frontend/src/components/SchemaEditorV1/utils/column.ts
deleted file mode 100644
index fc5133baf1..0000000000
--- a/frontend/src/components/SchemaEditorV1/utils/column.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-import { isEqual, isUndefined } from "lodash-es";
-import { useSchemaEditorV1Store } from "@/store";
-
-export const isColumnChanged = (
- parentName: string,
- schemaId: string,
- tableId: string,
- columnId: string
-): boolean => {
- const schemaEditorV1Store = useSchemaEditorV1Store();
- const table = schemaEditorV1Store.getTable(parentName, schemaId, tableId);
- const originTable = schemaEditorV1Store.getOriginTable(
- parentName,
- schemaId,
- 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 = originTable?.foreignKeyList.find(
- (fk) => fk.tableId === table?.id && fk.columnIdList.includes(columnId)
- );
- const foreignKey = table?.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/SchemaEditorV1/utils/columnDefaultValue.ts b/frontend/src/components/SchemaEditorV1/utils/columnDefaultValue.ts
deleted file mode 100644
index 28a50c7c34..0000000000
--- a/frontend/src/components/SchemaEditorV1/utils/columnDefaultValue.ts
+++ /dev/null
@@ -1,178 +0,0 @@
-import type { DropdownOption } from "naive-ui";
-import { t } from "@/plugins/i18n";
-import { Engine } from "@/types/proto/v1/common";
-import type { ColumnDefaultValue } from "@/types/v1/schemaEditor";
-
-interface DefaultValue {
- hasDefault: boolean;
- defaultNull?: boolean;
- defaultString?: string;
- defaultExpression?: string;
-}
-
-export interface DefaultValueOption {
- key: string;
- value: DefaultValue;
-}
-
-const NO_DEFAULT_OPTION: DefaultValueOption = {
- key: "no-default",
- value: {
- hasDefault: false,
- },
-};
-
-const EMPTY_STRING_OPTION: DefaultValueOption = {
- key: "empty-string",
- value: {
- hasDefault: true,
- defaultString: "",
- },
-};
-
-const EXPRESSION_OPTION: DefaultValueOption = {
- key: "expression",
- value: {
- hasDefault: true,
- defaultExpression: "",
- },
-};
-
-const INT_ZERO_OPTION: DefaultValueOption = {
- key: "zero",
- value: {
- hasDefault: true,
- defaultExpression: "0",
- },
-};
-
-const BOOLEAN_TRUE_OPTION: DefaultValueOption = {
- key: "true",
- value: {
- hasDefault: true,
- defaultExpression: "true",
- },
-};
-
-const BOOLEAN_FALSE_OPTION: DefaultValueOption = {
- key: "false",
- value: {
- hasDefault: true,
- defaultExpression: "false",
- },
-};
-
-export const isTextOfColumnType = (_: Engine, columnType: string) => {
- const type = columnType.toUpperCase();
- if (
- type === "TEXT" ||
- type.startsWith("VARCHAR") ||
- type.startsWith("CHAR")
- ) {
- return true;
- }
- return false;
-};
-
-export const getColumnTypeDefaultValueOptions = (
- engine: Engine,
- columnType: string
-): DefaultValueOption[] => {
- const type = columnType.toUpperCase();
- if (engine === Engine.MYSQL || engine === Engine.TIDB) {
- if (
- type === "TEXT" ||
- type.startsWith("VARCHAR") ||
- type.startsWith("CHAR")
- ) {
- return [NO_DEFAULT_OPTION, EMPTY_STRING_OPTION, EXPRESSION_OPTION];
- } else if (
- type === "INTEGER" ||
- type === "INT" ||
- type === "SMALLINT" ||
- type === "TINYINT" ||
- type === "MEDIUMINT" ||
- type === "BIGINT"
- ) {
- return [NO_DEFAULT_OPTION, INT_ZERO_OPTION, EXPRESSION_OPTION];
- } else if (type === "FLOAT" || type === "DOUBLE") {
- return [NO_DEFAULT_OPTION, INT_ZERO_OPTION];
- } else if (type === "BOOL" || type === "BOOLEAN") {
- return [NO_DEFAULT_OPTION, BOOLEAN_TRUE_OPTION, BOOLEAN_FALSE_OPTION];
- }
- } else if (engine === Engine.POSTGRES) {
- if (
- type === "TEXT" ||
- type.startsWith("VARCHAR") ||
- type.startsWith("CHAR")
- ) {
- return [NO_DEFAULT_OPTION, EMPTY_STRING_OPTION, EXPRESSION_OPTION];
- } else if (
- type === "SMALLINT" ||
- type === "INTEGER" ||
- type === "BIGINT" ||
- type === "SERIAL" ||
- type === "SMALLSERIAL" ||
- type === "BIGSERIAL" ||
- type === "INT2" ||
- type === "INT4" ||
- type === "INT8"
- ) {
- return [NO_DEFAULT_OPTION, INT_ZERO_OPTION, EXPRESSION_OPTION];
- } else if (type === "BOOLEAN") {
- return [NO_DEFAULT_OPTION, BOOLEAN_TRUE_OPTION, BOOLEAN_FALSE_OPTION];
- }
- }
-
- // Default options.
- return [NO_DEFAULT_OPTION, EMPTY_STRING_OPTION, EXPRESSION_OPTION];
-};
-
-export const getDefaultValueByKey = (key: string) => {
- const options = [
- NO_DEFAULT_OPTION,
- EMPTY_STRING_OPTION,
- EXPRESSION_OPTION,
- INT_ZERO_OPTION,
- BOOLEAN_TRUE_OPTION,
- BOOLEAN_FALSE_OPTION,
- ];
- return options.find((option) => option.key === key)?.value;
-};
-
-export const getColumnDefaultDisplayString = (column: ColumnDefaultValue) => {
- if (!column.hasDefault || column.defaultNull) {
- return undefined;
- }
- return column.defaultString || column.defaultExpression || "";
-};
-
-export const getColumnDefaultValuePlaceholder = (
- column: ColumnDefaultValue
-): string => {
- if (!column.hasDefault) {
- return "No default";
- }
- if (column.defaultNull) {
- return "Null";
- }
- if (column.defaultString !== undefined) {
- return column.defaultString || "Empty string";
- }
- if (column.defaultExpression !== undefined) {
- return column.defaultExpression || "Empty expression";
- }
- return "";
-};
-
-export const getColumnDefaultValueOptions = (
- engine: Engine,
- columnType: string
-): (DefaultValueOption & DropdownOption)[] => {
- return getColumnTypeDefaultValueOptions(engine, columnType).map((option) => {
- return {
- ...option,
- label: t(`schema-editor.default.${option.key}`),
- };
- });
-};
diff --git a/frontend/src/components/SchemaEditorV1/utils/database.ts b/frontend/src/components/SchemaEditorV1/utils/database.ts
deleted file mode 100644
index f857e568ca..0000000000
--- a/frontend/src/components/SchemaEditorV1/utils/database.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-import { cloneDeep } from "lodash-es";
-import { markRaw } from "vue";
-import {
- useDBSchemaV1Store,
- useDatabaseV1Store,
- useSchemaEditorV1Store,
-} from "@/store";
-import { Engine } from "@/types/proto/v1/common";
-import { SchemaMetadata } from "@/types/proto/v1/database_service";
-import {
- convertSchemaMetadataList,
- convertSchemaMetadataToSchema,
-} from "@/types/v1/schemaEditor";
-
-export const fetchSchemaListByDatabaseName = async ({
- database,
- skipCache = true,
-}: {
- database: string;
- skipCache?: boolean;
-}) => {
- const schemaEditorV1Store = useSchemaEditorV1Store();
- const db = useDatabaseV1Store().getDatabaseByName(database);
- const databaseMetadata =
- await useDBSchemaV1Store().getOrFetchDatabaseMetadata({
- database,
- skipCache,
- });
- const schemaList = convertSchemaMetadataList(
- databaseMetadata.schemas,
- databaseMetadata.schemaConfigs
- );
- if (schemaList.length === 0 && db.instanceEntity.engine === Engine.MYSQL) {
- schemaList.push(
- convertSchemaMetadataToSchema(SchemaMetadata.fromPartial({}), "normal")
- );
- }
-
- schemaEditorV1Store.resourceMap.database.set(database, {
- database: db,
- schemaList,
- originSchemaList: markRaw(cloneDeep(schemaList)),
- });
- return schemaList;
-};
diff --git a/frontend/src/components/SchemaEditorV1/utils/index.ts b/frontend/src/components/SchemaEditorV1/utils/index.ts
deleted file mode 100644
index a78d42ede9..0000000000
--- a/frontend/src/components/SchemaEditorV1/utils/index.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-export * from "./metadata";
-export * from "./schema";
-export * from "./table";
-export * from "./column";
diff --git a/frontend/src/components/SchemaEditorV1/utils/metadata.ts b/frontend/src/components/SchemaEditorV1/utils/metadata.ts
deleted file mode 100644
index 4bb91c930c..0000000000
--- a/frontend/src/components/SchemaEditorV1/utils/metadata.ts
+++ /dev/null
@@ -1,318 +0,0 @@
-import { cloneDeep, isEqual, uniq } from "lodash-es";
-import type { DatabaseMetadata } from "@/types/proto/v1/database_service";
-import {
- ColumnMetadata,
- IndexMetadata,
- SchemaMetadata,
- TableMetadata,
- SchemaConfig,
- ColumnConfig,
- TableConfig,
-} from "@/types/proto/v1/database_service";
-import type {
- Column,
- ForeignKey,
- Schema,
- Table,
-} from "@/types/v1/schemaEditor";
-import {
- convertColumnMetadataToColumn,
- convertSchemaMetadataToSchema,
- convertTableMetadataToTable,
-} from "@/types/v1/schemaEditor";
-import { keyBy } from "@/utils";
-
-export const transformTableEditToMetadata = (
- tableEdit: Table
-): TableMetadata => {
- const tableMetadata = TableMetadata.fromPartial({
- name: tableEdit.name,
- columns: [],
- indexes: [],
- foreignKeys: [],
- comment: tableEdit.comment,
- userComment: tableEdit.userComment,
- });
-
- for (const column of tableEdit.columnList) {
- tableMetadata.columns.push(transformColumnEditToMetadata(column));
- }
-
- if (tableEdit.primaryKey.columnIdList.length > 0) {
- const primaryIndex = IndexMetadata.fromPartial({
- // TODO: Maybe we should let user to specify the index name.
- name: tableEdit.primaryKey.name || `pk_${tableEdit.name}`,
- primary: true,
- expressions: [],
- });
- for (const columnId of tableEdit.primaryKey.columnIdList) {
- const column = tableEdit.columnList.find(
- (column) => column.id === columnId
- );
- if (column) {
- primaryIndex.expressions.push(column.name);
- }
- }
- if (primaryIndex.expressions.length > 0) {
- tableMetadata.indexes.push(primaryIndex);
- }
- }
-
- return tableMetadata;
-};
-
-const transformColumnEditToMetadata = (columnEdit: Column): ColumnMetadata => {
- return ColumnMetadata.fromPartial({
- name: columnEdit.name,
- type: columnEdit.type,
- nullable: columnEdit.nullable,
- hasDefault: columnEdit.hasDefault,
- defaultNull: columnEdit.defaultNull,
- defaultString: columnEdit.defaultString,
- defaultExpression: columnEdit.defaultExpression,
- comment: columnEdit.comment,
- userComment: columnEdit.userComment,
- });
-};
-
-export const rebuildEditableSchemas = (
- originalSchemas: Schema[],
- schemas: SchemaMetadata[],
- schemaConfigList: SchemaConfig[]
-): Schema[] => {
- const tag = [
- "rebuildEditableSchemas",
- `[${originalSchemas.map((s) => s.tableList.length)}]`,
- `[${schemas.map((s) => s.tables.length)}]`,
- `[${schemaConfigList.map((sc) => sc.tableConfigs.length)}]`,
- ].join("--");
- console.debug("go!", tag);
- console.time(tag);
- const editableSchemas = cloneDeep(originalSchemas);
-
- console.time("loop-1");
- const schemaMetadataByName = keyBy(schemas, (s) => s.name);
- const schemaConfigByName = keyBy(schemaConfigList, (sc) => sc.name);
- for (let i = 0; i < editableSchemas.length; i++) {
- const editableSchema = editableSchemas[i];
- const schema = schemaMetadataByName.get(editableSchema.name);
- if (!schema) {
- editableSchema.status = "dropped";
- continue;
- }
-
- const schemaConfig =
- schemaConfigByName.get(editableSchema.name) ??
- SchemaConfig.fromPartial({});
-
- for (const editableTable of editableSchema.tableList) {
- const table = schema.tables.find(
- (table) => table.name === editableTable.name
- );
- if (!table) {
- editableTable.status = "dropped";
- continue;
- }
-
- editableTable.userComment = table.userComment;
- editableTable.comment = table.comment;
-
- editableTable.config =
- schemaConfig.tableConfigs.find(
- (tableConfig) => tableConfig.name === editableTable.name
- ) ?? TableConfig.fromPartial({ name: editableTable.name });
-
- for (const editableColumn of editableTable.columnList) {
- editableColumn.config =
- editableTable.config.columnConfigs.find(
- (columnConfig) => columnConfig.name === editableColumn.name
- ) ?? ColumnConfig.fromPartial({ name: editableColumn.name });
-
- const column = table.columns.find(
- (column) => column.name === editableColumn.name
- );
- if (!column) {
- editableColumn.status = "dropped";
- continue;
- }
- if (isEqual(transformColumnEditToMetadata(editableColumn), column)) {
- continue;
- }
-
- editableColumn.type = column.type;
- editableColumn.nullable = column.nullable;
- editableColumn.comment = column.comment;
- editableColumn.userComment = column.userComment;
- editableColumn.hasDefault = column.hasDefault;
- editableColumn.defaultNull = column.defaultNull;
- editableColumn.defaultString = column.defaultString;
- editableColumn.defaultExpression = column.defaultExpression;
- }
-
- for (const column of table.columns) {
- const editableColumn = editableTable.columnList.find(
- (item) => item.name === column.name
- );
- if (!editableColumn) {
- const newColumn = convertColumnMetadataToColumn(
- column,
- "created",
- editableTable.config.columnConfigs.find(
- (columnConfig) => columnConfig.name === column.name
- )
- );
- editableTable.columnList.push(newColumn);
- }
- }
-
- // Rebuild primary key from primary index.
- const primaryIndex = table.indexes.find((index) => index.primary);
- if (primaryIndex) {
- editableTable.primaryKey.name = primaryIndex.name;
- for (const columnName of primaryIndex.expressions) {
- const column = editableTable.columnList.find(
- (column) => column.name === columnName
- );
- if (column) {
- editableTable.primaryKey.columnIdList.push(column.id);
- }
- }
- editableTable.primaryKey.columnIdList = uniq(
- editableTable.primaryKey.columnIdList
- );
- } else {
- editableTable.primaryKey = {
- name: "",
- columnIdList: [],
- };
- }
- }
-
- for (const table of schema.tables) {
- const editableTable = editableSchema.tableList.find(
- (item) => item.name === table.name
- );
- if (!editableTable) {
- const newTable = convertTableMetadataToTable(
- table,
- "created",
- schemaConfig.tableConfigs.find(
- (tableConfig) => tableConfig.name === table.name
- )
- );
- editableSchema.tableList.push(newTable);
- }
- }
- }
- console.timeEnd("loop-1");
-
- console.time("loop-2");
- for (const schema of schemas) {
- const editableSchema = editableSchemas.find(
- (item) => item.name === schema.name
- );
- if (!editableSchema) {
- const newSchema = convertSchemaMetadataToSchema(
- schema,
- "created",
- schemaConfigList.find(
- (schemaConfig) => schemaConfig.name === schema.name
- )
- );
- editableSchemas.push(newSchema);
- }
- }
- console.timeEnd("loop-2");
-
- console.time("loop-3");
- // Build foreign keys for schema and referenced schema.
- for (const schema of schemas) {
- const editableSchema = editableSchemas.find(
- (schema) => schema.name === schema.name
- );
- if (!editableSchema) {
- continue;
- }
-
- for (const table of schema.tables) {
- const editableTable = editableSchema.tableList.find(
- (item) => item.name === table.name
- );
- if (!editableTable) {
- continue;
- }
-
- const foreignKeyList: ForeignKey[] = [];
- for (const foreignKeyMetadata of table.foreignKeys) {
- const referencedSchema = editableSchemas.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: editableTable.id,
- columnIdList: [],
- referencedSchemaId: referencedSchema.id,
- referencedTableId: referencedTable.id,
- referencedColumnIdList: [],
- };
- for (const columnName of foreignKeyMetadata.columns) {
- const column = editableTable.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);
- }
- editableTable.foreignKeyList = foreignKeyList;
- }
- }
- console.timeEnd("loop-3");
-
- console.timeEnd(tag);
- return editableSchemas;
-};
-
-export const validateDatabaseMetadata = (
- databaseMetadata: DatabaseMetadata
-): string[] => {
- const messages: string[] = [];
-
- for (const schema of databaseMetadata.schemas) {
- for (const table of schema.tables) {
- if (!table.name) {
- messages.push(`Table name is required.`);
- continue;
- }
-
- for (const column of table.columns) {
- if (!column.name) {
- messages.push(`Column name is required.`);
- continue;
- }
- if (!column.type) {
- messages.push(`Column ${column.name} type is required.`);
- }
- }
- }
- }
-
- return uniq(messages);
-};
diff --git a/frontend/src/components/SchemaEditorV1/utils/schema.ts b/frontend/src/components/SchemaEditorV1/utils/schema.ts
deleted file mode 100644
index 8551ce5a05..0000000000
--- a/frontend/src/components/SchemaEditorV1/utils/schema.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import { isEqual } from "lodash-es";
-import { useSchemaEditorV1Store } from "@/store";
-
-export const isSchemaChanged = (
- parentName: string,
- schemaId: string
-): boolean => {
- const schemaEditorV1Store = useSchemaEditorV1Store();
- const editorSchema = schemaEditorV1Store.getSchema(parentName, schemaId);
- const originSchema = schemaEditorV1Store.getOriginSchema(
- parentName,
- schemaId
- );
- return !isEqual(originSchema, editorSchema);
-};
diff --git a/frontend/src/components/SchemaEditorV1/utils/table.ts b/frontend/src/components/SchemaEditorV1/utils/table.ts
deleted file mode 100644
index 1172d12f37..0000000000
--- a/frontend/src/components/SchemaEditorV1/utils/table.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { isEqual } from "lodash-es";
-import { useSchemaEditorV1Store } from "@/store";
-
-export const isTableChanged = (
- parentName: string,
- schemaId: string,
- tableId: string
-): boolean => {
- const schemaEditorV1Store = useSchemaEditorV1Store();
- const editorTable = schemaEditorV1Store.getTable(
- parentName,
- schemaId,
- tableId
- );
- const originTable = schemaEditorV1Store.getOriginTable(
- parentName,
- schemaId,
- tableId
- );
- return !isEqual(originTable, editorTable);
-};
diff --git a/frontend/src/components/SchemaEditorV1/utils/useMetadataForDiagram.ts b/frontend/src/components/SchemaEditorV1/utils/useMetadataForDiagram.ts
deleted file mode 100644
index a265290fa8..0000000000
--- a/frontend/src/components/SchemaEditorV1/utils/useMetadataForDiagram.ts
+++ /dev/null
@@ -1,229 +0,0 @@
-import { computed, unref } from "vue";
-import type { EditStatus } from "@/components/SchemaDiagram";
-import type { ComposedDatabase, MaybeRef } from "@/types";
-import {
- ColumnMetadata,
- DatabaseMetadata,
- ForeignKeyMetadata,
- IndexMetadata,
- SchemaMetadata,
- TableMetadata,
-} from "@/types/proto/v1/database_service";
-import type {
- DatabaseSchema,
- Column,
- Schema,
- Table,
-} from "@/types/v1/schemaEditor";
-import { isColumnChanged } from "./column";
-import { isSchemaChanged } from "./schema";
-import { isTableChanged } from "./table";
-
-type MetadataWithEditStatus<T, E> = T & {
- $$status?: EditStatus;
- $$edit?: E;
-};
-
-const statusOfSchema = (database: ComposedDatabase, schema: Schema) => {
- const { status } = schema;
- if (status === "created" || status === "dropped") {
- return status;
- }
- if (isSchemaChanged(database.name, schema.id)) {
- return "changed";
- }
- return "normal";
-};
-
-const statusOfTable = (
- database: ComposedDatabase,
- schema: Schema,
- table: Table
-): EditStatus => {
- const { status } = table;
- if (status === "created" || status === "dropped") {
- return status;
- }
- if (isTableChanged(database.name, schema.id, table.id)) {
- return "changed";
- }
-
- return "normal";
-};
-
-const statusOfColumn = (
- database: ComposedDatabase,
- schema: Schema,
- table: Table,
- column: Column
-): EditStatus => {
- const { status } = column;
- if (status === "created" || status === "dropped") {
- return status;
- }
- if (isColumnChanged(database.name, 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.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.hasDefault = column.hasDefault;
- columnMeta.defaultNull = column.defaultNull;
- columnMeta.defaultString = column.defaultString;
- columnMeta.defaultExpression = column.defaultExpression;
-
- 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];
-
- tableMeta.foreignKeys = table.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/store/modules/v1/index.ts b/frontend/src/store/modules/v1/index.ts
index e78fb86b08..a8589d1638 100644
--- a/frontend/src/store/modules/v1/index.ts
+++ b/frontend/src/store/modules/v1/index.ts
@@ -21,7 +21,6 @@ export * from "./vcs_connector";
export * from "./changeHistory";
export * from "./dbSchema";
export * from "./anomaly";
-export * from "./schemaEditor";
export * from "./changelist";
export * from "./issueComment";
export * from "./auditLog";
diff --git a/frontend/src/store/modules/v1/schemaEditor.ts b/frontend/src/store/modules/v1/schemaEditor.ts
deleted file mode 100644
index 845e4cadf1..0000000000
--- a/frontend/src/store/modules/v1/schemaEditor.ts
+++ /dev/null
@@ -1,271 +0,0 @@
-import { isUndefined, uniqueId } from "lodash-es";
-import { defineStore } from "pinia";
-import type { ComposedDatabase } from "@/types";
-import { emptyProject } from "@/types";
-import { Engine } from "@/types/proto/v1/common";
-import type {
- BranchSchema,
- DatabaseSchema,
- SchemaEditorV1State,
- Table,
- TabContext,
- TableTabContext,
-} from "@/types/v1/schemaEditor";
-import { SchemaEditorTabType } from "@/types/v1/schemaEditor";
-import type { Schema } from "@/types/v1/schemaEditor/atomType";
-import { useDatabaseV1Store } from "./database";
-
-export const generateUniqueTabId = () => {
- return uniqueId();
-};
-
-const getDefaultSchemaEditorState = (): SchemaEditorV1State => {
- return {
- project: emptyProject(),
- readonly: false,
- resourceType: "database",
- resourceMap: {
- database: new Map([]),
- branch: new Map([]),
- },
- tabState: {
- tabMap: new Map<string, TabContext>([]),
- currentTabId: "",
- },
- };
-};
-
-export const useSchemaEditorV1Store = defineStore("SchemaEditorV1", {
- state: (): SchemaEditorV1State => {
- 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.resourceMap["database"].values()).map(
- (databaseSchema) => databaseSchema.database
- );
- },
- currentDatabase(): ComposedDatabase | undefined {
- if (!this.currentTab) {
- return;
- }
- if (this.resourceType === "branch") {
- const baselineDatabase = this.resourceMap.branch.get(
- this.currentTab.parentName
- )?.branch.baselineDatabase;
- if (!baselineDatabase) {
- return;
- }
- return useDatabaseV1Store().getDatabaseByName(baselineDatabase);
- } else {
- return this.resourceMap.database.get(this.currentTab.parentName)
- ?.database;
- }
- },
- currentSchemaList(): Schema[] {
- if (!this.currentTab) {
- return [] as Schema[];
- }
- return (
- this.resourceMap[this.resourceType].get(this.currentTab.parentName)
- ?.schemaList ?? []
- );
- },
- },
- actions: {
- getCurrentEngine(parentName: string) {
- const parentResouce = this.resourceMap[this.resourceType].get(parentName);
- if (!parentResouce) {
- return Engine.MYSQL;
- }
- if (this.resourceType === "database") {
- return (parentResouce as DatabaseSchema).database.instanceEntity.engine;
- } else if (this.resourceType === "branch") {
- return (parentResouce as BranchSchema).branch.engine;
- } else {
- return Engine.MYSQL;
- }
- },
- setState(state: Partial<SchemaEditorV1State>) {
- Object.assign(this, state);
- },
- addTab(tab: TabContext, setAsCurrentTab = true) {
- const tabCache = this.tabList.find((item) => {
- if (
- item.type === tab.type &&
- item.parentName === tab.parentName &&
- (item.type === SchemaEditorTabType.TabForDatabase ||
- (item.type === SchemaEditorTabType.TabForTable &&
- 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(parentName: string, tableId?: string) {
- let tabType = SchemaEditorTabType.TabForDatabase;
- if (tableId !== undefined) {
- tabType = SchemaEditorTabType.TabForTable;
- }
-
- const tab = this.tabList.find((tab) => {
- if (
- tab.type === tabType &&
- tab.parentName === parentName &&
- (tab.type === SchemaEditorTabType.TabForDatabase ||
- (tab.type === SchemaEditorTabType.TabForTable &&
- tab.tableId === tableId))
- ) {
- return true;
- }
- return false;
- });
-
- return tab;
- },
- getSchema(parentName: string, schemaId: string) {
- return this.resourceMap[this.resourceType]
- .get(parentName)
- ?.schemaList.find((schema) => schema.id === schemaId);
- },
- getOriginSchema(parentName: string, schemaId: string) {
- return this.resourceMap[this.resourceType]
- .get(parentName)
- ?.originSchemaList.find((schema) => schema.id === schemaId);
- },
- dropSchema(parentName: string, schemaId: string) {
- const schema = this.getSchema(parentName, schemaId);
- if (!schema) {
- return;
- }
-
- if (schema.status === "created") {
- const resource = this.resourceMap[this.resourceType].get(parentName);
- if (resource) {
- resource.schemaList =
- this.resourceMap[this.resourceType]
- .get(parentName)
- ?.schemaList.filter((schema) => schema.id !== schemaId) || [];
-
- // Close related tabs.
- for (const tab of this.tabList) {
- if (tab.parentName !== parentName) {
- continue;
- }
-
- if (
- tab.type === SchemaEditorTabType.TabForTable &&
- tab.schemaId === schemaId
- ) {
- this.closeTab(tab.id);
- }
- }
- }
- } else {
- schema.status = "dropped";
- }
- },
- restoreSchema(parentName: string, schemaId: string) {
- const schema = this.getSchema(parentName, schemaId);
- if (!schema) {
- return;
- }
- schema.status = "normal";
- },
- getTable(parentName: string, schemaId: string, tableId: string) {
- return this.getSchema(parentName, schemaId)?.tableList.find(
- (table) => table.id === tableId
- );
- },
- getOriginTable(parentName: string, schemaId: string, tableId: string) {
- return this.getOriginSchema(parentName, schemaId)?.tableList.find(
- (table) => table.id === tableId
- );
- },
- getTableWithTableTab(tab: TableTabContext) {
- return this.resourceMap[this.resourceType]
- .get(tab.parentName)
- ?.schemaList.find((schema) => schema.id === tab.schemaId)
- ?.tableList?.find((table) => table.id === tab.tableId);
- },
- dropTable(parentName: string, schemaId: string, tableId: string) {
- const table = this.getTable(parentName, schemaId, tableId);
- if (!table) {
- return;
- }
-
- // Remove table record and close tab for created table.
- if (table.status === "created") {
- const tableList = this.resourceMap[this.resourceType]
- .get(parentName)
- ?.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(parentName, table.id);
- if (tab) {
- this.closeTab(tab.id);
- }
- } else {
- table.status = "dropped";
- }
- },
- restoreTable(parentName: string, schemaId: string, tableId: string) {
- const table = this.getTable(parentName, schemaId, tableId);
- if (!table) {
- return;
- }
- table.status = "normal";
- },
- },
-});
diff --git a/frontend/src/types/v1/schemaEditor/state.ts b/frontend/src/types/v1/schemaEditor/state.ts
index fe9dd5fca5..f50fc21e5e 100644
--- a/frontend/src/types/v1/schemaEditor/state.ts
+++ b/frontend/src/types/v1/schemaEditor/state.ts
@@ -1,4 +1,4 @@
-import type { ComposedDatabase, ComposedProject } from "..";
+import type { ComposedDatabase } from "..";
import type { Branch } from "../../proto/v1/branch_service";
import type { Schema } from "./atomType";
@@ -41,17 +41,3 @@ export interface BranchSchema {
schemaList: Schema[];
originSchemaList: Schema[];
}
-
-export interface SchemaEditorV1State {
- project: ComposedProject;
- readonly: boolean;
- resourceType: "database" | "branch";
- resourceMap: {
- database: Map<string, DatabaseSchema>;
- branch: Map<string, BranchSchema>;
- };
- tabState: {
- tabMap: Map<string, TabContext>;
- currentTabId?: string;
- };
-}