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: auto-save changes in UI editor (#3722)
boojackeea76305db79
diff --git a/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vue b/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vueindex 08f75d35ab..df08b5b7d7 100644--- a/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vue+++ b/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vue@@ -5,10 +5,10 @@@close="dismissModal"><div- class="w-full flex flex-row justify-start items-center border-b border-b-gray-300"+ class="w-full flex flex-row justify-start items-center border-b pl-1 border-b-gray-300"><button- 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="-mb-px px-3 leading-9 rounded-t-md text-sm text-gray-500 border border-b-0 border-transparent cursor-pointer select-none outline-none":class="state.selectedTab === 'ui-editor' &&'bg-white border-gray-300 text-gray-800'@@ -18,7 +18,7 @@{{ $t("ui-editor.self") }}</button><button- 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="-mb-px px-3 leading-9 rounded-t-md text-sm text-gray-500 border border-b-0 border-transparent cursor-pointer select-none outline-none":class="state.selectedTab === 'raw-sql' &&'bg-white border-gray-300 text-gray-800'diff --git a/frontend/src/components/UIEditor/DatabaseTree.vue b/frontend/src/components/UIEditor/DatabaseTree.vueindex ad51b3e5e7..5e929e07b3 100644--- a/frontend/src/components/UIEditor/DatabaseTree.vue+++ b/frontend/src/components/UIEditor/DatabaseTree.vue@@ -37,12 +37,20 @@/></div></div>++ <TableNameModal+ v-if="state.tableNameModalContext !== undefined"+ :database-id="state.tableNameModalContext.databaseId"+ :table="state.tableNameModalContext.table"+ @close="state.tableNameModalContext = undefined"+ /></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 { useI18n } from "vue-i18n";import scrollIntoView from "scroll-into-view-if-needed";import {DatabaseId,@@ -60,10 +68,10 @@ import {} from "@/store";import { getHighlightHTMLByKeyWords, isDescendantOf } from "@/utils";import InstanceEngineIcon from "@/components/InstanceEngineIcon.vue";+import TableNameModal from "./Modals/TableNameModal.vue";import DatabaseIcon from "~icons/heroicons-outline/database";import TableIcon from "~icons/heroicons-outline/table";import EllipsisIcon from "~icons/heroicons-solid/ellipsis-horizontal";-import { useI18n } from "vue-i18n";interface BaseTreeNode extends TreeOption {key: string;@@ -102,6 +110,10 @@ interface TreeContextMenu {interface LocalState {shouldRelocateTreeNode: boolean;+ tableNameModalContext?: {+ databaseId: DatabaseId;+ table: Table | undefined;+ };}const { t } = useI18n();@@ -148,9 +160,13 @@ const contextMenuOptions = computed(() => {label: t("ui-editor.actions.restore"),});} else {+ options.push({+ key: "rename",+ label: t("ui-editor.actions.rename"),+ });options.push({key: "drop",- label: t("ui-editor.actions.drop"),+ label: t("ui-editor.actions.drop-table"),});}return options;@@ -203,10 +219,15 @@ onMounted(async () => {const node = databaseTreeNodeList[0];await loadSubTree(node);expandedKeysRef.value.push(node.key);+ editorStore.addTab({+ id: generateUniqueTabId(),+ type: UIEditorTabType.TabForDatabase,+ databaseId: node.databaseId,+ });}});-watch(tableList.value, () => {+watch([tableList.value, databaseDataLoadedSet.value], () => {const databaseTreeNodeList: TreeNodeForDatabase[] = [];for (const treeNode of treeDataRef.value) {if (treeNode.type === "instance") {@@ -217,6 +238,9 @@ watch(tableList.value, () => {}for (const database of databaseList.value) {+ if (!databaseDataLoadedSet.value.has(database.id)) {+ continue;+ }const databaseTreeNode = databaseTreeNodeList.find((treeNode) =>treeNode.databaseId === database.id &&@@ -226,30 +250,30 @@ watch(tableList.value, () => {continue;}- const databaseTableList = [];+ const databaseTableList: Table[] = [];for (const table of tableList.value) {if (table.database.id === database.id) {databaseTableList.push(table);}}- databaseTreeNode.children = databaseTableList.map((table) => {- return {- type: "table",- key: `t-${table.database.id}-${table.id}-${table.name}`,- label: table.name,- children: [],- isLeaf: true,- instanceId: database.instance.id,- databaseId: database.id,- tableId: table.id,- table: table,- };- });-- if (databaseTreeNode.children.length > 0) {- databaseTreeNode.isLeaf = false;- } else {+ if (databaseTableList.length === 0) {databaseTreeNode.isLeaf = true;+ databaseTreeNode.children = [];+ } else {+ databaseTreeNode.isLeaf = false;+ databaseTreeNode.children = databaseTableList.map((table) => {+ return {+ type: "table",+ key: `t-${table.database.id}-${table.id}-${table.name}`,+ label: table.name,+ children: [],+ isLeaf: true,+ instanceId: database.instance.id,+ databaseId: database.id,+ tableId: table.id,+ table: table,+ };+ });}}});@@ -409,11 +433,9 @@ const loadSubTree = async (treeNode: TreeNode) => {const tableList = await editorStore.getOrFetchTableListByDatabaseId(databaseId);-if (tableList.length === 0) {+ treeNode.children = undefined;treeNode.isLeaf = true;- } else {- treeNode.isLeaf = false;}}};@@ -441,11 +463,11 @@ const nodeProps = ({ option: treeNode }: { option: TreeNode }) => {editorStore.addTab({id: generateUniqueTabId(),type: UIEditorTabType.TabForDatabase,- databaseId: treeNode.databaseId as any,+ databaseId: treeNode.databaseId,});} else if (treeNode.type === "table") {- const databaseId = treeNode.databaseId as any;- const tableId = treeNode.tableId as any;+ const databaseId = treeNode.databaseId;+ const tableId = treeNode.tableId;editorStore.addTab({id: generateUniqueTabId(),@@ -473,17 +495,18 @@ const nodeProps = ({ option: treeNode }: { option: TreeNode }) => {});}},- ondblclick(e: MouseEvent) {- e.preventDefault();- e.stopImmediatePropagation();- const index = expandedKeysRef.value.findIndex(- (key) => key === treeNode.key- );- if (index >= 0) {- expandedKeysRef.value.splice(index, 1);- } else {- expandedKeysRef.value.push(treeNode.key);- }+ 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);@@ -496,18 +519,18 @@ const handleContextMenuDropdownSelect = async (key: string) => {if (treeNode?.type === "database") {if (key === "create-table") {await loadSubTree(treeNode);- const table = editorStore.createNewTable(treeNode.databaseId);- editorStore.addTab({- id: generateUniqueTabId(),- type: UIEditorTabType.TabForTable,+ state.tableNameModalContext = {databaseId: treeNode.databaseId,- tableId: table.id,- table: table,- tableCache: cloneDeep(table),- });+ table: undefined,+ };}} else if (treeNode?.type === "table") {- if (key === "drop") {+ if (key === "rename") {+ state.tableNameModalContext = {+ databaseId: treeNode.databaseId,+ table: treeNode.table,+ };+ } else if (key === "drop") {editorStore.dropTable(treeNode.table);} else if (key === "restore") {editorStore.restoreTable(diff --git a/frontend/src/components/UIEditor/Modals/TableNameModal.vue b/frontend/src/components/UIEditor/Modals/TableNameModal.vuenew file mode 100644index 0000000000..cea7d76a14--- /dev/null+++ b/frontend/src/components/UIEditor/Modals/TableNameModal.vue@@ -0,0 +1,133 @@+<template>+ <BBModal+ :title="+ isCreatingTable+ ? $t('ui-editor.actions.create-table')+ : $t('ui-editor.actions.rename')+ "+ class="shadow-inner outline outline-gray-200"+ @close="dismissModal"+ >+ <div class="w-72">+ <p>{{ $t("ui-editor.table.name") }}</p>+ <BBTextField+ class="my-2 w-full"+ :required="true"+ :focus-on-mount="true"+ :value="state.tableName"+ @input="handleTableNameChange"+ />+ </div>+ <div class="w-full flex items-center justify-end mt-2 space-x-3 pr-1 pb-1">+ <button type="button" class="btn-normal" @click="dismissModal">+ {{ $t("common.cancel") }}+ </button>+ <button class="btn-primary" @click="handleConfirmButtonClick">+ {{ isCreatingTable ? $t("common.create") : $t("common.save") }}+ </button>+ </div>+ </BBModal>+</template>++<script lang="ts" setup>+import { computed, PropType, reactive } from "vue";+import { DatabaseId, Table, UNKNOWN_ID, UIEditorTabType } from "@/types";+import {+ useUIEditorStore,+ useNotificationStore,+ generateUniqueTabId,+} from "@/store";+import { cloneDeep } from "lodash-es";+import { useI18n } from "vue-i18n";++const tableNameFieldRegexp = /^\S+$/;++interface LocalState {+ tableName: string;+}++const props = defineProps({+ databaseId: {+ type: Number as PropType<DatabaseId>,+ default: UNKNOWN_ID,+ },+ table: {+ type: Object as PropType<Table | undefined>,+ default: undefined,+ },+});++const emit = defineEmits<{+ (event: "close"): void;+}>();++const { t } = useI18n();+const editorStore = useUIEditorStore();+const notificationStore = useNotificationStore();+const state = reactive<LocalState>({+ tableName: props.table?.name || "",+});++const isCreatingTable = computed(() => {+ return props.table === undefined;+});++const handleTableNameChange = (event: Event) => {+ state.tableName = (event.target as HTMLInputElement).value;+};++const handleConfirmButtonClick = async () => {+ if (!tableNameFieldRegexp.test(state.tableName)) {+ notificationStore.pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("ui-editor.message.invalid-table-name"),+ });+ return;+ }++ const databaseId = props.databaseId;+ const tableList = await editorStore.getOrFetchTableListByDatabaseId(+ databaseId+ );+ const tableNameList = tableList.map((table) => table.name);+ if (tableNameList.includes(state.tableName)) {+ notificationStore.pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("ui-editor.message.duplicated-table-name"),+ });+ return;+ }++ if (isCreatingTable.value) {+ const table = editorStore.createNewTable(props.databaseId);+ table.name = state.tableName;+ editorStore.addTab({+ id: generateUniqueTabId(),+ type: UIEditorTabType.TabForTable,+ databaseId: props.databaseId,+ tableId: table.id,+ table: table,+ tableCache: cloneDeep(table),+ });+ dismissModal();+ } else {+ const originTable = editorStore.tableList.find(+ (item) => item === props.table+ );+ if (originTable) {+ originTable.name = state.tableName;+ const tab = editorStore.getTableTabByTable(originTable);+ if (tab) {+ tab.tableCache.name = originTable.name;+ }+ }+ dismissModal();+ }+};++const dismissModal = () => {+ emit("close");+};+</script>diff --git a/frontend/src/components/UIEditor/Panels/DatabaseEditor.vue b/frontend/src/components/UIEditor/Panels/DatabaseEditor.vueindex 92edffdb91..603d00a39b 100644--- a/frontend/src/components/UIEditor/Panels/DatabaseEditor.vue+++ b/frontend/src/components/UIEditor/Panels/DatabaseEditor.vue@@ -1,16 +1,16 @@<template><div class="grid auto-rows-auto w-full h-full overflow-y-auto"><div- class="pt-3 w-full flex justify-start items-center border-b border-b-gray-300"+ class="pt-3 pl-1 w-full flex justify-start items-center border-b border-b-gray-300"><spanclass="-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' &&+ state.selectedTab === 'table-list' &&'bg-white border-gray-300 text-gray-800'"- @click="handleChangeTab('list')"- >{{ $t("ui-editor.list") }}</span+ @click="handleChangeTab('table-list')"+ >{{ $t("ui-editor.table-list") }}</span><spanclass="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"@@ -33,11 +33,8 @@</div><!-- List view -->- <template v-if="state.selectedTab === 'list'">+ <template v-if="state.selectedTab === 'table-list'"><div class="py-2 w-full flex justify-between items-center space-x-2">- <span class="ml-3 text-sm text-gray-500">{{- $t("ui-editor.tables")- }}</span><buttonclass="flex flex-row justify-center items-center border px-3 py-1 leading-6 rounded text-sm hover:bg-gray-100"@click="handleCreateNewTable"@@ -132,10 +129,18 @@</template></div></div>++ <TableNameModal+ v-if="state.tableNameModalContext !== undefined"+ :database-id="state.tableNameModalContext.databaseId"+ :table="state.tableNameModalContext.table"+ @close="state.tableNameModalContext = undefined"+ /></template><script lang="ts" setup>import { cloneDeep } from "lodash-es";+import { NEllipsis } from "naive-ui";import { computed, reactive, ref, watch } from "vue";import { useI18n } from "vue-i18n";import {@@ -144,17 +149,27 @@ import {useTableStore,useUIEditorStore,} from "@/store";-import { DatabaseTabContext, Table, UIEditorTabType } from "@/types";+import {+ DatabaseId,+ DatabaseTabContext,+ Table,+ UIEditorTabType,+} from "@/types";import { bytesToString } from "@/utils";import { diffTableList } from "@/utils/UIEditor/diffTable";import HighlightCodeBlock from "@/components/HighlightCodeBlock";+import TableNameModal from "../Modals/TableNameModal.vue";-type TabType = "list" | "er-diagram" | "raw-sql";+type TabType = "table-list" | "er-diagram" | "raw-sql";interface LocalState {selectedTab: TabType;isFetchingDDL: boolean;statement: string;+ tableNameModalContext?: {+ databaseId: DatabaseId;+ table: Table | undefined;+ };}const { t } = useI18n();@@ -162,7 +177,7 @@ const editorStore = useUIEditorStore();const databaseStore = useDatabaseStore();const tableStore = useTableStore();const state = reactive<LocalState>({- selectedTab: "list",+ selectedTab: "table-list",isFetchingDDL: false,statement: "",});@@ -255,15 +270,10 @@ const handleChangeTab = (tab: TabType) => {};const handleCreateNewTable = () => {- const table = editorStore.createNewTable(database.id);- editorStore.addTab({- id: generateUniqueTabId(),- type: UIEditorTabType.TabForTable,+ state.tableNameModalContext = {databaseId: database.id,- tableId: table.id,- table: table,- tableCache: cloneDeep(table),- });+ table: undefined,+ };};const handleTableItemClick = (table: Table) => {diff --git a/frontend/src/components/UIEditor/Panels/TableEditor.vue b/frontend/src/components/UIEditor/Panels/TableEditor.vueindex 7ce39865cc..640d9e31a9 100644--- a/frontend/src/components/UIEditor/Panels/TableEditor.vue+++ b/frontend/src/components/UIEditor/Panels/TableEditor.vue@@ -1,222 +1,203 @@<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"+ class="pt-3 pl-1 w-full flex justify-start items-center border-b border-b-gray-300">- <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"- >{{ $t("ui-editor.table.name") }}:- </span>- <input- v-model="tableCache.name"- placeholder=""- class="w-full leading-6 px-2 py-1 rounded border border-gray-200 text-sm"- type="text"- />+ <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 === 'column-list' &&+ 'bg-white border-gray-300 text-gray-800'+ "+ @click="handleChangeTab('column-list')"+ >{{ $t("ui-editor.column-list") }}</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')"+ >{{ $t("ui-editor.raw-sql") }}</span+ >+ </div>++ <template v-if="state.selectedTab === 'column-list'">+ <!-- column table -->+ <div class="w-full py-2 flex flex-row justify-between items-center">+ <div>+ <button+ class="flex flex-row justify-center items-center border px-3 py-1 leading-6 text-sm text-gray-700 rounded cursor-pointer hover:opacity-80"+ @click="handleAddColumn"+ >+ <heroicons-outline:plus class="w-4 h-auto mr-1 text-gray-400" />+ {{ $t("ui-editor.actions.add-column") }}+ </button>+ </div>+ <div>+ <button+ v-if="table.id !== UNKNOWN_ID"+ class="flex flex-row justify-center items-center border px-3 py-1 leading-6 text-sm text-gray-700 rounded cursor-pointer hover:opacity-80 disabled:cursor-not-allowed disabled:opacity-60"+ :disabled="allowResetTable"+ @click="handleDiscardChanges"+ >+ <heroicons-solid:arrow-uturn-left+ class="w-4 h-auto mr-1 text-gray-400"+ />+ {{ $t("ui-editor.actions.reset") }}+ </button></div></div>- <div class="flex flex-row items-center space-x-2">- <NPopover- trigger="click"- placement="bottom-center"- @update:show="handlePreviewDDLStatement"+ <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(4,_minmax(0,_1fr))_112px_32px] w-full text-sm leading-6 select-none bg-gray-50 text-gray-400"+ :class="tableCache.columnList.length > 0 && 'border-b'">- <template #trigger>- <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"+ <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(4,_minmax(0,_1fr))_112px_32px] gr text-sm even:bg-gray-50"+ >+ <div class="table-body-item-container">+ <input+ v-model="column.name"+ placeholder="column name"+ class="column-field-input"+ type="text"+ />+ </div>+ <div+ class="table-body-item-container flex flex-row justify-between items-center">- {{ $t("ui-editor.actions.sql-preview") }}- </button>- </template>- <div class="w-112 min-h-[16em] max-h-[32em] overflow-y-auto">+ <input+ v-model="column.type"+ placeholder="column type"+ class="column-field-input !pr-8"+ type="text"+ />+ <NDropdown+ trigger="click"+ :options="dataTypeOptions"+ @select="(dataType: string) => (column.type = dataType)"+ >+ <button class="absolute right-5">+ <heroicons-solid:chevron-up-down+ class="w-4 h-auto text-gray-400"+ />+ </button>+ </NDropdown>+ </div>+ <div class="table-body-item-container">+ <input+ v-model="column.default"+ placeholder="column default value"+ class="column-field-input"+ type="text"+ />+ </div>+ <div class="table-body-item-container">+ <input+ v-model="column.comment"+ placeholder="comment"+ class="column-field-input"+ type="text"+ />+ </div><div- v-if="state.isFetchingDDL"- class="w-full h-full flex justify-center items-center"+ class="table-body-item-container flex justify-start items-center">- <BBSpin />+ <BBCheckbox+ class="ml-3"+ :value="column.nullable"+ @toggle="(value) => (column.nullable = value)"+ />+ </div>+ <div class="w-full flex justify-start items-center">+ <n-tooltip trigger="hover">+ <template #trigger>+ <heroicons:trash+ class="w-[14px] h-auto text-gray-500 cursor-pointer hover:opacity-80"+ @click="handleRemoveColumn(column)"+ />+ </template>+ <span>Drop Column</span>+ </n-tooltip></div>- <template v-else>- <HighlightCodeBlock- v-if="state.statement !== ''"- class="text-sm whitespace-pre-wrap break-all"- language="sql"- :code="state.statement"- ></HighlightCodeBlock>- <span v-else class="py-2 italic">{{- $t("ui-editor.nothing-changed")- }}</span>- </template></div>- </NPopover>- <button- class="flex flex-row justify-center items-center border px-3 py-1 leading-6 text-sm text-gray-700 rounded cursor-pointer hover:opacity-80 disabled:cursor-not-allowed disabled:opacity-60"- :disabled="!allowSave"- @click="handleDiscardChanges"- >- <heroicons-solid:arrow-uturn-left- class="w-4 h-auto mr-1 text-gray-400"- />- {{ $t("ui-editor.actions.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" />- {{ $t("ui-editor.actions.save") }}- </button>- </div>- </div>- <!-- column table -->- <div class="w-full py-2 flex flex-row justify-between items-center">- <span class="ml-3 text-gray-500 font-normal text-sm">{{- t("ui-editor.columns")- }}</span>- <div>- <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" />- {{ $t("ui-editor.actions.add-column") }}- </button>+ </div></div>- </div>+ </template><div- class="w-full h-auto grid auto-rows-auto border-y relative overflow-y-auto"+ v-else-if="state.selectedTab === 'raw-sql'"+ class="w-full h-full overflow-y-auto">- <!-- column table header --><div- class="sticky top-0 z-10 grid grid-cols-[repeat(4,_minmax(0,_1fr))_112px_32px] w-full text-sm leading-6 select-none bg-gray-50 text-gray-400"- :class="tableCache.columnList.length > 0 && 'border-b'"+ v-if="state.isFetchingDDL"+ class="w-full h-full min-h-[64px] flex justify-center items-center">- <span- v-for="header in columnHeaderList"- :key="header.key"- class="table-header-item-container"- >{{ header.label }}</span- >- <span></span>+ <BBSpin /></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(4,_minmax(0,_1fr))_112px_32px] gr text-sm even:bg-gray-50"- >- <div class="table-body-item-container">- <input- v-model="column.name"- placeholder="column name"- class="column-field-input"- 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="column-field-input !pr-8"- type="text"- />- <NDropdown- trigger="click"- :options="dataTypeOptions"- @select="(dataType: string) => (column.type = dataType)"- >- <button class="absolute right-5">- <heroicons-solid:chevron-up-down- class="w-4 h-auto text-gray-400"- />- </button>- </NDropdown>- </div>- <div class="table-body-item-container">- <input- v-model="column.default"- placeholder="column default value"- class="column-field-input"- type="text"- />- </div>- <div class="table-body-item-container">- <input- v-model="column.comment"- placeholder="comment"- class="column-field-input"- type="text"- />- </div>- <div- class="table-body-item-container flex justify-start items-center"- >- <BBCheckbox- class="ml-3"- :value="column.nullable"- @toggle="(value) => (column.nullable = value)"- />- </div>- <div class="w-full flex justify-start items-center">- <n-tooltip trigger="hover">- <template #trigger>- <heroicons:trash- class="w-[14px] h-auto text-gray-500 cursor-pointer hover:opacity-80"- @click="handleRemoveColumn(column)"- />- </template>- <span>Drop Column</span>- </n-tooltip>- </div>+ <template v-else>+ <HighlightCodeBlock+ v-if="state.statement !== ''"+ class="text-sm px-3 py-2 whitespace-pre-wrap break-all"+ language="sql"+ :code="state.statement"+ ></HighlightCodeBlock>+ <div v-else class="flex px-3 py-2 italic text-sm text-gray-600">+ {{ $t("ui-editor.nothing-changed") }}</div>- </div>+ </template></div></div></template><script lang="ts" setup>-import { cloneDeep, isEqual } from "lodash-es";-import { computed, reactive } from "vue";+import { isEqual } from "lodash-es";+import { computed, reactive, watch } from "vue";import { useI18n } from "vue-i18n";-import {- useNotificationStore,- useTableStore,- useUIEditorStore,-} from "@/store/modules";+import { useDebounceFn } from "@vueuse/core";+import { useTableStore, useUIEditorStore } from "@/store/modules";import { TableTabContext, Column, UNKNOWN_ID, DatabaseEdit } from "@/types";import { BBCheckbox, BBSpin } from "@/bbkit";import { getDataTypeSuggestionList } from "@/utils";import { diffTableList } from "@/utils/UIEditor/diffTable";import HighlightCodeBlock from "@/components/HighlightCodeBlock";-const tableOrColumnNameFieldRegexp = /^\S+$/;-const columnTypeFieldRegexp = /^\S+$/;+type TabType = "column-list" | "raw-sql";interface LocalState {+ selectedTab: TabType;isFetchingDDL: boolean;statement: string;}const { t } = useI18n();const state = reactive<LocalState>({+ selectedTab: "column-list",isFetchingDDL: false,statement: "",});const editorStore = useUIEditorStore();const tableStore = useTableStore();-const notificationStore = useNotificationStore();const currentTab = editorStore.currentTab as TableTabContext;const table = currentTab.table;const tableCache = currentTab.tableCache;-const allowSave = computed(() => {- return !isEqual(tableCache, table);-});-const columnHeaderList = computed(() => {return [{@@ -253,63 +234,68 @@ const dataTypeOptions = computed(() => {);});-const handleSaveChanges = async () => {- if (!tableOrColumnNameFieldRegexp.test(tableCache.name)) {- notificationStore.pushNotification({- module: "bytebase",- style: "CRITICAL",- title: t("ui-editor.message.invalid-table-name"),- });- return;- }+const allowResetTable = computed(() => {+ const originTable = tableStore.getTableByDatabaseIdAndTableId(+ currentTab.databaseId,+ currentTab.tableId+ );- 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: t("ui-editor.message.duplicated-table-name"),- });- return;- }+ return isEqual(table, originTable);+});- for (const column of tableCache.columnList) {- if (!tableOrColumnNameFieldRegexp.test(column.name)) {- notificationStore.pushNotification({- module: "bytebase",- style: "CRITICAL",- title: t("ui-editor.message.invalid-column-name"),- });- return;- }- const foundColumnListByName = tableCache.columnList.filter(- (item) => item.name === column.name- );- if (foundColumnListByName.length > 1) {- notificationStore.pushNotification({- module: "bytebase",- style: "CRITICAL",- title: t("ui-editor.message.duplicated-column-name"),- });- return;- }- if (!columnTypeFieldRegexp.test(column.type)) {- notificationStore.pushNotification({- module: "bytebase",- style: "CRITICAL",- title: t("ui-editor.message.invalid-column-type"),- });- return;+watch([tableCache], () => {+ handleSaveChanges();+});++watch(+ () => state.selectedTab,+ async () => {+ if (state.selectedTab === "raw-sql") {+ const databaseEdit: DatabaseEdit = {+ databaseId: table.database.id,+ createTableList: [],+ alterTableList: [],+ renameTableList: [],+ dropTableList: [],+ };+ if (table.id === UNKNOWN_ID) {+ const diffTableListResult = diffTableList([], [table]);+ databaseEdit.createTableList = diffTableListResult.createTableList;+ } else {+ const originTable = tableStore.getTableByDatabaseIdAndTableId(+ table.database.id,+ table.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;+ databaseEdit.renameTableList = diffTableListResult.renameTableList;+ }+ }+ state.isFetchingDDL = true;+ try {+ const statement = await editorStore.postDatabaseEdit(databaseEdit);+ state.statement = statement;+ } catch (error) {+ state.statement = "";+ }+ state.isFetchingDDL = false;}}+);- editorStore.saveTab(currentTab);+const handleChangeTab = (tab: TabType) => {+ state.selectedTab = tab;};+const handleSaveChanges = useDebounceFn(async () => {+ editorStore.saveTab(currentTab);+}, 500);+const handleAddColumn = () => {tableCache.columnList.push({id: UNKNOWN_ID,@@ -327,48 +313,7 @@ const handleRemoveColumn = (column: Column) => {};const handleDiscardChanges = () => {- tableCache.name = table.name;- tableCache.columnList = cloneDeep(table.columnList);-};--const handlePreviewDDLStatement = async (show: boolean) => {- if (!show) {- return;- }-- const databaseEdit: DatabaseEdit = {- databaseId: table.database.id,- createTableList: [],- alterTableList: [],- renameTableList: [],- dropTableList: [],- };- if (table.id === UNKNOWN_ID) {- const diffTableListResult = diffTableList([], [table]);- databaseEdit.createTableList = diffTableListResult.createTableList;- } else {- const originTable = tableStore.getTableByDatabaseIdAndTableId(- table.database.id,- table.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;- databaseEdit.renameTableList = diffTableListResult.renameTableList;- }- }- state.isFetchingDDL = true;- try {- const statement = await editorStore.postDatabaseEdit(databaseEdit);- state.statement = statement;- } catch (error) {- state.statement = "";- }- state.isFetchingDDL = false;+ editorStore.discardTabChanges(currentTab);};</script>diff --git a/frontend/src/components/UIEditor/TabsContainer.vue b/frontend/src/components/UIEditor/TabsContainer.vueindex 0cbce2c151..3b089633af 100644--- a/frontend/src/components/UIEditor/TabsContainer.vue+++ b/frontend/src/components/UIEditor/TabsContainer.vue@@ -44,7 +44,7 @@<script lang="ts" setup>import { isEqual } from "lodash-es";-import { NEllipsis, useDialog } from "naive-ui";+import { NEllipsis } from "naive-ui";import { computed, nextTick, ref, watch } from "vue";import scrollIntoView from "scroll-into-view-if-needed";import { useTableStore, useUIEditorStore } from "@/store";@@ -52,7 +52,6 @@ import { TabContext, UIEditorTabType, UNKNOWN_ID } from "@/types";const editorStore = useUIEditorStore();const tableStore = useTableStore();-const dialog = useDialog();const tabsContainerRef = ref();const tabList = computed(() => {return Array.from(editorStore.tabState.tabMap.values());@@ -105,7 +104,7 @@ const getTabName = (tab: TabContext) => {);return `${database?.name || "unknown database"}`;} else if (tab.type === UIEditorTabType.TabForTable) {- return `${tab.tableCache.name}`;+ return `${tab.table.name}`;} else {// Should never reach here.return "unknown structure";@@ -117,24 +116,7 @@ const handleSelectTab = (tab: TabContext) => {};const handleCloseTab = (tab: TabContext) => {- if (tab.type === UIEditorTabType.TabForDatabase) {- editorStore.closeTab(tab.id);- } else if (tab.type === UIEditorTabType.TabForTable) {- if (isEqual(tab.tableCache, tab.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);- },- });- }- }+ editorStore.closeTab(tab.id);};</script>diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex f9cd1ab23a..96587c0771 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -1398,17 +1398,16 @@"use-tips": "Click a database/table to start.","preview-issue": "Preview issue","sync-sql-from-ui-editor": "Sync SQL from UI Editor",- "list": "List","raw-sql": "Raw SQL","actions": {"create-table": "New table",+ "rename": "Rename","drop-table": "Drop table",- "drop": "Drop","restore": "Restore","add-column": "Add column","drop-column": "Drop column","sql-preview": "SQL Preview",- "discard-changes": "Discard Changes",+ "reset": "Reset","save": "Save"},"database": {@@ -1419,11 +1418,11 @@"collation": "Collation","comment": "Comment"},- "tables": "Tables",+ "table-list": "Table List","table": {"name": "Table Name"},- "columns": "Columns",+ "column-list": "Column List","column": {"name": "Name","type": "Type",diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 7073100949..4b6f2a7fae 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -1398,7 +1398,6 @@"use-tips": "选择需要编辑的数据库或者表","preview-issue": "预览工单","sync-sql-from-ui-editor": "从 UI 编辑器中同步 SQL",- "list": "列表","raw-sql": "SQL 语句","actions": {"create-table": "新建表",@@ -1408,7 +1407,7 @@"add-column": "添加列","drop-column": "删除列","sql-preview": "预览 SQL",- "discard-changes": "撤销更改",+ "reset": "重置","save": "保存"},"database": {@@ -1419,11 +1418,11 @@"collation": "字符排序规则","comment": "注释"},- "tables": "数据表",+ "table-list": "表","table": {"name": "表名"},- "columns": "数据列",+ "column-list": "列","column": {"name": "名称","type": "类型",diff --git a/frontend/src/store/modules/UIEditor.ts b/frontend/src/store/modules/UIEditor.tsindex 319e8e1691..e1c60badd8 100644--- a/frontend/src/store/modules/UIEditor.ts+++ b/frontend/src/store/modules/UIEditor.ts@@ -91,6 +91,16 @@ export const useUIEditorStore = defineStore("UIEditor", {if (tab.type === UIEditorTabType.TabForDatabase) {// Edit database metadata is not allowed.} else if (tab.type === UIEditorTabType.TabForTable) {+ if (tab.tableId === UNKNOWN_ID) {+ return;+ }++ const originTable = useTableStore().getTableByDatabaseIdAndTableId(+ tab.databaseId,+ tab.tableId+ );+ tab.table.name = originTable.name;+ tab.table.columnList = cloneDeep(originTable.columnList);tab.tableCache.name = tab.table.name;tab.tableCache.columnList = cloneDeep(tab.table.columnList);}@@ -122,6 +132,15 @@ export const useUIEditorStore = defineStore("UIEditor", {}this.tabState.tabMap.delete(tabId);},+ getTableTabByTable(table: Table): TableTabContext | undefined {+ const tab = this.tabList.find((item) => {+ if (item.type === UIEditorTabType.TabForTable && item.table === table) {+ return true;+ }+ return false;+ });+ return tab as TableTabContext;+ },async fetchDatabaseList(databaseIdList: DatabaseId[]) {const databaseList: Database[] = [];for (const id of databaseIdList) {@@ -188,16 +207,17 @@ export const useUIEditorStore = defineStore("UIEditor", {const index = this.tableList.findIndex((item) => item === table);if (table.id === UNKNOWN_ID) {this.tableList.splice(index, 1);+ // Close tab for new table.+ const tab = this.tabList.find(+ (tab) =>+ tab.type === UIEditorTabType.TabForTable && tab.table === table+ );+ if (tab) {+ this.closeTab(tab.id);+ }} else {this.droppedTableList.push(table);}-- const tab = this.tabList.find(- (tab) => tab.type === UIEditorTabType.TabForTable && tab.table === table- );- if (tab) {- this.closeTab(tab.id);- }},restoreTable(databaseId: DatabaseId, tableId: TableId, tableName: string) {const index = this.droppedTableList.findIndex(