Skip to content

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

feat: initial schema designer components (#7050)

boojack3b185402ebb0
diff --git a/frontend/src/components/SchemaDesigner/AsidePanel.vue b/frontend/src/components/SchemaDesigner/AsidePanel.vue
new file mode 100644
index 0000000000..3bba344d8a
--- /dev/null
+++ b/frontend/src/components/SchemaDesigner/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/SchemaDesigner/DatabaseTree.vue b/frontend/src/components/SchemaDesigner/DatabaseTree.vue
new file mode 100644
index 0000000000..26c6c4a70c
--- /dev/null
+++ b/frontend/src/components/SchemaDesigner/DatabaseTree.vue
@@ -0,0 +1,430 @@
+<template>
+ <div class="w-full h-full pl-1 pr-2 relative overflow-y-hidden">
+ <div class="w-full sticky top-0 pt-2 h-12 bg-white z-10">
+ <NInput
+ v-model:value="searchPattern"
+ :placeholder="$t('schema-editor.search-database-and-table')"
+ >
+ <template #prefix>
+ <heroicons-outline:search class="w-4 h-auto text-gray-300" />
+ </template>
+ </NInput>
+ </div>
+ <div ref="treeRef" class="schema-editor-database-tree pb-2 h-auto">
+ <NTree
+ :block-line="true"
+ :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"
+ :on-update:selected-keys="handleSelectedKeysChange"
+ />
+ <NDropdown
+ trigger="manual"
+ placement="bottom-start"
+ :show="contextMenu.showDropdown"
+ :options="contextMenuOptions"
+ :x="contextMenu.clientX"
+ :y="contextMenu.clientY"
+ to="body"
+ @select="handleContextMenuDropdownSelect"
+ @clickoutside="handleDropdownClickoutside"
+ />
+ </div>
+ </div>
+
+ <SchemaNameModal
+ v-if="state.schemaNameModalContext !== undefined"
+ :database-id="state.schemaNameModalContext.databaseId"
+ @close="state.schemaNameModalContext = undefined"
+ />
+
+ <TableNameModal
+ v-if="state.tableNameModalContext !== undefined"
+ :schema="state.tableNameModalContext.schema"
+ @close="state.tableNameModalContext = undefined"
+ />
+</template>
+
+<script lang="ts" setup>
+import { escape, isUndefined } from "lodash-es";
+import { TreeOption, NEllipsis, NInput, NDropdown, NTree } from "naive-ui";
+import { computed, onMounted, watch, ref, h, reactive, nextTick } from "vue";
+import { useI18n } from "vue-i18n";
+import scrollIntoView from "scroll-into-view-if-needed";
+import SchemaIcon from "~icons/heroicons-outline/view-columns";
+import TableIcon from "~icons/heroicons-outline/table-cells";
+import EllipsisIcon from "~icons/heroicons-solid/ellipsis-horizontal";
+
+import { generateUniqueTabId } from "@/store";
+import { getHighlightHTMLByKeyWords, isDescendantOf } from "@/utils";
+import SchemaNameModal from "./Modals/SchemaNameModal.vue";
+import TableNameModal from "./Modals/TableNameModal.vue";
+import { Engine } from "@/types/proto/v1/common";
+import { useSchemaDesignerContext, SchemaDesignerTabType } from "./common";
+
+interface BaseTreeNode extends TreeOption {
+ key: string;
+ label: string;
+ isLeaf: boolean;
+ children?: TreeNode[];
+}
+
+interface TreeNodeForSchema extends BaseTreeNode {
+ type: "schema";
+ schema: string;
+}
+
+interface TreeNodeForTable extends BaseTreeNode {
+ type: "table";
+ schema: string;
+ table: string;
+}
+
+type TreeNode = TreeNodeForSchema | TreeNodeForTable;
+
+interface TreeContextMenu {
+ showDropdown: boolean;
+ clientX: number;
+ clientY: number;
+ treeNode?: TreeNode;
+}
+
+interface LocalState {
+ shouldRelocateTreeNode: boolean;
+ schemaNameModalContext?: {
+ databaseId: string;
+ };
+ tableNameModalContext?: {
+ schema: string;
+ };
+}
+
+const { t } = useI18n();
+const {
+ engine,
+ metadata,
+ tabState,
+ addTab,
+ getCurrentTab,
+ dropSchema,
+ dropTable,
+} = useSchemaDesignerContext();
+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 schemaList = computed(() => Array.from(metadata.value.schemas));
+const tableList = computed(() =>
+ schemaList.value.map((schema) => schema.tables).flat()
+);
+const contextMenuOptions = computed(() => {
+ const treeNode = contextMenu.treeNode;
+ if (isUndefined(treeNode)) {
+ return [];
+ }
+
+ if (treeNode.type === "schema") {
+ const options = [];
+ if (engine === Engine.POSTGRES) {
+ const schema = schemaList.value.find(
+ (schema) => schema.name === treeNode.schema
+ );
+ if (!schema) {
+ return [];
+ }
+
+ options.push({
+ key: "create-table",
+ label: t("schema-editor.actions.create-table"),
+ });
+ options.push({
+ key: "drop-schema",
+ label: t("schema-editor.actions.drop-schema"),
+ });
+ }
+ return options;
+ } else if (treeNode.type === "table") {
+ const schema = schemaList.value.find(
+ (schema) => schema.name === treeNode.schema
+ );
+ if (!schema) {
+ return [];
+ }
+
+ const table = schema.tables.find((table) => table.name === treeNode.table);
+ if (!table) {
+ return [];
+ }
+
+ const options = [];
+ options.push({
+ key: "drop",
+ label: t("schema-editor.actions.drop-table"),
+ });
+ return options;
+ }
+
+ return [];
+});
+
+onMounted(async () => {
+ const treeNodeList: TreeNode[] = [];
+ if (engine === Engine.MYSQL) {
+ for (const table of tableList.value) {
+ const tableTreeNode: TreeNodeForTable = {
+ type: "table",
+ key: `t-${table.name}`,
+ label: table.name,
+ isLeaf: true,
+ schema: "",
+ table: table.name,
+ };
+ treeNodeList.push(tableTreeNode);
+ }
+ } else {
+ for (const schema of schemaList.value) {
+ const schemaTreeNode: TreeNodeForSchema = {
+ type: "schema",
+ key: `s-${schema.name}`,
+ label: schema.name,
+ isLeaf: false,
+ schema: schema.name,
+ };
+ treeNodeList.push(schemaTreeNode);
+ for (const table of schema.tables) {
+ const tableTreeNode: TreeNodeForTable = {
+ type: "table",
+ key: `t-${schema.name}-${table.name}`,
+ label: table.name,
+ isLeaf: true,
+ schema: schema.name,
+ table: table.name,
+ };
+ schemaTreeNode.children?.push(tableTreeNode);
+ }
+ }
+ }
+
+ treeDataRef.value = treeNodeList;
+});
+
+watch(
+ () => tabState.value.currentTabId,
+ () => {
+ const currentTab = getCurrentTab();
+ if (!currentTab) {
+ selectedKeysRef.value = [];
+ return;
+ }
+
+ if (currentTab.type === SchemaDesignerTabType.TabForTable) {
+ const schemaTreeNodeKey = `s-${currentTab.schema}`;
+ if (!expandedKeysRef.value.includes(schemaTreeNodeKey)) {
+ expandedKeysRef.value.push(schemaTreeNodeKey);
+ }
+ const tableTreeNodeKey = `t-${currentTab.schema}-${currentTab.table}`;
+ selectedKeysRef.value = [tableTreeNodeKey];
+ }
+
+ if (state.shouldRelocateTreeNode) {
+ nextTick(() => {
+ const element = treeRef.value?.querySelector(".n-tree-node--selected");
+ if (element) {
+ scrollIntoView(element, {
+ scrollMode: "if-needed",
+ });
+ }
+ });
+ }
+ }
+);
+
+// Render prefix icons before label text.
+const renderPrefix = ({ option: treeNode }: { option: 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: treeNode }: { option: TreeNode }) => {
+ const additionalClassList: string[] = ["select-none"];
+
+ return h(
+ NEllipsis,
+ {
+ class: additionalClassList.join(" "),
+ },
+ () => [
+ h("span", {
+ innerHTML: getHighlightHTMLByKeyWords(
+ escape(treeNode.label),
+ escape(searchPattern.value)
+ ),
+ }),
+ ]
+ );
+};
+
+// Render a 'menu' icon in the right of the node
+const renderSuffix = ({ option: treeNode }: { option: TreeNode }) => {
+ const icon = h(EllipsisIcon, {
+ class: "w-4 h-auto text-gray-600",
+ onClick: (e) => {
+ handleShowDropdown(e, treeNode);
+ },
+ });
+ if (treeNode.type === "schema") {
+ if (engine === 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];
+};
+
+// Set event handler to tree nodes.
+const nodeProps = ({ option: treeNode }: { option: 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")) {
+ state.shouldRelocateTreeNode = false;
+
+ if (treeNode.type === "table") {
+ addTab({
+ id: generateUniqueTabId(),
+ type: SchemaDesignerTabType.TabForTable,
+ schema: treeNode.schema,
+ table: treeNode.table,
+ });
+ }
+
+ nextTick(() => {
+ if (treeNode.type === "table") {
+ selectedKeysRef.value = [
+ `t-${treeNode.databaseId}-${treeNode.tableId}`,
+ ];
+ }
+ 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 === "schema") {
+ if (key === "create-table") {
+ state.tableNameModalContext = {
+ schema: treeNode.schema,
+ };
+ } else if (key === "drop-schema") {
+ dropSchema(treeNode.schema);
+ }
+ } else if (treeNode?.type === "table") {
+ if (key === "drop") {
+ dropTable(treeNode.schema, treeNode.table);
+ }
+ }
+ 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>
+.schema-editor-database-tree .n-tree-node-wrapper {
+ @apply !py-px;
+}
+.schema-editor-database-tree .n-tree-node-content__prefix {
+ @apply shrink-0 !mr-1;
+}
+.schema-editor-database-tree .n-tree-node-content__text {
+ @apply truncate mr-1;
+}
+.schema-editor-database-tree .n-tree-node-content__suffix {
+ @apply rounded-sm !hidden hover:opacity-80;
+}
+.schema-editor-database-tree
+ .n-tree-node-wrapper:hover
+ .n-tree-node-content__suffix {
+ @apply !flex;
+}
+.schema-editor-database-tree
+ .n-tree-node-wrapper
+ .n-tree-node--selected
+ .n-tree-node-content__suffix {
+ @apply !flex;
+}
+.schema-editor-database-tree .n-tree-node-switcher {
+ @apply px-0 !w-4 !h-7;
+}
+</style>
+
+<style scoped>
+.schema-editor-database-tree {
+ @apply overflow-y-auto;
+ max-height: calc(100% - 48px);
+}
+</style>
diff --git a/frontend/src/components/SchemaDesigner/EmptyTips.vue b/frontend/src/components/SchemaDesigner/EmptyTips.vue
new file mode 100644
index 0000000000..b74e12488c
--- /dev/null
+++ b/frontend/src/components/SchemaDesigner/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" />
+ {{ $t("schema-editor.use-tips") }}
+ </div>
+</template>
diff --git a/frontend/src/components/SchemaDesigner/Modals/ActionConfirmModal.vue b/frontend/src/components/SchemaDesigner/Modals/ActionConfirmModal.vue
new file mode 100644
index 0000000000..b68f82a26e
--- /dev/null
+++ b/frontend/src/components/SchemaDesigner/Modals/ActionConfirmModal.vue
@@ -0,0 +1,49 @@
+<template>
+ <BBModal
+ :title="props.title"
+ class="shadow-inner outline outline-gray-200"
+ @close="dismissModal"
+ >
+ <div class="w-80 mb-6">
+ <p>{{ props.description }}</p>
+ </div>
+ <div class="w-full flex items-center justify-end mt-2 space-x-3 pr-1 pb-1">
+ <button type="button" class="btn-cancel" @click="dismissModal">
+ {{ $t("common.cancel") }}
+ </button>
+ <button :class="`btn-${props.style}`" @click="handleConfirmButtonClick">
+ {{ $t("common.confirm") }}
+ </button>
+ </div>
+ </BBModal>
+</template>
+
+<script lang="ts" setup>
+const props = defineProps({
+ title: {
+ type: String,
+ default: "",
+ },
+ description: {
+ type: String,
+ default: "",
+ },
+ style: {
+ type: String,
+ default: "primary",
+ },
+});
+
+const emit = defineEmits<{
+ (event: "close"): void;
+ (event: "confirm"): void;
+}>();
+
+const handleConfirmButtonClick = async () => {
+ emit("confirm");
+};
+
+const dismissModal = () => {
+ emit("close");
+};
+</script>
diff --git a/frontend/src/components/SchemaDesigner/Modals/EditColumnForeignKeyModal.vue b/frontend/src/components/SchemaDesigner/Modals/EditColumnForeignKeyModal.vue
new file mode 100644
index 0000000000..ad3cb3773b
--- /dev/null
+++ b/frontend/src/components/SchemaDesigner/Modals/EditColumnForeignKeyModal.vue
@@ -0,0 +1,259 @@
+<template>
+ <BBModal
+ :title="$t('schema-editor.edit-foreign-key')"
+ class="shadow-inner outline outline-gray-200"
+ @close="dismissModal"
+ >
+ <div v-if="shouldShowSchemaSelector" class="w-72">
+ <p class="mb-2">{{ $t("schema-editor.select-reference-schema") }}</p>
+ <BBSelect
+ :selected-item="selectedSchema"
+ :item-list="schemas"
+ :placeholder="$t('schema-editor.schema.select')"
+ :show-prefix-item="true"
+ @select-item="(schema: SchemaMetadata) => state.referencedSchema = schema.name"
+ >
+ <template #menuItem="{ item }">
+ {{ item.name }}
+ </template>
+ </BBSelect>
+ </div>
+ <div class="w-72">
+ <p class="mt-4 mb-2">{{ $t("schema-editor.select-reference-table") }}</p>
+ <BBSelect
+ :selected-item="selectedTable"
+ :item-list="tableList"
+ :placeholder="$t('schema-editor.table.select')"
+ :show-prefix-item="true"
+ @select-item="(table: TableMetadata) => state.referencedTable = table.name"
+ >
+ <template #menuItem="{ item }">
+ {{ item.name }}
+ </template>
+ </BBSelect>
+ </div>
+ <div class="w-72">
+ <p class="mt-4 mb-2">{{ $t("schema-editor.select-reference-column") }}</p>
+ <BBSelect
+ :selected-item="selectedColumn"
+ :item-list="columnList"
+ :placeholder="$t('schema-editor.column.select')"
+ :show-prefix-item="true"
+ @select-item="(column: ColumnMetadata) => state.referencedColumn = column.name"
+ >
+ <template #menuItem="{ item }">
+ {{ item.name }}
+ </template>
+ </BBSelect>
+ </div>
+ <div
+ class="w-full flex items-center justify-between mt-6 space-x-2 pr-1 pb-1"
+ >
+ <div class="flex items-center justify-start">
+ <button
+ v-if="foreignKey !== undefined"
+ type="button"
+ class="btn-danger"
+ @click="handleRemoveFKButtonClick"
+ >
+ Remove
+ </button>
+ </div>
+ <div class="flex items-center justify-end space-x-2">
+ <button type="button" class="btn-normal" @click="dismissModal">
+ {{ $t("common.cancel") }}
+ </button>
+ <button class="btn-primary" @click="handleConfirmButtonClick">
+ {{ $t("common.save") }}
+ </button>
+ </div>
+ </div>
+ </BBModal>
+</template>
+
+<script lang="ts" setup>
+import { isUndefined } from "lodash-es";
+import { computed, onMounted, reactive, watch } from "vue";
+import { BBModal, BBSelect } from "@/bbkit";
+import { Engine } from "@/types/proto/v1/common";
+import { useSchemaDesignerContext } from "../common";
+import {
+ ColumnMetadata,
+ ForeignKeyMetadata,
+ SchemaMetadata,
+ TableMetadata,
+} from "@/types/proto/v1/database_service";
+
+interface LocalState {
+ referencedSchema?: string;
+ referencedTable?: string;
+ referencedColumn?: string;
+}
+
+const props = defineProps({
+ schema: {
+ type: String,
+ default: "",
+ },
+ table: {
+ type: String,
+ default: "",
+ },
+ column: {
+ type: String,
+ default: "",
+ },
+});
+
+const emit = defineEmits<{
+ (event: "close"): void;
+}>();
+
+const { engine, metadata } = useSchemaDesignerContext();
+const schemas = computed(() => metadata.value.schemas);
+const state = reactive<LocalState>({
+ referencedSchema: props.schema,
+});
+
+const schema = computed(() => {
+ return schemas.value.find((item) => item.name === props.schema);
+});
+
+const table = computed(() => {
+ return schema.value?.tables.find((item) => item.name === props.table);
+});
+
+const propsColumn = computed(() => {
+ return table.value?.columns.find((item) => item.name === props.column);
+});
+
+const foreignKeyList = computed(() => {
+ return table.value?.foreignKeys || [];
+});
+
+const shouldShowSchemaSelector = computed(() => {
+ return engine === Engine.POSTGRES;
+});
+
+const selectedSchema = computed(() => {
+ return schemas.value.find((schema) => schema.name === state.referencedSchema);
+});
+
+const tableList = computed(() => {
+ return selectedSchema.value?.tables || [];
+});
+
+const selectedTable = computed(() => {
+ return tableList.value.find(
+ (table: TableMetadata) => table.name === state.referencedTable
+ );
+});
+
+const columnList = computed(() => {
+ if (!selectedTable.value) {
+ return [];
+ }
+
+ return selectedTable.value.columns.filter(
+ (column) =>
+ column.name !== props.column &&
+ column.type.toUpperCase() === propsColumn.value?.type.toUpperCase()
+ );
+});
+
+const selectedColumn = computed(() => {
+ return columnList.value.find(
+ (column) => column.name === state.referencedColumn
+ );
+});
+
+const foreignKey = computed(() => {
+ for (const fk of foreignKeyList.value) {
+ const foundIndex = fk.columns.findIndex(
+ (column) => column === props.column
+ );
+ if (foundIndex > -1) {
+ return fk;
+ }
+ }
+ return undefined;
+});
+
+onMounted(() => {
+ if (foreignKey.value) {
+ const foundIndex = foreignKey.value.columns.findIndex(
+ (column) => column === props.column
+ );
+ if (foundIndex > -1) {
+ state.referencedSchema = foreignKey.value.referencedSchema;
+ state.referencedTable = foreignKey.value.referencedTable;
+ state.referencedColumn = foreignKey.value.referencedColumns[foundIndex];
+ }
+ }
+});
+
+watch(
+ () => state.referencedTable,
+ () => {
+ const found = columnList.value.find(
+ (column) => column.name === state.referencedColumn
+ );
+ if (!found) {
+ state.referencedColumn = undefined;
+ }
+ }
+);
+
+const handleRemoveFKButtonClick = async () => {
+ if (isUndefined(foreignKey.value)) {
+ return;
+ }
+
+ const index = foreignKey.value.columns.findIndex(
+ (column) => column === propsColumn.value?.name
+ );
+ if (index > -1) {
+ foreignKey.value.referencedColumns.splice(index, 1);
+ foreignKey.value.columns.splice(index, 1);
+ dismissModal();
+ }
+};
+
+const handleConfirmButtonClick = async () => {
+ if (
+ isUndefined(state.referencedSchema) ||
+ isUndefined(state.referencedTable) ||
+ isUndefined(state.referencedColumn)
+ ) {
+ return;
+ }
+
+ const column = propsColumn.value as ColumnMetadata;
+ if (isUndefined(foreignKey.value)) {
+ table.value?.foreignKeys.push(
+ ForeignKeyMetadata.fromPartial({
+ columns: [column.name],
+ referencedSchema: state.referencedSchema,
+ referencedTable: state.referencedTable,
+ referencedColumns: [state.referencedColumn],
+ })
+ );
+ } else {
+ const index = foreignKey.value.columns.findIndex(
+ (item) => item === column.name
+ );
+ if (index >= 0) {
+ foreignKey.value.referencedColumns[index] = state.referencedColumn;
+ foreignKey.value.columns[index] = column.name;
+ } else {
+ foreignKey.value.referencedColumns.push(state.referencedColumn);
+ foreignKey.value.columns.push(column.name);
+ }
+ }
+ dismissModal();
+};
+
+const dismissModal = () => {
+ emit("close");
+};
+</script>
diff --git a/frontend/src/components/SchemaDesigner/Modals/SchemaNameModal.vue b/frontend/src/components/SchemaDesigner/Modals/SchemaNameModal.vue
new file mode 100644
index 0000000000..841f8790c4
--- /dev/null
+++ b/frontend/src/components/SchemaDesigner/Modals/SchemaNameModal.vue
@@ -0,0 +1,75 @@
+<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
+ class="my-2 w-full"
+ :required="true"
+ :focus-on-mount="true"
+ :value="state.schemaName"
+ @input="handleSchemaNameChange"
+ />
+ </div>
+ <div class="w-full flex items-center justify-end mt-2 space-x-3 pr-1 pb-1">
+ <button type="button" class="btn-normal" @click="dismissModal">
+ {{ $t("common.cancel") }}
+ </button>
+ <button class="btn-primary" @click="handleConfirmButtonClick">
+ {{ $t("common.create") }}
+ </button>
+ </div>
+ </BBModal>
+</template>
+
+<script lang="ts" setup>
+import { reactive } from "vue";
+import { useI18n } from "vue-i18n";
+import { useNotificationStore } from "@/store";
+import { SchemaMetadata } from "@/types/proto/store/database";
+import { useSchemaDesignerContext } from "../common";
+
+const schemaNameFieldRegexp = /^\S+$/;
+
+interface LocalState {
+ schemaName: string;
+}
+
+const emit = defineEmits<{
+ (event: "close"): void;
+}>();
+
+const { t } = useI18n();
+const { metadata } = useSchemaDesignerContext();
+const notificationStore = useNotificationStore();
+const state = reactive<LocalState>({
+ schemaName: "",
+});
+
+const handleSchemaNameChange = (event: Event) => {
+ state.schemaName = (event.target as HTMLInputElement).value;
+};
+
+const handleConfirmButtonClick = async () => {
+ if (!schemaNameFieldRegexp.test(state.schemaName)) {
+ notificationStore.pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("schema-editor.message.invalid-schema-name"),
+ });
+ return;
+ }
+
+ const schema = SchemaMetadata.fromPartial({});
+ metadata.value.schemas.push(schema);
+ // TODO(steven): Open the schema tab.
+ dismissModal();
+};
+
+const dismissModal = () => {
+ emit("close");
+};
+</script>
diff --git a/frontend/src/components/SchemaDesigner/Modals/TableNameModal.vue b/frontend/src/components/SchemaDesigner/Modals/TableNameModal.vue
new file mode 100644
index 0000000000..3ecada3722
--- /dev/null
+++ b/frontend/src/components/SchemaDesigner/Modals/TableNameModal.vue
@@ -0,0 +1,105 @@
+<template>
+ <BBModal
+ :title="$t('schema-editor.actions.create-table')"
+ class="shadow-inner outline outline-gray-200"
+ @close="dismissModal"
+ >
+ <div class="w-72">
+ <p>{{ $t("schema-editor.table.name") }}</p>
+ <BBTextField
+ class="my-2 w-full"
+ :required="true"
+ :focus-on-mount="true"
+ :value="state.tableName"
+ @input="handleTableNameChange"
+ />
+ </div>
+ <div class="w-full flex items-center justify-end mt-2 space-x-3 pr-1 pb-1">
+ <button type="button" class="btn-normal" @click="dismissModal">
+ {{ $t("common.cancel") }}
+ </button>
+ <button class="btn-primary" @click="handleConfirmButtonClick">
+ {{ $t("common.create") }}
+ </button>
+ </div>
+ </BBModal>
+</template>
+
+<script lang="ts" setup>
+import { reactive } from "vue";
+import { useI18n } from "vue-i18n";
+import { useNotificationStore } from "@/store";
+import { ColumnMetadata, TableMetadata } from "@/types/proto/store/database";
+import { Engine } from "@/types/proto/v1/common";
+import { useSchemaDesignerContext } from "../common";
+
+const tableNameFieldRegexp = /^\S+$/;
+
+interface LocalState {
+ tableName: string;
+}
+
+const props = defineProps({
+ schema: {
+ type: String,
+ default: "",
+ },
+});
+
+const emit = defineEmits<{
+ (event: "close"): void;
+}>();
+
+const { t } = useI18n();
+const { engine, metadata } = useSchemaDesignerContext();
+const notificationStore = useNotificationStore();
+const state = reactive<LocalState>({
+ tableName: "",
+});
+
+const handleTableNameChange = (event: Event) => {
+ state.tableName = (event.target as HTMLInputElement).value;
+};
+
+const handleConfirmButtonClick = async () => {
+ if (!tableNameFieldRegexp.test(state.tableName)) {
+ notificationStore.pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("schema-editor.message.invalid-table-name"),
+ });
+ return;
+ }
+
+ const schema = metadata.value.schemas.find(
+ (schema) => schema.name === props.schema
+ );
+ if (!schema) {
+ notificationStore.pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("schema-editor.message.schema-not-found"),
+ });
+ return;
+ }
+
+ const table = TableMetadata.fromPartial({});
+ table.name = state.tableName;
+ const column = ColumnMetadata.fromPartial({});
+ column.name = "id";
+ if (engine === Engine.POSTGRES) {
+ column.type = "INTEGER";
+ } else {
+ column.type = "INT";
+ }
+ column.comment = "ID";
+ table.columns.push(column);
+ schema.tables.push(table);
+
+ dismissModal();
+};
+
+const dismissModal = () => {
+ emit("close");
+};
+</script>
diff --git a/frontend/src/components/SchemaDesigner/Panels/TableEditor.vue b/frontend/src/components/SchemaDesigner/Panels/TableEditor.vue
new file mode 100644
index 0000000000..62b739f767
--- /dev/null
+++ b/frontend/src/components/SchemaDesigner/Panels/TableEditor.vue
@@ -0,0 +1,453 @@
+<template>
+ <div class="flex flex-col w-full h-full overflow-y-auto">
+ <div class="py-2 w-full flex flex-row justify-between items-center">
+ <div>
+ <div
+ v-if="state.selectedSubtab === 'column-list'"
+ class="w-full flex justify-between items-center space-x-2"
+ >
+ <button
+ class="flex flex-row justify-center items-center border px-3 py-1 leading-6 text-sm text-gray-700 rounded cursor-pointer hover:opacity-80 disabled:cursor-not-allowed disabled:opacity-60"
+ @click="handleAddColumn"
+ >
+ <heroicons-outline:plus class="w-4 h-auto mr-1 text-gray-400" />
+ {{ $t("schema-editor.actions.add-column") }}
+ </button>
+ </div>
+ </div>
+ <div class="flex justify-end items-center">
+ <NInput
+ v-if="state.selectedSubtab === 'column-list'"
+ v-model:value="searchPattern"
+ class="!w-48 mr-3"
+ :placeholder="$t('schema-editor.search-column')"
+ >
+ <template #prefix>
+ <heroicons-outline:search class="w-4 h-auto text-gray-300" />
+ </template>
+ </NInput>
+ <div
+ class="flex flex-row justify-end items-center bg-gray-100 p-1 rounded"
+ >
+ <button
+ class="px-2 leading-7 text-sm text-gray-500 cursor-pointer select-none rounded flex justify-center items-center"
+ :class="
+ state.selectedSubtab === 'column-list' &&
+ 'bg-gray-200 text-gray-800'
+ "
+ @click="handleChangeTab('column-list')"
+ >
+ <heroicons-outline:queue-list class="inline w-4 h-auto mr-1" />
+ {{ $t("schema-editor.columns") }}
+ </button>
+ <button
+ class="px-2 leading-7 text-sm text-gray-500 cursor-pointer select-none rounded flex justify-center items-center"
+ :class="
+ state.selectedSubtab === 'raw-sql' && 'bg-gray-200 text-gray-800'
+ "
+ @click="handleChangeTab('raw-sql')"
+ >
+ <heroicons-outline:clipboard class="inline w-4 h-auto mr-1" />
+ {{ $t("schema-editor.raw-sql") }}
+ </button>
+ </div>
+ </div>
+ </div>
+
+ <template v-if="state.selectedSubtab === 'column-list'">
+ <!-- column table -->
+ <div
+ id="table-editor-container"
+ ref="tableEditorContainerRef"
+ class="w-full h-auto grid auto-rows-auto border-y relative overflow-y-auto"
+ >
+ <!-- column table header -->
+ <div
+ class="sticky top-0 z-10 grid grid-cols-[repeat(4,_minmax(0,_1fr))_repeat(2,_96px)_minmax(0,_1fr)_32px] w-full text-sm leading-6 select-none bg-gray-50 text-gray-400"
+ :class="shownColumnList.length > 0 && 'border-b'"
+ >
+ <span
+ v-for="header in columnHeaderList"
+ :key="header.key"
+ class="table-header-item-container"
+ >{{ header.label }}</span
+ >
+ <span></span>
+ </div>
+ <!-- column table body -->
+ <div class="w-full">
+ <div
+ v-for="(column, index) in shownColumnList"
+ :key="`${column.name}-${index}`"
+ class="grid grid-cols-[repeat(4,_minmax(0,_1fr))_repeat(2,_96px)_minmax(0,_1fr)_32px] gr text-sm even:bg-gray-50"
+ :class="[getColumnComputedClassList(column)]"
+ >
+ <div class="table-body-item-container">
+ <input
+ v-model="column.name"
+ placeholder="column name"
+ class="column-field-input column-name-input"
+ type="text"
+ />
+ </div>
+ <div
+ class="table-body-item-container flex flex-row justify-between items-center"
+ >
+ <input
+ v-model="column.type"
+ placeholder="column type"
+ class="column-field-input column-type-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 flex flex-row justify-between items-center"
+ >
+ <input
+ v-model="column.default"
+ :placeholder="column.default === undefined ? 'NULL' : 'EMPTY'"
+ class="column-field-input !pr-8"
+ type="text"
+ />
+ <NDropdown
+ trigger="click"
+ :options="dataDefaultOptions"
+ @select="(defaultString:string)=>handleColumnDefaultFieldChange(column, defaultString)"
+ >
+ <button class="absolute right-5">
+ <heroicons-solid:chevron-up-down
+ class="w-4 h-auto text-gray-400"
+ />
+ </button>
+ </NDropdown>
+ </div>
+ <div class="table-body-item-container">
+ <input
+ v-model="column.comment"
+ placeholder="comment"
+ class="column-field-input"
+ type="text"
+ />
+ </div>
+ <div
+ class="table-body-item-container flex justify-start items-center"
+ >
+ <BBCheckbox
+ class="ml-3"
+ :value="!column.nullable"
+ :disabled="isColumnPrimaryKey(column)"
+ @toggle="(value) => (column.nullable = !value)"
+ />
+ </div>
+ <div
+ class="table-body-item-container flex justify-start items-center"
+ >
+ <BBCheckbox
+ class="ml-3"
+ :value="isColumnPrimaryKey(column)"
+ @toggle="(value) => setColumnPrimaryKey(column, value)"
+ />
+ </div>
+ <div
+ class="table-body-item-container foreign-key-field flex justify-start items-center"
+ >
+ <span
+ v-if="checkColumnHasForeignKey(column)"
+ class="column-field-text cursor-pointer !w-auto hover:opacity-80"
+ >
+ {{ getReferencedForeignKeyName(column) }}
+ </span>
+ <span
+ v-else
+ class="column-field-text italic text-gray-400 !w-auto"
+ >EMPTY</span
+ >
+ <button
+ class="foreign-key-edit-button hidden cursor-pointer hover:opacity-80 disabled:cursor-not-allowed disabled:opacity-60"
+ @click="handleEditColumnForeignKey(column)"
+ >
+ <heroicons:pencil-square class="w-4 h-auto text-gray-400" />
+ </button>
+ </div>
+ <div class="w-full flex justify-start items-center">
+ <n-tooltip trigger="hover">
+ <template #trigger>
+ <button
+ class="text-gray-500 cursor-pointer hover:opacity-80 disabled:cursor-not-allowed disabled:opacity-60"
+ @click="handleDropColumn(column)"
+ >
+ <heroicons:trash class="w-4 h-auto" />
+ </button>
+ </template>
+ <span>{{ $t("schema-editor.actions.drop-column") }}</span>
+ </n-tooltip>
+ </div>
+ </div>
+ </div>
+ </div>
+ </template>
+ <div
+ v-else-if="state.selectedSubtab === 'raw-sql'"
+ class="w-full h-full overflow-y-auto"
+ >
+ <div
+ v-if="state.isFetchingDDL"
+ class="w-full h-full min-h-[64px] flex justify-center items-center"
+ >
+ <BBSpin />
+ </div>
+ <template v-else>
+ <HighlightCodeBlock
+ v-if="state.statement !== ''"
+ class="text-sm px-3 py-2 whitespace-pre-wrap break-all"
+ language="sql"
+ :code="state.statement"
+ ></HighlightCodeBlock>
+ <div v-else class="flex px-3 py-2 italic text-sm text-gray-600">
+ {{ $t("schema-editor.nothing-changed") }}
+ </div>
+ </template>
+ </div>
+ </div>
+
+ <EditColumnForeignKeyModal
+ v-if="state.showEditColumnForeignKeyModal && editForeignKeyColumn"
+ :schema="schema.name"
+ :table="table.name"
+ :column="editForeignKeyColumn.name"
+ @close="state.showEditColumnForeignKeyModal = false"
+ />
+</template>
+
+<script lang="ts" setup>
+import { isUndefined } from "lodash-es";
+import { computed, nextTick, reactive, ref } from "vue";
+import { useI18n } from "vue-i18n";
+import { NDropdown } from "naive-ui";
+import { ColumnMetadata } from "@/types/proto/store/database";
+import { getDataTypeSuggestionList } from "@/utils";
+import { BBCheckbox, BBSpin } from "@/bbkit";
+import HighlightCodeBlock from "@/components/HighlightCodeBlock";
+import EditColumnForeignKeyModal from "../Modals/EditColumnForeignKeyModal.vue";
+import { Engine } from "@/types/proto/v1/common";
+import { TableTabContext, useSchemaDesignerContext } from "../common";
+import {
+ SchemaMetadata,
+ TableMetadata,
+} from "@/types/proto/v1/database_service";
+
+type SubtabType = "column-list" | "raw-sql";
+
+interface LocalState {
+ selectedSubtab: SubtabType;
+ isFetchingDDL: boolean;
+ statement: string;
+ showEditColumnForeignKeyModal: boolean;
+}
+
+const { t } = useI18n();
+const { engine, metadata, getCurrentTab } = useSchemaDesignerContext();
+const currentTab = computed(() => getCurrentTab() as TableTabContext);
+const state = reactive<LocalState>({
+ selectedSubtab:
+ (currentTab.value.selectedSubtab as SubtabType) || "column-list",
+ isFetchingDDL: false,
+ statement: "",
+ showEditColumnForeignKeyModal: false,
+});
+
+const schema = computed(() => {
+ return metadata.value.schemas.find(
+ (schema) => schema.name === currentTab.value.schema
+ ) as SchemaMetadata;
+});
+const table = computed(() => {
+ return schema.value.tables.find(
+ (table) => table.name === currentTab.value.table
+ ) as TableMetadata;
+});
+const foreignKeyList = computed(() => {
+ return table.value.foreignKeys;
+});
+
+const searchPattern = ref("");
+const tableEditorContainerRef = ref<HTMLDivElement>();
+const editForeignKeyColumn = ref<ColumnMetadata>();
+
+const shownColumnList = computed(() => {
+ return table.value.columns.filter((column) =>
+ column.name.includes(searchPattern.value.trim())
+ );
+});
+
+const columnHeaderList = computed(() => {
+ return [
+ {
+ key: "name",
+ label: t("schema-editor.column.name"),
+ },
+ {
+ key: "type",
+ label: t("schema-editor.column.type"),
+ },
+ {
+ key: "default",
+ label: t("schema-editor.column.default"),
+ },
+ {
+ key: "comment",
+ label: t("schema-editor.column.comment"),
+ },
+ {
+ key: "nullable",
+ label: t("schema-editor.column.not-null"),
+ },
+ {
+ key: "primary",
+ label: t("schema-editor.column.primary"),
+ },
+ {
+ key: "foreign_key",
+ label: "Foreign Key",
+ },
+ ];
+});
+
+const dataDefaultOptions = [
+ {
+ label: "NULL",
+ key: "NULL",
+ },
+ {
+ label: "EMPTY",
+ key: "EMPTY",
+ },
+];
+
+const dataTypeOptions = computed(() => {
+ return getDataTypeSuggestionList(engine).map((dataType) => {
+ return {
+ label: dataType,
+ key: dataType,
+ };
+ });
+});
+
+const getColumnComputedClassList = (column: ColumnMetadata) => {
+ return [`column-${column.name}`];
+};
+
+const isColumnPrimaryKey = (column: ColumnMetadata): boolean => {
+ return (
+ table.value.indexes.find(
+ (index) => index.primary && index.expressions.includes(column.name)
+ ) !== undefined
+ );
+};
+
+const checkColumnHasForeignKey = (column: ColumnMetadata): boolean => {
+ return foreignKeyList.value
+ .map((fk) => fk.columns)
+ .flat()
+ .flat()
+ .includes(column.name);
+};
+
+const getReferencedForeignKeyName = (column: ColumnMetadata) => {
+ if (!checkColumnHasForeignKey(column)) {
+ return;
+ }
+ const fk = foreignKeyList.value.find(
+ (fk) =>
+ fk.columns.find((columnName) => columnName === column.name) !== undefined
+ );
+ const index = fk?.columns.findIndex(
+ (columnName) => columnName === column.name
+ );
+ if (isUndefined(fk) || isUndefined(index) || index < 0) {
+ return;
+ }
+
+ const referencedSchema = fk.referencedSchema[index];
+ const referencedTable = fk.referencedTable[index];
+ const referencedColumn = fk.referencedSchema[index];
+ if (!referencedTable || !referencedColumn) {
+ return;
+ }
+
+ if (engine === Engine.MYSQL) {
+ return `${referencedTable}(${referencedColumn})`;
+ } else {
+ return `${referencedSchema}.${referencedTable}(${referencedColumn})`;
+ }
+};
+
+const setColumnPrimaryKey = (column: ColumnMetadata, isPrimaryKey: boolean) => {
+ // TODO
+};
+
+const handleChangeTab = (tab: SubtabType) => {
+ state.selectedSubtab = tab;
+};
+
+const handleAddColumn = () => {
+ const column = ColumnMetadata.fromPartial({});
+ table.value.columns.push(column);
+ nextTick(() => {
+ (
+ tableEditorContainerRef.value?.querySelector(
+ `.column-${column.name} .column-name-input`
+ ) as HTMLInputElement
+ )?.focus();
+ });
+};
+
+const handleColumnDefaultFieldChange = (
+ column: ColumnMetadata,
+ defaultString: string
+) => {
+ if (defaultString === "NULL") {
+ column.default = undefined;
+ } else if (defaultString === "EMPTY") {
+ column.default = "";
+ }
+};
+
+const handleEditColumnForeignKey = (column: ColumnMetadata) => {
+ editForeignKeyColumn.value = column;
+ state.showEditColumnForeignKeyModal = true;
+};
+
+const handleDropColumn = (column: ColumnMetadata) => {
+ table.value.columns = table.value.columns.filter((col) => col !== column);
+};
+</script>
+
+<style scoped>
+.table-header-item-container {
+ @apply py-2 px-3;
+}
+.table-body-item-container {
+ @apply w-full h-10 box-border p-px pr-2 relative;
+}
+.column-field-input {
+ @apply w-full pr-1 box-border border-transparent truncate select-none rounded bg-transparent text-sm placeholder:italic placeholder:text-gray-400 focus:bg-white focus:text-black;
+}
+.column-field-text {
+ @apply w-full pl-3 pr-1 box-border border-transparent truncate select-none rounded bg-transparent text-sm placeholder:italic placeholder:text-gray-400 focus:bg-white focus:text-black;
+}
+.foreign-key-field:hover .foreign-key-edit-button {
+ @apply block;
+}
+</style>
diff --git a/frontend/src/components/SchemaDesigner/PrepForm/SchemaDesignTable.vue b/frontend/src/components/SchemaDesigner/PrepForm/SchemaDesignTable.vue
new file mode 100644
index 0000000000..1881259a11
--- /dev/null
+++ b/frontend/src/components/SchemaDesigner/PrepForm/SchemaDesignTable.vue
@@ -0,0 +1,94 @@
+<template>
+ <div ref="wrapper" rule="database-table" v-bind="$attrs">
+ <BBGrid
+ :column-list="COLUMN_LIST"
+ :data-source="schemaDesigns"
+ @click-row="clickSchemaDesign"
+ >
+ <template #item="{ item: schemaDesign }: { item: SchemaDesign }">
+ <div class="bb-grid-cell">
+ {{ schemaDesign.title }}
+ </div>
+ <div class="bb-grid-cell">
+ {{ getFormatedValue(schemaDesign).project }}
+ </div>
+ <div class="bb-grid-cell">
+ {{ getFormatedValue(schemaDesign).engine }}
+ </div>
+ <div class="bb-grid-cell">
+ {{ getFormatedValue(schemaDesign).creator }}
+ </div>
+ <div class="bb-grid-cell">
+ {{ getFormatedValue(schemaDesign).updater }}
+ </div>
+ <div class="bb-grid-cell">
+ <HumanizeTs
+ :ts="(schemaDesign.updateTime?.getTime() ?? 0) / 1000"
+ class="ml-1"
+ />)
+ </div>
+ </template>
+ </BBGrid>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import dayjs from "dayjs";
+import { computed } from "vue";
+import { useI18n } from "vue-i18n";
+import { BBGridColumn } from "@/bbkit";
+import { getProjectAndSchemaDesignSheetId } from "@/store/modules/v1/common";
+import { useProjectV1Store, useUserStore } from "@/store";
+import { SchemaDesign } from "@/types/proto/v1/schema_design_service";
+import { projectV1Name } from "@/utils";
+
+defineProps<{
+ schemaDesigns: SchemaDesign[];
+}>();
+
+const { t } = useI18n();
+const projectV1Store = useProjectV1Store();
+
+const COLUMN_LIST = computed(() => {
+ const columns: BBGridColumn[] = [
+ { title: t("common.name"), width: "1fr" },
+ {
+ title: t("common.project"),
+ width: "1fr",
+ },
+ {
+ title: t("common.engine"),
+ width: "1fr",
+ },
+ { title: t("common.creator"), width: "minmax(auto, 10rem)" },
+ { title: t("common.updater"), width: "minmax(auto, 10rem)" },
+ { title: t("common.updated-at"), width: "minmax(auto, 10rem)" },
+ ];
+
+ return columns;
+});
+
+const getFormatedValue = (schemaDesign: SchemaDesign) => {
+ const [projectName] = getProjectAndSchemaDesignSheetId(schemaDesign.name);
+ const project = projectV1Store.getProjectByName(`projects/${projectName}`);
+
+ return {
+ name: schemaDesign.title,
+ project: projectV1Name(project),
+ engine: schemaDesign.engine,
+ creator:
+ useUserStore().getUserByIdentifier(schemaDesign.creator)?.title ??
+ schemaDesign.creator,
+ updater:
+ useUserStore().getUserByIdentifier(schemaDesign.updater)?.title ??
+ schemaDesign.updater,
+ updated: dayjs
+ .duration((schemaDesign.updateTime ?? new Date()).getTime() - Date.now())
+ .humanize(true),
+ };
+};
+
+const clickSchemaDesign = (schemaDesign: SchemaDesign) => {
+ // TODO
+};
+</script>
diff --git a/frontend/src/components/SchemaDesigner/PrepForm/index.vue b/frontend/src/components/SchemaDesigner/PrepForm/index.vue
new file mode 100644
index 0000000000..8f24d091f3
--- /dev/null
+++ b/frontend/src/components/SchemaDesigner/PrepForm/index.vue
@@ -0,0 +1,21 @@
+<template>
+ <div>
+ <div class="w-full"></div>
+ <SchemaDesignTable :schema-designs="schemaDesignList" />
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { reactive } from "vue";
+import SchemaDesignTable from "./SchemaDesignTable.vue";
+import { useSchemaDesignList } from "@/store/modules/schemaDesign";
+
+interface LocalState {
+ tab: "TABLE" | "VIEW";
+}
+
+const { schemaDesignList } = useSchemaDesignList();
+const _ = reactive<LocalState>({
+ tab: "TABLE",
+});
+</script>
diff --git a/frontend/src/components/SchemaDesigner/TabsContainer.vue b/frontend/src/components/SchemaDesigner/TabsContainer.vue
new file mode 100644
index 0000000000..d728c9da0f
--- /dev/null
+++ b/frontend/src/components/SchemaDesigner/TabsContainer.vue
@@ -0,0 +1,100 @@
+<template>
+ <div
+ ref="tabsContainerRef"
+ class="w-full max-w-full overflow-x-auto bg-gray-100 select-none shrink-0 rounded"
+ >
+ <div class="w-fit flex flex-nowrap">
+ <div
+ v-for="tab in tabList"
+ :key="tab.id"
+ class="relative px-1 pl-2 py-2 rounded w-40 flex flex-row justify-between items-center shrink-0 border border-transparent cursor-pointer"
+ :class="[
+ `tab-${tab.id}`,
+ tab.id === currentTab?.id && 'bg-white border-gray-200',
+ ]"
+ @click="handleSelectTab(tab)"
+ >
+ <div class="flex flex-row justify-start items-center mr-1">
+ <span class="mr-1">
+ <heroicons-outline:table-cells
+ v-if="tab.type === SchemaDesignerTabType.TabForTable"
+ class="rounded w-4 h-auto text-gray-400"
+ />
+ </span>
+ <NEllipsis
+ class="text-sm w-24"
+ :class="getTabComputedClassList(tab)"
+ >{{ getTabName(tab) }}</NEllipsis
+ >
+ </div>
+ <span class="tab-close-button shrink-0 flex">
+ <heroicons-outline:x
+ class="rounded w-4 h-auto text-gray-400 hover:text-gray-600"
+ @click.stop.prevent="handleCloseTab(tab)"
+ />
+ </span>
+ <div
+ v-if="tab.id === currentTab?.id"
+ class="absolute -bottom-px left-0 w-full h-[3px] bg-accent rounded"
+ ></div>
+ </div>
+ </div>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { NEllipsis } from "naive-ui";
+import { computed, nextTick, ref, watch } from "vue";
+import scrollIntoView from "scroll-into-view-if-needed";
+import {
+ useSchemaDesignerContext,
+ TabContext,
+ SchemaDesignerTabType,
+} from "./common";
+
+const { tabState, getCurrentTab } = useSchemaDesignerContext();
+const tabsContainerRef = ref();
+const tabList = computed(() => {
+ return Array.from(tabState.value.tabMap.values());
+});
+const currentTab = computed(() => {
+ return getCurrentTab();
+});
+
+watch(
+ () => currentTab.value,
+ () => {
+ nextTick(() => {
+ const element = tabsContainerRef.value?.querySelector(
+ `.tab-${currentTab.value?.id}`
+ );
+ if (element) {
+ scrollIntoView(element, {
+ scrollMode: "if-needed",
+ });
+ }
+ });
+ }
+);
+
+const getTabComputedClassList = (tab: TabContext) => {
+ return [];
+};
+
+const getTabName = (tab: TabContext) => {
+ if (tab.type === SchemaDesignerTabType.TabForTable) {
+ return tab.table || "";
+ } else {
+ // Should never reach here.
+ return "unknown structure";
+ }
+};
+
+const handleSelectTab = (tab: TabContext) => {
+ tabState.value.currentTabId = tab.id;
+};
+
+const handleCloseTab = (tab: TabContext) => {
+ tabState.value.currentTabId = undefined;
+};
+</script>
diff --git a/frontend/src/components/SchemaDesigner/common/context.ts b/frontend/src/components/SchemaDesigner/common/context.ts
new file mode 100644
index 0000000000..73a8059380
--- /dev/null
+++ b/frontend/src/components/SchemaDesigner/common/context.ts
@@ -0,0 +1,110 @@
+import { inject, InjectionKey, provide } from "vue";
+import {
+ SchemaDesignerContext,
+ SchemaDesignerTabType,
+ TabContext,
+} from "./type";
+import { isUndefined } from "lodash-es";
+
+export const KEY = Symbol(
+ "bb.schema-designer"
+) as InjectionKey<SchemaDesignerContext>;
+
+export const useSchemaDesignerContext = () => {
+ return inject(KEY)!;
+};
+
+export const provideSchemaDesignerContext = (
+ context: Pick<
+ SchemaDesignerContext,
+ "engine" | "baselineMetadata" | "metadata" | "tabState"
+ >
+) => {
+ const { metadata, tabState } = context;
+
+ provide(KEY, {
+ ...context,
+ // Tab related functions.
+ getCurrentTab: (): TabContext | undefined => {
+ if (isUndefined(tabState.value.currentTabId)) {
+ return undefined;
+ }
+ return tabState.value.tabMap.get(tabState.value.currentTabId);
+ },
+ addTab(tab: TabContext, setAsCurrentTab = true) {
+ const tabCache = Array.from(tabState.value.tabMap.values()).find(
+ (item) => {
+ if (item.type !== tab.type) {
+ return false;
+ }
+
+ if (
+ item.type === SchemaDesignerTabType.TabForTable &&
+ item.schema === tab.schema &&
+ item.table === tab.table
+ ) {
+ return true;
+ }
+ return false;
+ }
+ );
+
+ if (tabCache !== undefined) {
+ tab = {
+ ...tabCache,
+ ...tab,
+ id: tabCache.id,
+ };
+ }
+ tabState.value.tabMap.set(tab.id, tab);
+
+ if (setAsCurrentTab) {
+ tabState.value.currentTabId = tab.id;
+ }
+ },
+ // Schema related functions.
+ dropSchema: (schema: string) => {
+ const tabList = Array.from(tabState.value.tabMap.values());
+ for (const tab of tabList) {
+ if (tab.schema === schema) {
+ tabState.value.tabMap.delete(tab.id);
+ if (tabState.value.currentTabId === tab.id) {
+ tabState.value.currentTabId = undefined;
+ }
+ }
+ }
+
+ metadata.value.schemas = metadata.value.schemas.filter(
+ (item) => item.name !== schema
+ );
+ },
+
+ // Table related functions.
+ dropTable: (schema: string, table: string) => {
+ const tabList = Array.from(tabState.value.tabMap.values());
+ for (const tab of tabList) {
+ if (
+ tab.type === SchemaDesignerTabType.TabForTable &&
+ tab.schema === schema &&
+ tab.table === table
+ ) {
+ tabState.value.tabMap.delete(tab.id);
+ if (tabState.value.currentTabId === tab.id) {
+ tabState.value.currentTabId = undefined;
+ }
+ }
+ }
+
+ const schemaItem = metadata.value.schemas.find(
+ (item) => item.name === schema
+ );
+ if (schemaItem === undefined) {
+ return;
+ }
+
+ schemaItem.tables = schemaItem.tables.filter(
+ (item) => item.name !== table
+ );
+ },
+ });
+};
diff --git a/frontend/src/components/SchemaDesigner/common/index.ts b/frontend/src/components/SchemaDesigner/common/index.ts
new file mode 100644
index 0000000000..003f7d11bf
--- /dev/null
+++ b/frontend/src/components/SchemaDesigner/common/index.ts
@@ -0,0 +1,2 @@
+export * from "./context";
+export * from "./type";
diff --git a/frontend/src/components/SchemaDesigner/common/type.ts b/frontend/src/components/SchemaDesigner/common/type.ts
new file mode 100644
index 0000000000..2ffeef86ed
--- /dev/null
+++ b/frontend/src/components/SchemaDesigner/common/type.ts
@@ -0,0 +1,41 @@
+import { Engine } from "@/types/proto/v1/common";
+import { DatabaseMetadata } from "@/types/proto/v1/database_service";
+import { Ref } from "vue";
+
+export enum SchemaDesignerTabType {
+ TabForTable = "table",
+}
+
+// Tab context for editing table.
+export interface TableTabContext {
+ id: string;
+ type: SchemaDesignerTabType.TabForTable;
+ schema: string;
+ table: string;
+ selectedSubtab?: string;
+}
+
+export type TabContext = TableTabContext;
+
+export interface SchemaDesignerTabState {
+ tabMap: Map<string, TabContext>;
+ currentTabId?: string;
+}
+
+export interface SchemaDesignerContext {
+ baselineMetadata: DatabaseMetadata;
+ engine: Engine;
+
+ metadata: Ref<DatabaseMetadata>;
+ tabState: Ref<SchemaDesignerTabState>;
+
+ // Tab related functions.
+ getCurrentTab: () => TabContext | undefined;
+ addTab: (tab: TabContext, setAsCurrentTab?: boolean) => void;
+
+ // Schema related functions.
+ dropSchema: (schema: string) => void;
+
+ // Table related functions.
+ dropTable: (schema: string, table: string) => void;
+}
diff --git a/frontend/src/components/SchemaDesigner/index.vue b/frontend/src/components/SchemaDesigner/index.vue
new file mode 100644
index 0000000000..e8ff687481
--- /dev/null
+++ b/frontend/src/components/SchemaDesigner/index.vue
@@ -0,0 +1,114 @@
+<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-full relative overflow-y-auto"
+ >
+ <TableEditor
+ v-if="currentTab.type === SchemaDesignerTabType.TabForTable"
+ />
+ </div>
+ </template>
+ <EmptyTips v-else />
+ </main>
+ </Pane>
+ </Splitpanes>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { Splitpanes, Pane } from "splitpanes";
+import { computed, onMounted, reactive, ref } from "vue";
+import { useDBSchemaV1Store } from "@/store";
+import AsidePanel from "./AsidePanel.vue";
+import EmptyTips from "./EmptyTips.vue";
+import TabsContainer from "./TabsContainer.vue";
+import TableEditor from "./Panels/TableEditor.vue";
+import {
+ provideSchemaDesignerContext,
+ useSchemaDesignerContext,
+} from "./common";
+import { DatabaseMetadata } from "@/types/proto/v1/database_service";
+import { Engine } from "@/types/proto/v1/common";
+import { SchemaDesignerTabState, SchemaDesignerTabType } from "./common/type";
+
+interface LocalState {
+ isLoading: boolean;
+}
+
+const props = defineProps({
+ database: {
+ type: String,
+ required: true,
+ },
+});
+const state = reactive<LocalState>({
+ isLoading: true,
+});
+
+const { getCurrentTab } = useSchemaDesignerContext();
+const dbSchemaStore = useDBSchemaV1Store();
+const currentTab = computed(() => {
+ return getCurrentTab();
+});
+const metadata = ref<DatabaseMetadata>(DatabaseMetadata.fromPartial({}));
+const baselineMetadata = ref<DatabaseMetadata>(
+ DatabaseMetadata.fromPartial({})
+);
+const tabState = ref<SchemaDesignerTabState>({
+ tabMap: new Map(),
+});
+
+provideSchemaDesignerContext({
+ metadata,
+ baselineMetadata: baselineMetadata.value,
+ engine: Engine.MYSQL,
+ tabState: tabState,
+});
+
+onMounted(async () => {
+ const databaseMetadata = await dbSchemaStore.getOrFetchDatabaseMetadata(
+ props.database
+ );
+ baselineMetadata.value = databaseMetadata;
+ metadata.value = databaseMetadata;
+ state.isLoading = false;
+});
+</script>
+
+<style>
+@import "splitpanes/dist/splitpanes.css";
+
+/* splitpanes pane style */
+.splitpanes.default-theme .splitpanes__pane {
+ @apply bg-transparent !transition-none;
+}
+
+.splitpanes.default-theme .splitpanes__splitter {
+ @apply bg-gray-100 border-none;
+}
+
+.splitpanes.default-theme .splitpanes__splitter:hover {
+ @apply bg-indigo-300;
+}
+
+.splitpanes.default-theme .splitpanes__splitter::before,
+.splitpanes.default-theme .splitpanes__splitter::after {
+ @apply bg-gray-700 opacity-50 text-white;
+}
+
+.splitpanes.default-theme .splitpanes__splitter:hover::before,
+.splitpanes.default-theme .splitpanes__splitter:hover::after {
+ @apply bg-white opacity-100;
+}
+</style>
diff --git a/frontend/src/components/SchemaDesigner/utils/column.ts b/frontend/src/components/SchemaDesigner/utils/column.ts
new file mode 100644
index 0000000000..2c42a8cbb3
--- /dev/null
+++ b/frontend/src/components/SchemaDesigner/utils/column.ts
@@ -0,0 +1,4 @@
+// TODO(steven): Implement this function.
+export const isColumnChanged = (): boolean => {
+ return false;
+};
diff --git a/frontend/src/components/SchemaDesigner/utils/schema.ts b/frontend/src/components/SchemaDesigner/utils/schema.ts
new file mode 100644
index 0000000000..c9ba0c70d5
--- /dev/null
+++ b/frontend/src/components/SchemaDesigner/utils/schema.ts
@@ -0,0 +1,4 @@
+// TODO(steven): Implement this function.
+export const isSchemaChanged = (): boolean => {
+ return false;
+};
diff --git a/frontend/src/components/SchemaDesigner/utils/table.ts b/frontend/src/components/SchemaDesigner/utils/table.ts
new file mode 100644
index 0000000000..3a5f0405ff
--- /dev/null
+++ b/frontend/src/components/SchemaDesigner/utils/table.ts
@@ -0,0 +1,4 @@
+// TODO(steven): Implement this function.
+export const isTableChanged = (): boolean => {
+ return false;
+};
diff --git a/frontend/src/store/modules/v1/common.ts b/frontend/src/store/modules/v1/common.ts
index 0daeb75a68..9bb6e0e863 100644
--- a/frontend/src/store/modules/v1/common.ts
+++ b/frontend/src/store/modules/v1/common.ts
@@ -15,6 +15,7 @@ export const externalVersionControlPrefix = "externalVersionControls/";
export const logNamePrefix = "logs/";
export const issueNamePrefix = "issues/";
export const secretNamePrefix = "secrets/";
+export const schemaDesignNamePrefix = "schemaDesigns/";
export const getNameParentTokens = (
name: string,
@@ -66,6 +67,19 @@ export const getProjectAndSheetId = (name: string): string[] => {
return tokens;
};
+export const getProjectAndSchemaDesignSheetId = (name: string): string[] => {
+ const tokens = getNameParentTokens(name, [
+ projectNamePrefix,
+ schemaDesignNamePrefix,
+ ]);
+
+ if (tokens.length != 2) {
+ return ["", ""];
+ }
+
+ return tokens;
+};
+
export const getInstanceAndDatabaseId = (name: string): string[] => {
const tokens = getNameParentTokens(name, [
instanceNamePrefix,