Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: add UI editor components (#3515)
boojack3b7bd76b0608
diff --git a/frontend/src/components/AlterSchemaPrepForm/ProjectStandardView.vue b/frontend/src/components/AlterSchemaPrepForm/ProjectStandardView.vueindex 46e4f7e124..55e4d1e0ae 100644--- a/frontend/src/components/AlterSchemaPrepForm/ProjectStandardView.vue+++ b/frontend/src/components/AlterSchemaPrepForm/ProjectStandardView.vue@@ -1,6 +1,4 @@<template>- <!-- eslint-disable vue/no-mutating-props -->-<template v-if="state.alterType === 'MULTI_DB'"><!-- multiple stage view --><div v-if="databaseList.length === 0" class="textinfolabel">diff --git a/frontend/src/components/HighlightCodeBlock.ts b/frontend/src/components/HighlightCodeBlock.tsindex e035b6a14f..ef10188ec8 100644--- a/frontend/src/components/HighlightCodeBlock.ts+++ b/frontend/src/components/HighlightCodeBlock.ts@@ -19,13 +19,14 @@ export default defineComponent({},render() {const { code, language, tag } = this.$props;+ const { class: additionalClass } = this.$attrs;const result = hljs.highlight(code, {language: language,});return h(tag, {- class: language,+ class: [language, additionalClass],innerHTML: result.value,});},diff --git a/frontend/src/components/UIEditor/AsidePanel.vue b/frontend/src/components/UIEditor/AsidePanel.vuenew file mode 100644index 0000000000..3bba344d8a--- /dev/null+++ b/frontend/src/components/UIEditor/AsidePanel.vue@@ -0,0 +1,7 @@+<template>+ <DatabaseTree />+</template>++<script lang="ts" setup>+import DatabaseTree from "./DatabaseTree.vue";+</script>diff --git a/frontend/src/components/UIEditor/DatabaseTree.vue b/frontend/src/components/UIEditor/DatabaseTree.vuenew file mode 100644index 0000000000..deeb6a8ad8--- /dev/null+++ b/frontend/src/components/UIEditor/DatabaseTree.vue@@ -0,0 +1,557 @@+<template>+ <div class="w-full h-full pr-2 relative overflow-y-hidden">+ <div class="w-full sticky top-0 pt-2 h-12 bg-white z-10">+ <NInput+ v-model:value="searchPattern"+ :placeholder="$t('sql-editor.search-databases')"+ >+ <template #prefix>+ <heroicons-outline:search class="w-4 h-auto text-gray-300" />+ </template>+ </NInput>+ </div>+ <div+ ref="treeRef"+ class="ui-editor-database-tree pb-2 h-auto"+ v-bind="$attrs"+ >+ <n-tree+ block-line+ :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"+ :on-update:selected-keys="handleSelectedKeysChange"+ />+ <n-dropdown+ trigger="manual"+ placement="bottom-start"+ :show="contextMenu.showDropdown"+ :options="contextMenuOptions"+ :x="contextMenu.clientX"+ :y="contextMenu.clientY"+ @select="handleContextMenuDropdownSelect"+ @clickoutside="handleDropdownClickoutside"+ />+ </div>+ </div>+</template>++<script lang="ts" setup>+import { cloneDeep, escape, isEqual, isUndefined } from "lodash-es";+import { TreeOption, NEllipsis, NInput } from "naive-ui";+import { computed, onMounted, watch, ref, h, reactive, nextTick } from "vue";+import scrollIntoView from "scroll-into-view-if-needed";+import {+ DatabaseId,+ InstanceId,+ Table,+ TableId,+ UIEditorTabType,+ UNKNOWN_ID,+} from "@/types";+import {+ useUIEditorStore,+ generateUniqueTabId,+ useInstanceStore,+ useTableStore,+} from "@/store";+import { getHighlightHTMLByKeyWords, isDescendantOf } from "@/utils";+import InstanceEngineIcon from "@/components/InstanceEngineIcon.vue";+import DatabaseIcon from "~icons/heroicons-outline/database";+import TableIcon from "~icons/heroicons-outline/table";+import EllipsisIcon from "~icons/heroicons-solid/ellipsis-horizontal";++interface BaseTreeNode extends TreeOption {+ key: string;+ label: string;+ isLeaf: boolean;+ children?: TreeNode[];+}++interface TreeNodeForInstance extends BaseTreeNode {+ type: "instance";+ instanceId: InstanceId;+}++interface TreeNodeForDatabase extends BaseTreeNode {+ type: "database";+ instanceId: InstanceId;+ databaseId: DatabaseId;+}++interface TreeNodeForTable extends BaseTreeNode {+ type: "table";+ instanceId: InstanceId;+ databaseId: DatabaseId;+ tableId: TableId;+}++type TreeNode = TreeNodeForInstance | TreeNodeForDatabase | TreeNodeForTable;++interface TreeContextMenu {+ showDropdown: boolean;+ clientX: number;+ clientY: number;+ treeNode?: TreeNode;+}++interface LocalState {+ shouldRelocateTreeNode: boolean;+}++const editorStore = useUIEditorStore();+const instanceStore = useInstanceStore();+const tableStore = useTableStore();+const state = reactive<LocalState>({+ shouldRelocateTreeNode: false,+});+const contextMenu = reactive<TreeContextMenu>({+ showDropdown: false,+ clientX: 0,+ clientY: 0,+ treeNode: undefined,+});+const treeRef = ref();+const searchPattern = ref("");+const expandedKeysRef = ref<string[]>([]);+const selectedKeysRef = ref<string[]>([]);+const treeDataRef = ref<TreeNode[]>([]);++const databaseList = computed(() => editorStore.databaseList);+const tableList = computed(() => editorStore.tableList);+const contextMenuOptions = computed(() => {+ const treeNode = contextMenu.treeNode;+ if (isUndefined(treeNode)) {+ return [];+ }++ if (treeNode?.type === "database") {+ const options = [];+ options.push({+ key: "new-table",+ label: "New Table",+ });+ return options;+ } else if (treeNode?.type === "table") {+ const table = editorStore.findTable(+ treeNode.tableId,+ treeNode.label,+ treeNode.databaseId+ );+ const isDropped = editorStore.droppedTableList.includes(table as Table);+ const options = [];+ if (isDropped) {+ options.push({+ key: "restore",+ label: "Restore",+ });+ } else {+ options.push({+ key: "drop",+ label: "Drop",+ });+ }+ return options;+ }++ return [];+});++onMounted(() => {+ const treeNodeList: TreeNode[] = [];+ const instanceTreeNodeMap: Map<InstanceId, TreeNodeForInstance> = new Map();+ for (const database of databaseList.value) {+ const instance = instanceStore.getInstanceById(database.instanceId);+ let instanceTreeNode: TreeNodeForInstance;+ if (instanceTreeNodeMap.has(instance.id)) {+ instanceTreeNode = instanceTreeNodeMap.get(+ instance.id+ ) as TreeNodeForInstance;+ } else {+ instanceTreeNode = {+ type: "instance",+ key: `i-${instance.id}`,+ label: instance.name,+ isLeaf: false,+ instanceId: database.instance.id,+ children: [],+ };+ instanceTreeNodeMap.set(instance.id, 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.id}`,+ label: database.name,+ isLeaf: false,+ instanceId: database.instance.id,+ databaseId: database.id,+ };+ instanceTreeNode.children?.push(databaseTreeNode);+ }+ treeDataRef.value = treeNodeList;+});++watch(tableList.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) {+ const databaseTreeNode = databaseTreeNodeList.find(+ (treeNode) => treeNode.databaseId === database.id+ );+ if (isUndefined(databaseTreeNode)) {+ continue;+ }++ const databaseTableList = [];+ for (const table of tableList.value) {+ if (table.database.id === database.id) {+ databaseTableList.push(table);+ }+ }+ if (databaseTableList.length > 0) {+ databaseTreeNode.children = databaseTableList.map((table) => {+ return {+ type: "table",+ key: `t-${table.id}-${table.name}`,+ label: table.name,+ children: [],+ isLeaf: true,+ instanceId: database.instance.id,+ databaseId: database.id,+ tableId: table.id,+ };+ });+ }+ }+});++watch(+ () => editorStore.currentTab,+ () => {+ const currentTab = editorStore.currentTab;+ if (!currentTab) {+ selectedKeysRef.value = [];+ return;+ }++ if (currentTab.type === UIEditorTabType.TabForDatabase) {+ const key = `d-${currentTab.databaseId}`;+ selectedKeysRef.value = [key];+ } else if (currentTab.type === UIEditorTabType.TabForTable) {+ const databaseTreeNodeKey = `d-${currentTab.databaseId}`;+ if (!expandedKeysRef.value.includes(databaseTreeNodeKey)) {+ expandedKeysRef.value.push(databaseTreeNodeKey);+ }+ const tableTreeNodeKey = `t-${currentTab.tableId}-${currentTab.tableCache.name}`;+ selectedKeysRef.value = [tableTreeNodeKey];+ }++ if (state.shouldRelocateTreeNode) {+ nextTick(() => {+ const element = treeRef.value?.querySelector(".n-tree-node--selected");+ scrollIntoView(element);+ });+ }+ }+);++// Render prefix icons before label text.+const renderPrefix = ({ option: treeNode }: { option: TreeNode }) => {+ if (treeNode.type === "instance") {+ const instance = instanceStore.getInstanceById(treeNode.instanceId);+ const children = [+ h(InstanceEngineIcon, {+ instance,+ }),+ h(+ "span",+ {+ class: "text-gray-500 text-sm",+ },+ `(${instance.environment.name})`+ ),+ ];++ return h("span", { class: "flex items-center gap-x-1" }, children);+ } else if (treeNode.type === "database") {+ return h(DatabaseIcon, {+ class: "w-4 h-auto text-gray-400",+ });+ } else if (treeNode.type === "table") {+ return h(TableIcon, {+ class: "w-4 h-auto text-gray-400",+ });+ }+ return null;+};++// Render label text.+const renderLabel = ({ option: treeNode }: { option: TreeNode }) => {+ const additionalClassList: string[] = ["select-none"];++ if (treeNode.type === "table") {+ if (treeNode.tableId === UNKNOWN_ID) {+ additionalClassList.push("text-green-700");+ } else {+ const originTable = tableStore.getTableByDatabaseIdAndTableId(+ treeNode.databaseId,+ treeNode.tableId+ );+ const table = editorStore.findTable(+ treeNode.tableId,+ treeNode.label,+ treeNode.databaseId+ );++ const isDropped = editorStore.droppedTableList.includes(table as Table);+ if (isDropped) {+ additionalClassList.push("text-red-700 line-through");+ } else if (!isEqual(originTable, table)) {+ additionalClassList.push("text-yellow-700");+ }+ }+ }++ return h(+ NEllipsis,+ {+ class: additionalClassList.join(" "),+ },+ [+ h("span", {+ innerHTML: getHighlightHTMLByKeyWords(+ escape(treeNode.label),+ escape(searchPattern.value)+ ),+ }),+ ]+ );+};++// Render a 'menu' icon in the right of the node+const renderSuffix = ({ option: treeNode }: { option: TreeNode }) => {+ if (treeNode.type === "database") {+ return h(EllipsisIcon, {+ class: "w-4 h-auto text-gray-600",+ onClick: (e) => {+ handleShowDropdown(e, treeNode);+ },+ });+ } else if (treeNode.type === "table") {+ return h(EllipsisIcon, {+ class: "w-4 h-auto text-gray-600",+ onClick: (e) => {+ handleShowDropdown(e, treeNode);+ },+ });+ }+ return null;+};++const handleShowDropdown = (e: MouseEvent, treeNode: TreeNode) => {+ e.preventDefault();+ e.stopPropagation();+ contextMenu.treeNode = treeNode;+ contextMenu.showDropdown = true;+ contextMenu.clientX = e.clientX;+ contextMenu.clientY = e.clientY;+ selectedKeysRef.value = [treeNode.key];+};++// Dynamic fetching table list when database tree node clicking.+const loadSubTree = async (treeNode: TreeNode) => {+ if (treeNode.type === "database") {+ const instanceId = treeNode.instanceId;+ const databaseId = treeNode.databaseId;+ const tableList = await editorStore.getOrFetchTableListByDatabaseId(+ databaseId+ );++ const knownTableList = tableList.filter((table) => table.id !== UNKNOWN_ID);+ if (knownTableList.length === 0) {+ treeNode.isLeaf = true;+ } else {+ treeNode.isLeaf = false;+ treeNode.children = knownTableList.map((table) => {+ return {+ type: "table",+ key: `t-${table.id}-${table.name}`,+ label: table.name,+ children: [],+ isLeaf: true,+ instanceId: instanceId,+ databaseId: databaseId,+ tableId: table.id,+ };+ });+ }+ }+};++// Set event handler to tree nodes.+const nodeProps = ({ option: treeNode }: { option: TreeNode }) => {+ return {+ async onClick(e: MouseEvent) {+ // Check if clicked on the content part.+ // And ignore the fold/unfold arrow.+ if (isDescendantOf(e.target as Element, ".n-tree-node-content")) {+ state.shouldRelocateTreeNode = false;++ if (treeNode.type === "instance") {+ // Toggle instance tree node expanded status.+ const index = expandedKeysRef.value.findIndex(+ (key) => key === treeNode.key+ );+ if (index >= 0) {+ expandedKeysRef.value.splice(index, 1);+ } else {+ expandedKeysRef.value.push(treeNode.key);+ }+ } else if (treeNode.type === "database") {+ editorStore.addTab({+ id: generateUniqueTabId(),+ type: UIEditorTabType.TabForDatabase,+ databaseId: treeNode.databaseId as any,+ });+ } else if (treeNode.type === "table") {+ const databaseId = treeNode.databaseId as any;+ const tableId = treeNode.tableId as any;+ const table = editorStore.findTable(+ tableId,+ treeNode.label || "",+ databaseId+ ) as Table;++ editorStore.addTab({+ id: generateUniqueTabId(),+ type: UIEditorTabType.TabForTable,+ databaseId: databaseId,+ tableId: tableId,+ tableCache: cloneDeep(table),+ });+ }++ nextTick(() => {+ if (treeNode.type === "database") {+ selectedKeysRef.value = [`d-${treeNode.databaseId}`];+ } else if (treeNode.type === "table") {+ selectedKeysRef.value = [`t-${treeNode.tableId}-${treeNode.label}`];+ }+ state.shouldRelocateTreeNode = true;+ });+ } else {+ nextTick(() => {+ selectedKeysRef.value = [];+ });+ }+ },+ onContextmenu(e: MouseEvent) {+ handleShowDropdown(e, treeNode);+ },+ };+};++const handleContextMenuDropdownSelect = async (key: string) => {+ const treeNode = contextMenu.treeNode;+ if (treeNode?.type === "database") {+ if (key === "new-table") {+ await editorStore.getOrFetchTableListByDatabaseId(treeNode.databaseId);+ const table = editorStore.createNewTable(treeNode.databaseId);+ editorStore.addTab({+ id: generateUniqueTabId(),+ type: UIEditorTabType.TabForTable,+ databaseId: treeNode.databaseId,+ tableId: table.id,+ tableCache: cloneDeep(table),+ });+ }+ } else if (treeNode?.type === "table") {+ if (key === "drop") {+ editorStore.dropTable(+ treeNode.databaseId,+ treeNode.tableId,+ treeNode.label+ );+ } else if (key === "restore") {+ editorStore.restoreTable(+ treeNode.databaseId,+ treeNode.tableId,+ treeNode.label+ );+ }+ }+ 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;+};++const handleSelectedKeysChange = (selectedKeys: string[]) => {+ selectedKeysRef.value = selectedKeys;+};+</script>++<style>+.ui-editor-database-tree .n-tree-node-wrapper {+ @apply !py-px;+}+.ui-editor-database-tree .n-tree-node-content__prefix {+ @apply shrink-0 !mr-1;+}+.ui-editor-database-tree .n-tree-node-content__text {+ @apply truncate mr-1;+}+.ui-editor-database-tree .n-tree-node-content__suffix {+ @apply rounded-sm !hidden hover:opacity-80;+}+.ui-editor-database-tree+ .n-tree-node-wrapper:hover+ .n-tree-node-content__suffix {+ @apply !flex;+}+.ui-editor-database-tree+ .n-tree-node-wrapper+ .n-tree-node--selected+ .n-tree-node-content__suffix {+ @apply !flex;+}+.ui-editor-database-tree .n-tree-node-switcher {+ @apply px-0 !w-4 !h-7;+}+</style>++<style scoped>+.ui-editor-database-tree {+ @apply overflow-y-auto;+ max-height: calc(100% - 48px);+}+</style>diff --git a/frontend/src/components/UIEditor/EmptyTips.vue b/frontend/src/components/UIEditor/EmptyTips.vuenew file mode 100644index 0000000000..11fd31c3d7--- /dev/null+++ b/frontend/src/components/UIEditor/EmptyTips.vue@@ -0,0 +1,8 @@+<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" />+ Click a database/table to start.+ </div>+</template>diff --git a/frontend/src/components/UIEditor/Panels/DatabaseEditor.vue b/frontend/src/components/UIEditor/Panels/DatabaseEditor.vuenew file mode 100644index 0000000000..896463061c--- /dev/null+++ b/frontend/src/components/UIEditor/Panels/DatabaseEditor.vue@@ -0,0 +1,277 @@+<template>+ <div class="grid auto-rows-auto w-full h-full overflow-y-auto">+ <div+ class="my-2 w-full flex justify-start items-center border-b border-b-gray-300"+ >+ <span+ class="-mb-px px-3 leading-9 rounded-t-md text-sm text-gray-500 border border-b-0 border-transparent cursor-pointer select-none"+ :class="+ state.selectedTab === 'list' &&+ 'bg-white border-gray-300 text-gray-800'+ "+ @click="handleChangeTab('list')"+ >List</span+ >+ <span+ class="hidden -mb-px px-3 leading-9 rounded-t-md text-sm text-gray-500 border border-b-0 border-transparent cursor-pointer select-none"+ :class="+ state.selectedTab === 'er-diagram' &&+ 'bg-white border-gray-300 text-gray-800'+ "+ @click="handleChangeTab('er-diagram')"+ >ER Diagram</span+ >+ <span+ class="-mb-px px-3 leading-9 rounded-t-md text-sm text-gray-500 border border-b-0 border-transparent cursor-pointer select-none"+ :class="+ state.selectedTab === 'raw-sql' &&+ 'bg-white border-gray-300 text-gray-800'+ "+ @click="handleChangeTab('raw-sql')"+ >Raw SQL</span+ >+ </div>++ <!-- List view -->+ <template v-if="state.selectedTab === 'list'">+ <div class="mb-2 w-full flex justify-between items-center space-x-2">+ <span class="ml-3 text-sm text-gray-500">Tables</span>+ <button+ class="flex flex-row justify-center items-center border px-2 py-1 rounded text-sm hover:bg-gray-100"+ @click="handleCreateNewTable"+ >+ <heroicons-outline:plus class="w-4 h-auto mr-1 text-gray-400" />+ New Table+ </button>+ </div>+ <!-- table list -->+ <div+ class="w-full h-auto grid auto-rows-auto border-y relative overflow-y-auto"+ >+ <!-- table header -->+ <div+ class="sticky top-0 z-10 grid grid-cols-[repeat(6,_minmax(0,_1fr))_32px] w-full border-b text-sm leading-6 select-none bg-gray-50 text-gray-400"+ >+ <span+ v-for="header in tableHeaderList"+ :key="header.key"+ class="table-header-item-container"+ >{{ header.label }}</span+ >+ <span></span>+ </div>+ <!-- table body -->+ <div class="w-full">+ <div+ v-for="(table, index) in tableListRef"+ :key="`${index}-${table.id}`"+ class="grid grid-cols-[repeat(6,_minmax(0,_1fr))_32px] text-sm even:bg-gray-50"+ >+ <div+ class="table-body-item-container cursor-pointer hover:opacity-80"+ @click="handleTableItemClick(table)"+ >+ {{ table.name }}+ </div>+ <div class="table-body-item-container">+ {{ table.rowCount }}+ </div>+ <div class="table-body-item-container">+ {{ table.dataSize }}+ </div>+ <div class="table-body-item-container">+ {{ table.engine }}+ </div>+ <div class="table-body-item-container">+ {{ table.collation }}+ </div>+ <div class="table-body-item-container">+ {{ table.comment }}+ </div>+ <div class="w-full flex justify-start items-center">+ <n-tooltip trigger="hover">+ <template #trigger>+ <heroicons-solid:x-mark+ class="w-[14px] h-auto text-gray-500 cursor-pointer hover:opacity-80"+ @click="handleDropTable(table)"+ />+ </template>+ <span>Drop Table</span>+ </n-tooltip>+ </div>+ </div>+ </div>+ </div>+ </template>+ <template v-else-if="state.selectedTab === 'er-diagram'">+ <p class="px-3 py-2 italic">ER Diagram by zp</p>+ </template>+ <div+ v-else-if="state.selectedTab === 'raw-sql'"+ class="w-full h-full overflow-y-auto"+ >+ <div+ v-if="state.isFetchingDDL"+ class="w-full h-full min-h-[64px] flex justify-center items-center"+ >+ <BBSpin />+ </div>+ <template v-else>+ <HighlightCodeBlock+ v-if="state.ddlStatement !== ''"+ class="text-sm px-3 py-2 whitespace-pre-wrap break-all"+ language="sql"+ :code="state.ddlStatement"+ ></HighlightCodeBlock>+ <span v-else class="px-3 my-2 italic">Nothing changed</span>+ </template>+ </div>+ </div>+</template>++<script lang="ts" setup>+import { cloneDeep } from "lodash-es";+import { computed, reactive, ref, watch } from "vue";+import {+ generateUniqueTabId,+ useDatabaseStore,+ useTableStore,+ useUIEditorStore,+} from "@/store";+import { DatabaseTabContext, Table, UIEditorTabType } from "@/types";+import { diffTableList } from "@/utils/UIEditor/diffTable";+import HighlightCodeBlock from "@/components/HighlightCodeBlock";++type TabType = "list" | "er-diagram" | "raw-sql";++interface LocalState {+ selectedTab: TabType;+ isFetchingDDL: boolean;+ ddlStatement: string;+}++const editorStore = useUIEditorStore();+const databaseStore = useDatabaseStore();+const tableStore = useTableStore();+const state = reactive<LocalState>({+ selectedTab: "list",+ isFetchingDDL: false,+ ddlStatement: "",+});+const currentTab = editorStore.currentTab as DatabaseTabContext;+const database = databaseStore.getDatabaseById(currentTab.databaseId);+const tableListRef = ref<Table[]>([]);+const tableHeaderList = computed(() => {+ return [+ {+ key: "name",+ label: "Name",+ },+ {+ key: "raw-count",+ label: "Row Count",+ },+ {+ key: "data-size",+ label: "Data Size",+ },+ {+ key: "engine",+ label: "Engine",+ },+ {+ key: "collation",+ label: "Collation",+ },+ {+ key: "comment",+ label: "Comment",+ },+ ];+});++watch(+ [editorStore.tableList, editorStore.droppedTableList],+ async () => {+ const tableList = await editorStore.getOrFetchTableListByDatabaseId(+ database.id+ );+ tableListRef.value = tableList.filter(+ (table) => !editorStore.droppedTableList.includes(table)+ );+ },+ {+ immediate: true,+ }+);++watch(+ () => state.selectedTab,+ async () => {+ if (state.selectedTab === "raw-sql") {+ state.isFetchingDDL = true;+ const originTableList = await tableStore.getOrFetchTableListByDatabaseId(+ database.id+ );+ const updatedTableList = (+ await editorStore.getOrFetchTableListByDatabaseId(database.id)+ ).filter((table) => !editorStore.droppedTableList.includes(table));+ const diffTableListResult = diffTableList(+ originTableList,+ updatedTableList+ );+ if (+ diffTableListResult.createTableList.length > 0 ||+ diffTableListResult.alterTableList.length > 0 ||+ diffTableListResult.dropTableList.length > 0+ ) {+ const databaseEdit = {+ databaseId: database.id,+ ...diffTableListResult,+ };+ const statement = await editorStore.postDatabaseEdit(databaseEdit);+ state.ddlStatement = statement;+ }+ state.isFetchingDDL = false;+ }+ }+);++const handleChangeTab = (tab: TabType) => {+ state.selectedTab = tab;+};++const handleCreateNewTable = () => {+ const table = editorStore.createNewTable(database.id);+ editorStore.addTab({+ id: generateUniqueTabId(),+ type: UIEditorTabType.TabForTable,+ databaseId: database.id,+ tableId: table.id,+ tableCache: cloneDeep(table),+ });+};++const handleTableItemClick = (table: Table) => {+ editorStore.addTab({+ id: generateUniqueTabId(),+ type: UIEditorTabType.TabForTable,+ databaseId: database.id,+ tableId: table.id,+ tableCache: cloneDeep(table),+ });+};++const handleDropTable = (table: Table) => {+ editorStore.dropTable(table.database.id, table.id, table.name);+};+</script>++<style scoped>+.table-header-item-container {+ @apply py-2 px-3;+}+.table-body-item-container {+ @apply w-full box-border p-px pl-3 pr-4 relative leading-8;+}+</style>diff --git a/frontend/src/components/UIEditor/Panels/TableEditor.vue b/frontend/src/components/UIEditor/Panels/TableEditor.vuenew file mode 100644index 0000000000..306b7368ae--- /dev/null+++ b/frontend/src/components/UIEditor/Panels/TableEditor.vue@@ -0,0 +1,350 @@+<template>+ <div class="grid auto-rows-auto w-full h-full overflow-y-auto">+ <div+ class="w-full h-auto flex flex-row justify-between items-center py-2 border-b"+ >+ <div class="flex flex-row items-center space-x-2">+ <div class="flex flex-row justify-start items-center">+ <span class="mr-1 text-sm ml-3 whitespace-nowrap text-gray-500"+ >Table Name:+ </span>+ <input+ v-model="tableCache.name"+ placeholder=""+ :disabled="tableCache.id !== UNKNOWN_ID"+ class="w-full leading-6 px-2 py-1 rounded border text-sm"+ :class="+ tableCache.id === UNKNOWN_ID+ ? 'border-gray-200'+ : 'border-transparent'+ "+ type="text"+ />+ </div>+ </div>+ <div class="flex flex-row items-center space-x-2">+ <NPopover trigger="click" placement="bottom-end">+ <template #trigger>+ <button+ class="flex flex-row justify-center items-center border px-2 py-1 text-sm text-gray-700 rounded cursor-pointer hover:bg-gray-100"+ @click="handlePreviewDDLStatement"+ >+ SQL Preview+ </button>+ </template>+ <div class="w-112 min-h-[16em] max-h-[32em] overflow-y-auto">+ <div+ v-if="state.isFetchingDDL"+ class="w-full h-full flex justify-center items-center"+ >+ <BBSpin />+ </div>+ <template v-else>+ <HighlightCodeBlock+ v-if="state.ddlStatement !== ''"+ class="text-sm whitespace-pre-wrap break-all"+ language="sql"+ :code="state.ddlStatement"+ ></HighlightCodeBlock>+ <span v-else class="py-2 italic">Nothing changed</span>+ </template>+ </div>+ </NPopover>+ </div>+ </div>+ <!-- column table -->+ <p class="py-2 mt-2 ml-3 text-gray-500 font-normal text-sm">Columns</p>+ <div+ class="w-full h-auto grid auto-rows-auto border-y relative overflow-y-auto"+ >+ <!-- column table header -->+ <div+ class="sticky top-0 z-10 grid grid-cols-[repeat(5,_minmax(0,_1fr))_32px] w-full text-sm leading-6 select-none bg-gray-50 text-gray-400"+ :class="tableCache.columnList.length > 0 && 'border-b'"+ >+ <span+ v-for="header in columnHeaderList"+ :key="header.key"+ class="table-header-item-container"+ >{{ header.label }}</span+ >+ <span></span>+ </div>+ <!-- column table body -->+ <div class="w-full">+ <div+ v-for="(column, index) in tableCache.columnList"+ :key="`${index}-${column.id}`"+ class="grid grid-cols-[repeat(5,_minmax(0,_1fr))_32px] gr text-sm even:bg-gray-50"+ >+ <div class="table-body-item-container">+ <input+ v-model="column.name"+ :disabled="column.id !== UNKNOWN_ID"+ placeholder="column name"+ class="w-full box-border border-none bg-transparent text-sm focus:bg-white focus:text-black placeholder:italic placeholder:text-gray-400"+ type="text"+ />+ </div>+ <div+ class="table-body-item-container flex flex-row justify-between items-center"+ >+ <input+ v-model="column.type"+ placeholder="column type"+ class="w-full pr-8 box-border border-none bg-transparent text-sm focus:bg-white focus:text-black placeholder:italic placeholder:text-gray-400"+ type="text"+ />+ <NDropdown+ trigger="click"+ :options="dataTypeOptions"+ @select="(dataType: string) => (column.type = dataType)"+ >+ <button class="absolute right-6">+ <heroicons-solid:chevron-up-down+ class="w-4 h-auto text-gray-400"+ />+ </button>+ </NDropdown>+ </div>+ <div+ class="table-body-item-container flex justify-start items-center"+ >+ <BBCheckbox+ class="ml-3"+ :value="column.nullable"+ @toggle="(value) => (column.nullable = value)"+ />+ </div>+ <div class="table-body-item-container">+ <input+ v-model="column.default"+ placeholder="column default value"+ class="w-full box-border border-none bg-transparent text-sm focus:bg-white focus:text-black placeholder:italic placeholder:text-gray-400"+ type="text"+ />+ </div>+ <div class="table-body-item-container">+ <input+ v-model="column.comment"+ placeholder="comment"+ class="w-full box-border border-none bg-transparent text-sm focus:bg-white focus:text-black placeholder:italic placeholder:text-gray-400"+ type="text"+ />+ </div>+ <div class="w-full flex justify-start items-center">+ <n-tooltip trigger="hover">+ <template #trigger>+ <heroicons-solid:x-mark+ class="w-[14px] h-auto text-gray-500 cursor-pointer hover:opacity-80"+ @click="handleRemoveColumn(column)"+ />+ </template>+ <span>Drop Column</span>+ </n-tooltip>+ </div>+ </div>+ </div>+ </div>+ <!-- Action buttons container -->+ <div+ class="py-2 w-full flex flex-row justify-between items-center space-x-2"+ >+ <button+ class="flex flex-row justify-center items-center border px-3 py-1 leading-6 text-sm text-gray-700 rounded cursor-pointer hover:bg-gray-100"+ @click="handleAddColumn"+ >+ <heroicons-outline:plus class="w-4 h-auto mr-1 text-gray-400" />+ Add column+ </button>+ <div>+ <div class="flex flex-row items-center space-x-2">+ <button+ class="flex flex-row justify-center items-center border px-3 py-1 leading-6 text-sm text-gray-700 rounded cursor-pointer hover:bg-gray-100"+ @click="handleDiscardChanges"+ >+ <heroicons-outline:trash class="w-4 h-auto mr-1 text-gray-400" />+ Discard changes+ </button>+ <button+ class="flex flex-row bg-accent text-white justify-center items-center px-3 py-1 leading-6 text-sm rounded cursor-pointer hover:opacity-80 disabled:cursor-not-allowed disabled:opacity-60"+ :disabled="!allowSave"+ @click="handleSaveChanges"+ >+ <heroicons-outline:save class="w-4 h-auto mr-1" />+ Save+ </button>+ </div>+ </div>+ </div>+ </div>+</template>++<script lang="ts" setup>+import { cloneDeep, isEqual } from "lodash-es";+import { computed, reactive } from "vue";+import {+ useNotificationStore,+ useTableStore,+ useUIEditorStore,+} from "@/store/modules";+import {+ TableTabContext,+ Column,+ UNKNOWN_ID,+ Table,+ DatabaseEdit,+} from "@/types";+import { BBCheckbox, BBSpin } from "@/bbkit";+import { getDataTypeSuggestionList } from "@/utils";+import { diffTableList } from "@/utils/UIEditor/diffTable";+import HighlightCodeBlock from "@/components/HighlightCodeBlock";++interface LocalState {+ isFetchingDDL: boolean;+ ddlStatement: string;+}++const state = reactive<LocalState>({+ isFetchingDDL: false,+ ddlStatement: "",+});+const editorStore = useUIEditorStore();+const tableStore = useTableStore();+const notificationStore = useNotificationStore();+const currentTab = editorStore.currentTab as TableTabContext;+const tableCache = currentTab.tableCache;+const table = editorStore.findTable(+ tableCache.id,+ tableCache.name,+ tableCache.database.id+) as Table;++const allowSave = computed(() => {+ return !isEqual(tableCache, table);+});++const columnHeaderList = computed(() => {+ return [+ {+ key: "name",+ label: "Name",+ },+ {+ key: "type",+ label: "Type",+ },+ {+ key: "nullable",+ label: "Nullable",+ },+ {+ key: "default",+ label: "Default",+ },+ {+ key: "comment",+ label: "Comment",+ },+ ];+});++const dataTypeOptions = computed(() => {+ return getDataTypeSuggestionList(tableCache.database.instance.engine).map(+ (dataType) => {+ return {+ label: dataType,+ key: dataType,+ };+ }+ );+});++const handleSaveChanges = async () => {+ if (tableCache.name === "") {+ notificationStore.pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: "Table name cannot be empty",+ });+ return;+ }++ const tableNameList = (+ await editorStore.getOrFetchTableListByDatabaseId(tableCache.database.id)+ )+ .filter((item) => item !== table)+ .map((table) => table.name);+ if (tableNameList.includes(tableCache.name)) {+ notificationStore.pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: "Invalid table name: duplicate with others",+ });+ return;+ }++ table.name = tableCache.name;+ table.columnList = cloneDeep(tableCache.columnList);+};++const handleAddColumn = () => {+ tableCache.columnList.push({+ id: UNKNOWN_ID,+ name: "",+ type: "",+ nullable: false,+ comment: "",+ } as Column);+};++const handleRemoveColumn = (column: Column) => {+ tableCache.columnList = tableCache.columnList.filter(+ (item) => item !== column+ );+};++const handleDiscardChanges = () => {+ tableCache.name = table.name;+ tableCache.columnList = cloneDeep(table.columnList);+};++const handlePreviewDDLStatement = async () => {+ const databaseEdit: DatabaseEdit = {+ databaseId: tableCache.database.id,+ createTableList: [],+ alterTableList: [],+ dropTableList: [],+ };+ if (table.id === UNKNOWN_ID) {+ const diffTableListResult = diffTableList([], [tableCache]);+ databaseEdit.createTableList = diffTableListResult.createTableList;+ } else {+ const originTable = tableStore.getTableByDatabaseIdAndTableId(+ tableCache.database.id,+ tableCache.id+ );+ const isDropped = editorStore.droppedTableList.includes(table);+ if (isDropped) {+ const diffTableListResult = diffTableList([originTable], []);+ databaseEdit.dropTableList = diffTableListResult.dropTableList;+ } else {+ const diffTableListResult = diffTableList([originTable], [table]);+ databaseEdit.alterTableList = diffTableListResult.alterTableList;+ }+ }+ state.isFetchingDDL = true;+ const statement = await editorStore.postDatabaseEdit(databaseEdit);+ state.ddlStatement = statement;+ state.isFetchingDDL = false;+};+</script>++<style scoped>+.table-header-item-container {+ @apply py-2 px-3;+}+.table-body-item-container {+ @apply w-full box-border p-px pr-2 relative;+}+</style>diff --git a/frontend/src/components/UIEditor/TabsContainer.vue b/frontend/src/components/UIEditor/TabsContainer.vuenew file mode 100644index 0000000000..e59d9361cd--- /dev/null+++ b/frontend/src/components/UIEditor/TabsContainer.vue@@ -0,0 +1,149 @@+<template>+ <div+ ref="tabsContainerRef"+ class="w-full max-w-full overflow-x-auto bg-gray-100 select-none shrink-0 rounded"+ >+ <div class="w-fit flex flex-nowrap">+ <div+ v-for="tab in tabList"+ :key="tab.id"+ class="tab-container px-1 pl-2 py-2 rounded w-40 flex flex-row justify-between items-center shrink-0 border border-transparent cursor-pointer"+ :class="[+ `tab-${tab.id}`,+ tab.id === currentTab?.id && 'bg-white border-gray-200',+ ]"+ @click="handleSelectTab(tab)"+ >+ <div class="flex flex-row justify-start items-center mr-1">+ <span class="mr-1">+ <heroicons-outline:circle-stack+ v-if="tab.type === UIEditorTabType.TabForDatabase"+ class="rounded w-4 h-auto text-gray-400"+ />+ <heroicons-outline:table-cells+ v-else-if="tab.type === UIEditorTabType.TabForTable"+ class="rounded w-4 h-auto text-gray-400"+ />+ </span>+ <NEllipsis+ class="text-sm w-24"+ :class="checkTabSaved(tab) ? '' : 'italic'"+ >{{ 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>+</template>++<script lang="ts" setup>+import { isEqual } from "lodash-es";+import { NEllipsis, useDialog } from "naive-ui";+import { computed, nextTick, ref, watch } from "vue";+import scrollIntoView from "scroll-into-view-if-needed";+import { useUIEditorStore } from "@/store";+import { TabContext, UIEditorTabType } from "@/types";++const editorStore = useUIEditorStore();+const tabsContainerRef = ref();+const tabList = computed(() => {+ return Array.from(editorStore.tabState.tabMap.values());+});+const currentTab = computed(() => {+ return editorStore.currentTab;+});+const dialog = useDialog();++watch(+ () => currentTab.value,+ () => {+ nextTick(() => {+ const element = tabsContainerRef.value?.querySelector(+ `.tab-${currentTab.value?.id}`+ );+ scrollIntoView(element);+ });+ }+);++const checkTabSaved = (tab: TabContext) => {+ if (tab.type === UIEditorTabType.TabForTable) {+ const table = editorStore.tableList.find((table) => {+ return (+ table.id === tab.tableCache.id &&+ table.database.id === tab.tableCache.database.id &&+ table.name === tab.tableCache.name+ );+ });+ if (!isEqual(tab.tableCache, table)) {+ return false;+ }+ } else if (tab.type === UIEditorTabType.TabForDatabase) {+ // Edit database metadata is not allowed.+ return true;+ }++ return true;+};++const getTabName = (tab: TabContext) => {+ if (tab.type === UIEditorTabType.TabForDatabase) {+ const database = editorStore.databaseList.find(+ (database) => database.id === tab.databaseId+ );+ return `${database?.name || "unknown database"}`;+ } else if (tab.type === UIEditorTabType.TabForTable) {+ return `${tab.tableCache.name}`;+ } else {+ // Should never reach here.+ return "unknown structure";+ }+};++const handleSelectTab = (tab: TabContext) => {+ editorStore.setCurrentTab(tab.id);+};++const handleCloseTab = (tab: TabContext) => {+ if (tab.type === UIEditorTabType.TabForDatabase) {+ editorStore.closeTab(tab.id);+ } else if (tab.type === UIEditorTabType.TabForTable) {+ const table = editorStore.tableList.find((table) => {+ return (+ table.id === tab.tableCache.id &&+ table.database.id === tab.tableCache.database.id &&+ table.name === tab.tableCache.name+ );+ });+ if (!table) {+ return;+ }+ if (isEqual(tab.tableCache, table)) {+ editorStore.closeTab(tab.id);+ } else {+ dialog.warning({+ title: "Confirm to close",+ content:+ "There are unsaved changes. Are you sure you want to close the panel? Your changes will be lost.",+ negativeText: "Cancel",+ positiveText: "Confirm",+ onPositiveClick: () => {+ editorStore.closeTab(tab.id);+ },+ });+ }+ }+};+</script>++<style scoped>+.tab-container:hover > .tab-close-button {+ @apply flex;+}+</style>diff --git a/frontend/src/components/UIEditor/UIEditor.vue b/frontend/src/components/UIEditor/UIEditor.vuenew file mode 100644index 0000000000..9bfa670df9--- /dev/null+++ b/frontend/src/components/UIEditor/UIEditor.vue@@ -0,0 +1,103 @@+<template>+ <div v-if="!state.isLoading" class="w-full h-full">+ <Splitpanes+ class="default-theme w-full h-full flex flex-row overflow-hidden"+ >+ <Pane size="20">+ <AsidePanel />+ </Pane>+ <Pane min-size="60" size="80">+ <main class="pl-2 pt-2 w-full h-full flex flex-col overflow-y-auto">+ <template v-if="currentTab">+ <TabsContainer />+ <div+ :key="currentTab.id"+ class="w-full h-auto relative overflow-y-auto"+ >+ <DatabaseEditor+ v-if="currentTab.type === UIEditorTabType.TabForDatabase"+ />+ <TableEditor+ v-else-if="currentTab.type === UIEditorTabType.TabForTable"+ />+ </div>+ </template>+ <EmptyTips v-else />+ </main>+ </Pane>+ </Splitpanes>+ </div>+</template>++<script lang="ts" setup>+import { uniq } from "lodash-es";+import { Splitpanes, Pane } from "splitpanes";+import { computed, onMounted, PropType, reactive } from "vue";+import { useInstanceStore, useUIEditorStore } from "@/store";+import { DatabaseId, UIEditorTabType } from "@/types";+import AsidePanel from "./AsidePanel.vue";+import EmptyTips from "./EmptyTips.vue";+import TabsContainer from "./TabsContainer.vue";+import DatabaseEditor from "./Panels/DatabaseEditor.vue";+import TableEditor from "./Panels/TableEditor.vue";++interface LocalState {+ isLoading: boolean;+}++const props = defineProps({+ databaseIdList: {+ type: Array as PropType<DatabaseId[]>,+ required: true,+ },+});+const state = reactive<LocalState>({+ isLoading: true,+});++const editorStore = useUIEditorStore();+const instanceStore = useInstanceStore();+const currentTab = computed(() => {+ return editorStore.currentTab;+});++onMounted(async () => {+ // Prepare instance and database data.+ const databaseIdList = props.databaseIdList;+ const databaseList = await editorStore.fetchDatabaseList(databaseIdList);+ const instanceIdList = uniq(+ databaseList.map((database) => database.instanceId)+ );+ for (const instanceId of instanceIdList) {+ await instanceStore.getOrFetchInstanceById(instanceId);+ }+ state.isLoading = false;+});+</script>++<style>+@import "splitpanes/dist/splitpanes.css";++/* splitpanes pane style */+.splitpanes.default-theme .splitpanes__pane {+ @apply bg-transparent !transition-none;+}++.splitpanes.default-theme .splitpanes__splitter {+ @apply bg-gray-100 border-none;+}++.splitpanes.default-theme .splitpanes__splitter:hover {+ @apply bg-indigo-300;+}++.splitpanes.default-theme .splitpanes__splitter::before,+.splitpanes.default-theme .splitpanes__splitter::after {+ @apply bg-gray-700 opacity-50 text-white;+}++.splitpanes.default-theme .splitpanes__splitter:hover::before,+.splitpanes.default-theme .splitpanes__splitter:hover::after {+ @apply bg-white opacity-100;+}+</style>diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex bba1a73f41..cdc503f38d 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -958,6 +958,9 @@"character-sets-diff-found": "There are differences between character sets.","preview-issue": "Preview issue"},+ "ui-editor": {+ "preview-issue": "Preview issue"+ },"sensitive": "Sensitive"},"repository": {diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 4fdf5783aa..d7641b35d8 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -958,6 +958,9 @@"character-sets-diff-found": "Schema 之间的字符集不同","preview-issue": "预览工单"},+ "ui-editor": {+ "preview-issue": "预览工单"+ },"sensitive": "敏感"},"repository": {diff --git a/frontend/src/store/modules/UIEditor.ts b/frontend/src/store/modules/UIEditor.tsindex 5505d67b03..ebd01f6d6a 100644--- a/frontend/src/store/modules/UIEditor.ts+++ b/frontend/src/store/modules/UIEditor.ts@@ -165,6 +165,15 @@ export const useUIEditorStore = defineStore("UIEditor", {table.id = UNKNOWN_ID;table.name = tableName;table.database = database;+ table.columnList = [];++ // generate a default column.+ const unknownColumn = unknown("COLUMN");+ unknownColumn.name = "id";+ unknownColumn.type = "int";+ unknownColumn.comment = "ID";+ table.columnList.push(unknownColumn);+this.tableList.push(table);return table;},diff --git a/frontend/src/types/common.ts b/frontend/src/types/common.tsindex f974e26038..1835301190 100644--- a/frontend/src/types/common.ts+++ b/frontend/src/types/common.ts@@ -27,6 +27,7 @@ import { Policy, DefaultApprovalPolicy } from "./policy";import { Sheet } from "./sheet";import { SQLReviewPolicy } from "./sqlReview";import { Table } from "./table";+import { Column } from "./column";// System bot idexport const SYSTEM_BOT_ID = 1;@@ -131,7 +132,8 @@ export type ResourceType =| "DEPLOYMENT_CONFIG"| "SHEET"| "SQL_REVIEW"- | "TABLE";+ | "TABLE"+ | "COLUMN";interface ResourceMaker {(type: "PRINCIPAL"): Principal;@@ -160,6 +162,7 @@ interface ResourceMaker {(type: "SHEET"): Sheet;(type: "SQL_REVIEW"): SQLReviewPolicy;(type: "TABLE"): Table;+ (type: "COLUMN"): Column;}const makeUnknown = (type: ResourceType) => {@@ -538,6 +541,23 @@ const makeUnknown = (type: ResourceType) => {columnList: [],};+ const UNKNOWN_COLUMN: Column = {+ id: UNKNOWN_ID,+ databaseId: UNKNOWN_DATABASE.id,+ tableId: UNKNOWN_TABLE.id,+ creatorId: UNKNOWN_PRINCIPAL.id,+ createdTs: 0,+ updaterId: UNKNOWN_PRINCIPAL.id,+ updatedTs: 0,+ name: "<<Unknown table>>",+ position: 0,+ nullable: false,+ type: "Unknown type",+ characterSet: "",+ collation: "",+ comment: "",+ };+switch (type) {case "PRINCIPAL":return UNKNOWN_PRINCIPAL;@@ -591,6 +611,8 @@ const makeUnknown = (type: ResourceType) => {return UNKNOWN_SQL_REVIEW_POLICY;case "TABLE":return UNKNOWN_TABLE;+ case "COLUMN":+ return UNKNOWN_COLUMN;}};export const unknown = makeUnknown as ResourceMaker;