Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: support table template (#8377)
ecmadao6298e9f65f18
diff --git a/frontend/src/components/Branch/utils.ts b/frontend/src/components/Branch/utils.tsindex a0649b9b2c..153a2c03de 100644--- a/frontend/src/components/Branch/utils.ts+++ b/frontend/src/components/Branch/utils.ts@@ -262,9 +262,12 @@ const transformSchemaEditToMetadata = (schemaEdit: Schema): SchemaMetadata => {return schemaMetadata;};-const transformTableEditToMetadata = (tableEdit: Table): TableMetadata => {+export const transformTableEditToMetadata = (+ tableEdit: Table+): TableMetadata => {const tableMetadata = TableMetadata.fromPartial({name: tableEdit.name,+ comment: tableEdit.comment,columns: [],indexes: [],foreignKeys: [],@@ -367,8 +370,7 @@ export const rebuildEditableSchemas = ((item) => item.name === column.name);if (!editableColumn) {- const newColumn = convertColumnMetadataToColumn(column);- newColumn.status = "created";+ const newColumn = convertColumnMetadataToColumn(column, "created");editableTable.columnList.push(newColumn);}}@@ -398,11 +400,7 @@ export const rebuildEditableSchemas = ((item) => item.name === table.name);if (!editableTable) {- const newTable = convertTableMetadataToTable(table);- newTable.status = "created";- for (const column of newTable.columnList) {- column.status = "created";- }+ const newTable = convertTableMetadataToTable(table, "created");editableSchema.tableList.push(newTable);}}diff --git a/frontend/src/components/SchemaTemplate/FieldTemplateForm.vue b/frontend/src/components/SchemaTemplate/FieldTemplateForm.vueindex ab47224da2..49c6cf1241 100644--- a/frontend/src/components/SchemaTemplate/FieldTemplateForm.vue+++ b/frontend/src/components/SchemaTemplate/FieldTemplateForm.vue@@ -56,6 +56,7 @@type="radio"class="btn mr-2":checked="state.engine === engine"+ :disabled="!allowEdit"/><EngineIcon:engine="engine"@@ -98,30 +99,20 @@:classification="state.column?.classification":classification-config="classificationConfig"/>- <div class="flex">- <template v-if="allowEdit">- <button- v-if="state.column?.classification"- class="w-6 h-6 p-1 hover:bg-control-bg-hover rounded cursor-pointer disabled:cursor-not-allowed disabled:hover:bg-white disabled:text-gray-400"- @click.prevent="state.column!.classification = ''"- >- <heroicons-outline:x class="w-4 h-4" />- </button>- <button- class="w-6 h-6 p-1 hover:bg-control-bg-hover rounded cursor-pointer disabled:cursor-not-allowed disabled:hover:bg-white disabled:text-gray-400"- @click.prevent="state.showClassificationDrawer = true"- >- <heroicons-outline:pencil class="w-4 h-4" />- </button>- </template>- <template v-else>- <input- name="classification"- type="text"- class="textfield w-full"- :disabled="true"- />- </template>+ <div v-if="allowEdit" class="flex">+ <button+ v-if="state.column?.classification"+ class="w-6 h-6 p-1 hover:bg-control-bg-hover rounded cursor-pointer disabled:cursor-not-allowed disabled:hover:bg-white disabled:text-gray-400"+ @click.prevent="state.column!.classification = ''"+ >+ <heroicons-outline:x class="w-4 h-4" />+ </button>+ <button+ class="w-6 h-6 p-1 hover:bg-control-bg-hover rounded cursor-pointer disabled:cursor-not-allowed disabled:hover:bg-white disabled:text-gray-400"+ @click.prevent="state.showClassificationDrawer = true"+ >+ <heroicons-outline:pencil class="w-4 h-4" />+ </button></div></div></div>@@ -226,7 +217,7 @@{{ $t("common.cancel") }}</NButton><NButton- v-if="!readonly && allowEdit"+ v-if="allowEdit":disabled="sumbitDisabled"type="primary"@click.prevent="sumbit"@@ -248,7 +239,7 @@</template><script lang="ts" setup>-import { isEqual } from "lodash-es";+import { isEqual, cloneDeep } from "lodash-es";import { computed, reactive } from "vue";import { DrawerContent } from "@/components/v2";import { useSettingV1Store } from "@/store";@@ -364,7 +355,10 @@ const sumbit = async () => {const settingValue = SchemaTemplateSetting.fromJSON({});if (setting?.value?.schemaTemplateSettingValue) {- Object.assign(settingValue, setting.value.schemaTemplateSettingValue);+ Object.assign(+ settingValue,+ cloneDeep(setting.value.schemaTemplateSettingValue)+ );}const index = settingValue.fieldTemplates.findIndex(diff --git a/frontend/src/components/SchemaTemplate/FieldTemplateTable.vue b/frontend/src/components/SchemaTemplate/FieldTemplateTable.vueindex fc23127f37..3638699c85 100644--- a/frontend/src/components/SchemaTemplate/FieldTemplateTable.vue+++ b/frontend/src/components/SchemaTemplate/FieldTemplateTable.vue@@ -34,14 +34,20 @@>{{ $t("common.view") }}</button>- <BBButtonConfirm- v-if="!readonly"- :style="'DELETE'"- :ok-text="$t('common.delete')"- :confirm-title="$t('common.delete') + ` '${item.column?.name}'?`"- :require-confirm="true"- @confirm="() => deleteTemplate(item.id)"- />+ <NPopconfirm v-if="!readonly" @positive-click="deleteTemplate(item.id)">+ <template #trigger>+ <button+ class="w-5 h-5 p-0.5 hover:bg-gray-300 rounded cursor-pointer disabled:cursor-not-allowed disabled:hover:bg-white disabled:text-gray-400"+ @click.stop=""+ >+ <heroicons-outline:trash class="w-4 h-4" />+ </button>+ </template>++ <div class="whitespace-nowrap">+ {{ $t("common.delete") + ` '${item.column?.name}'?` }}+ </div>+ </NPopconfirm></div></template></BBGrid>@@ -49,6 +55,7 @@<script lang="ts" setup>import { pullAt } from "lodash-es";+import { NPopconfirm } from "naive-ui";import { computed } from "vue";import { useI18n } from "vue-i18n";import { BBGrid, BBGridColumn } from "@/bbkit";diff --git a/frontend/src/components/SchemaTemplate/TableTemplateForm.vue b/frontend/src/components/SchemaTemplate/TableTemplateForm.vuenew file mode 100644index 0000000000..f55c273c9c--- /dev/null+++ b/frontend/src/components/SchemaTemplate/TableTemplateForm.vue@@ -0,0 +1,365 @@+<template>+ <DrawerContent :title="$t('schema-template.table-template.self')">+ <div+ class="space-y-6 divide-y divide-block-border w-[calc(100vw-256px)] !max-w-[60rem]"+ >+ <div class="space-y-6">+ <!-- category -->+ <div class="sm:col-span-2 sm:col-start-1">+ <label for="category" class="textlabel">+ {{ $t("schema-template.form.category") }}+ </label>+ <p class="text-sm text-gray-500 mb-2">+ {{ $t("schema-template.form.category-desc") }}+ </p>+ <div class="relative flex flex-row justify-between items-center mt-1">+ <input+ v-model="state.category"+ required+ name="category"+ type="text"+ :placeholder="$t('schema-template.form.unclassified')"+ class="textfield w-full"+ :disabled="!allowEdit"+ />+ <NDropdown+ trigger="click"+ :options="categoryOptions"+ :disabled="!allowEdit"+ @select="(category: string) => (state.category = category)"+ >+ <button class="absolute right-5">+ <heroicons-solid:chevron-up-down+ class="w-4 h-auto text-gray-400"+ />+ </button>+ </NDropdown>+ </div>+ </div>++ <div class="w-full mb-6 space-y-1">+ <label for="engine" class="textlabel">+ {{ $t("database.engine") }}+ </label>+ <div class="grid grid-cols-4 gap-2">+ <template v-for="engine in engineList" :key="engine">+ <div+ class="flex relative justify-start p-2 border rounded"+ :class="[+ state.engine === engine && 'font-medium bg-control-bg-hover',+ allowEdit+ ? 'cursor-pointer hover:bg-control-bg-hover'+ : 'cursor-not-allowed',+ ]"+ @click.capture="changeEngine(engine)"+ >+ <div class="flex flex-row justify-start items-center">+ <input+ type="radio"+ class="btn mr-2"+ :checked="state.engine === engine"+ :disabled="!allowEdit"+ />+ <EngineIcon+ :engine="engine"+ custom-class="w-5 h-auto max-h-[20px] object-contain mr-1"+ />+ <p class="text-center text-sm">+ {{ engineNameV1(engine) }}+ </p>+ </div>+ </div>+ </template>+ </div>+ </div>+ </div>+ <div class="space-y-6 pt-6">+ <div class="grid grid-cols-1 gap-y-6 gap-x-4 sm:grid-cols-4">+ <!-- table name -->+ <div class="sm:col-span-2 sm:col-start-1">+ <label for="table-name" class="textlabel">+ {{ $t("schema-template.form.table-name") }}+ <span class="text-red-600 mr-2">*</span>+ </label>+ <input+ v-model="state.table!.name"+ required+ name="table-name"+ type="text"+ placeholder="table name"+ class="textfield mt-1 w-full"+ :disabled="!allowEdit"+ />+ </div>++ <!-- comment -->+ <div class="sm:col-span-4 sm:col-start-1">+ <label for="comment" class="textlabel">+ {{ $t("schema-template.form.comment") }}+ </label>+ <textarea+ v-model="state.table!.comment"+ rows="3"+ class="textfield block w-full resize-none mt-1 text-sm text-control rounded-md whitespace-pre-wrap"+ :disabled="!allowEdit"+ />+ </div>++ <div class="col-span-4">+ <div+ v-if="allowEdit"+ class="w-full py-2 flex items-center space-x-2"+ >+ <NButton size="small" :disabled="false" @click="onColumnAdd">+ <heroicons-outline:plus class="w-4 h-auto mr-1 text-gray-400" />+ {{ $t("schema-editor.actions.add-column") }}+ </NButton>+ <NButton+ size="small"+ :disabled="false"+ @click="state.showFieldTemplateDrawer = true"+ >+ <FeatureBadge feature="bb.feature.schema-template" />+ <heroicons-outline:plus class="w-4 h-auto mr-1 text-gray-400" />+ {{ $t("schema-editor.actions.add-from-template") }}+ </NButton>+ </div>+ <TableColumnEditor+ :readonly="!allowEdit"+ :show-foreign-key="false"+ :table="state.table"+ :engine="state.engine"+ :classification-config-id="classificationConfig.id"+ @on-drop="onColumnDrop"+ @on-primary-key-set="setColumnPrimaryKey"+ />+ </div>+ </div>+ </div>+ </div>++ <template #footer>+ <div class="w-full flex justify-between items-center">+ <div class="w-full flex justify-end items-center gap-x-3">+ <NButton @click.prevent="$emit('dismiss')">+ {{ $t("common.cancel") }}+ </NButton>+ <NButton+ v-if="allowEdit"+ :disabled="sumbitDisabled"+ type="primary"+ @click.prevent="onSumbit"+ >+ {{ create ? $t("common.create") : $t("common.update") }}+ </NButton>+ </div>+ </div>+ </template>+ </DrawerContent>++ <Drawer+ :show="state.showFieldTemplateDrawer"+ @close="state.showFieldTemplateDrawer = false"+ >+ <DrawerContent :title="$t('schema-template.field-template.self')">+ <div class="w-[calc(100vw-36rem)] min-w-[64rem] max-w-[calc(100vw-8rem)]">+ <FieldTemplates+ :engine="state.engine"+ :readonly="true"+ @apply="handleApplyColumnTemplate"+ />+ </div>+ </DrawerContent>+ </Drawer>+</template>++<script lang="ts" setup>+import { isEqual, cloneDeep } from "lodash-es";+import { computed, nextTick, reactive } from "vue";+import { transformTableEditToMetadata } from "@/components/Branch/utils";+import { Drawer, DrawerContent } from "@/components/v2";+import { useSettingV1Store } from "@/store";+import { Engine } from "@/types/proto/v1/common";+import { ColumnMetadata } from "@/types/proto/v1/database_service";+import {+ SchemaTemplateSetting,+ SchemaTemplateSetting_FieldTemplate,+ SchemaTemplateSetting_TableTemplate,+} from "@/types/proto/v1/setting_service";+import { convertTableMetadataToTable } from "@/types/v1/schemaEditor";+import {+ Column,+ Table,+ convertColumnMetadataToColumn,+} from "@/types/v1/schemaEditor";+import { engineNameV1, useWorkspacePermissionV1 } from "@/utils";+import FieldTemplates from "@/views/SchemaTemplate/FieldTemplates.vue";+import { engineList } from "./utils";++const props = defineProps<{+ create: boolean;+ readonly?: boolean;+ template: SchemaTemplateSetting_TableTemplate;+}>();++const emit = defineEmits(["dismiss"]);++interface LocalState {+ id: string;+ engine: Engine;+ category: string;+ table: Table;+ showClassificationDrawer: boolean;+ showFieldTemplateDrawer: boolean;+}++const state = reactive<LocalState>({+ id: props.template.id,+ engine: props.template.engine,+ category: props.template.category,+ table: convertTableMetadataToTable(Object.assign({}, props.template.table)),+ showClassificationDrawer: false,+ showFieldTemplateDrawer: false,+});+const settingStore = useSettingV1Store();+const allowEdit = computed(() => {+ return (+ useWorkspacePermissionV1("bb.permission.workspace.manage-general").value &&+ !props.readonly+ );+});++const schemaTemplateList = computed(() => {+ const setting = settingStore.getSettingByName("bb.workspace.schema-template");+ return setting?.value?.schemaTemplateSettingValue?.fieldTemplates ?? [];+});++const classificationConfig = computed(() => {+ // TODO(ed): it's a temporary solution+ return settingStore.classification[0];+});++const categoryOptions = computed(() => {+ const options = [];+ for (const category of new Set(+ schemaTemplateList.value.map((template) => template.category)+ ).values()) {+ if (!category) {+ continue;+ }+ options.push({+ label: category,+ key: category,+ });+ }+ return options;+});++const changeEngine = (engine: Engine) => {+ if (allowEdit.value) {+ state.engine = engine;+ }+};++const sumbitDisabled = computed(() => {+ if (!state.table.name || state.table.columnList.length === 0) {+ return true;+ }+ if (state.table.columnList.some((col) => !col.name || !col.type)) {+ return true;+ }+ if (+ !props.create &&+ isEqual(convertTableMetadataToTable(props.template.table!), state.table)+ ) {+ return true;+ }+ return false;+});++const onSumbit = async () => {+ const template: SchemaTemplateSetting_TableTemplate = {+ id: state.id,+ engine: state.engine,+ category: state.category,+ table: transformTableEditToMetadata(state.table),+ };+ const setting = await settingStore.fetchSettingByName(+ "bb.workspace.schema-template"+ );++ const settingValue = SchemaTemplateSetting.fromJSON({});+ if (setting?.value?.schemaTemplateSettingValue) {+ Object.assign(+ settingValue,+ cloneDeep(setting.value.schemaTemplateSettingValue)+ );+ }++ const index = settingValue.tableTemplates.findIndex(+ (t) => t.id === template.id+ );+ if (index >= 0) {+ settingValue.tableTemplates[index] = template;+ } else {+ settingValue.tableTemplates.push(template);+ }++ await settingStore.upsertSetting({+ name: "bb.workspace.schema-template",+ value: {+ schemaTemplateSettingValue: settingValue,+ },+ });+ emit("dismiss");+};++const onColumnAdd = () => {+ const column = convertColumnMetadataToColumn(+ ColumnMetadata.fromPartial({}),+ "created"+ );+ state.table.columnList.push(column);+ nextTick(() => {+ const container = document.querySelector("#table-editor-container");+ (+ container?.querySelector(+ `.column-${column.id} .column-name-input`+ ) as HTMLInputElement+ )?.focus();+ });+};++const onColumnDrop = (column: Column) => {+ state.table.columnList = state.table.columnList.filter(+ (item) => item.id !== column.id+ );+ state.table.primaryKey.columnIdList =+ state.table.primaryKey.columnIdList.filter(+ (columnId) => columnId !== column.id+ );+};++const setColumnPrimaryKey = (column: Column, isPrimaryKey: boolean) => {+ if (isPrimaryKey) {+ column.nullable = false;+ state.table.primaryKey.columnIdList.push(column.id);+ } else {+ state.table.primaryKey.columnIdList =+ state.table.primaryKey.columnIdList.filter(+ (columnId) => columnId !== column.id+ );+ }+};++const handleApplyColumnTemplate = (+ template: SchemaTemplateSetting_FieldTemplate+) => {+ if (template.engine !== state.engine || !template.column) {+ return;+ }+ const column = convertColumnMetadataToColumn(template.column, "created");+ state.table.columnList.push(column);+ state.showFieldTemplateDrawer = false;+};+</script>diff --git a/frontend/src/components/SchemaTemplate/TableTemplateTable.vue b/frontend/src/components/SchemaTemplate/TableTemplateTable.vuenew file mode 100644index 0000000000..0c34654575--- /dev/null+++ b/frontend/src/components/SchemaTemplate/TableTemplateTable.vue@@ -0,0 +1,121 @@+<template>+ <BBGrid+ :column-list="columnList"+ :data-source="templateList"+ :is-row-clickable="isRowClickable"+ class="border"+ @click-row="clickRow"+ >+ <template #item="{ item }: { item: SchemaTemplateSetting_TableTemplate }">+ <div class="bb-grid-cell flex justify-start items-center">+ <EngineIcon :engine="item.engine" custom-class="ml-0 mr-1" />+ {{ item.table?.name }}+ </div>+ <div class="bb-grid-cell">+ {{ item.table?.comment }}+ </div>+ <div class="bb-grid-cell flex items-center justify-start gap-x-5">+ <button+ type="button"+ class="btn-normal flex justify-end !py-1 !px-3"+ @click.stop="$emit('view', item)"+ >+ {{ $t("common.view") }}+ </button>+ <NPopconfirm v-if="!readonly" @positive-click="deleteTemplate(item.id)">+ <template #trigger>+ <button+ class="w-5 h-5 p-0.5 hover:bg-gray-300 rounded cursor-pointer disabled:cursor-not-allowed disabled:hover:bg-white disabled:text-gray-400"+ @click.stop=""+ >+ <heroicons-outline:trash class="w-4 h-4" />+ </button>+ </template>++ <div class="whitespace-nowrap">+ {{ $t("common.delete") + ` '${item.table?.name}'?` }}+ </div>+ </NPopconfirm>+ </div>+ </template>+ </BBGrid>+</template>++<script lang="ts" setup>+import { pullAt } from "lodash-es";+import { NPopconfirm } from "naive-ui";+import { computed } from "vue";+import { useI18n } from "vue-i18n";+import { BBGrid, BBGridColumn } from "@/bbkit";+import { useSettingV1Store } from "@/store";+import { Engine } from "@/types/proto/v1/common";+import {+ SchemaTemplateSetting,+ SchemaTemplateSetting_TableTemplate,+} from "@/types/proto/v1/setting_service";++const props = defineProps<{+ engine?: Engine;+ readonly: boolean;+ templateList: SchemaTemplateSetting_TableTemplate[];+}>();++const emit = defineEmits<{+ (event: "view", item: SchemaTemplateSetting_TableTemplate): void;+ (event: "apply", item: SchemaTemplateSetting_TableTemplate): void;+}>();++const { t } = useI18n();+const settingStore = useSettingV1Store();++const columnList = computed((): BBGridColumn[] => {+ return [+ {+ title: t("schema-template.form.table-name"),+ width: "15rem",+ class: "capitalize",+ },+ {+ title: t("schema-template.form.comment"),+ width: "auto",+ class: "capitalize",+ },+ {+ title: t("common.operations"),+ width: "10rem",+ class: "capitalize",+ },+ ];+});++const clickRow = (template: SchemaTemplateSetting_TableTemplate) => {+ emit("apply", template);+};++const isRowClickable = (template: SchemaTemplateSetting_TableTemplate) => {+ return template.engine === props.engine;+};++const deleteTemplate = async (id: string) => {+ const setting = await settingStore.fetchSettingByName(+ "bb.workspace.schema-template"+ );++ const settingValue = SchemaTemplateSetting.fromJSON({});+ if (setting?.value?.schemaTemplateSettingValue) {+ Object.assign(settingValue, setting.value.schemaTemplateSettingValue);+ }++ const index = settingValue.tableTemplates.findIndex((t) => t.id === id);+ if (index >= 0) {+ pullAt(settingValue.tableTemplates, index);++ await settingStore.upsertSetting({+ name: "bb.workspace.schema-template",+ value: {+ schemaTemplateSettingValue: settingValue,+ },+ });+ }+};+</script>diff --git a/frontend/src/components/SchemaTemplate/TableTemplateView.vue b/frontend/src/components/SchemaTemplate/TableTemplateView.vuenew file mode 100644index 0000000000..48fcbed52d--- /dev/null+++ b/frontend/src/components/SchemaTemplate/TableTemplateView.vue@@ -0,0 +1,113 @@+<template>+ <div v-if="templateList.length === 0" class="bg-white rounded-lg">+ <div+ class="border-4 border-dashed border-gray-200 rounded-lg h-96 flex justify-center items-center"+ >+ <div class="text-center flex flex-col justify-center items-center">+ <img src="../../assets/illustration/no-data.webp" class="w-52" />+ </div>+ </div>+ </div>+ <div v-else class="flex">+ <div+ class="hidden sm:flex w-1/5 max-w-xs flex-col space-y-3 border-r mr-5 pr-5"+ >+ <p class="text-lg">+ {{ $t("schema-template.form.category") }}+ </p>+ <div class="space-y-2">+ <label+ v-for="item in categoryList"+ :key="item.id"+ class="flex items-center gap-x-1 text-sm text-gray-600"+ >+ <input+ type="checkbox"+ :value="item"+ :checked="state.selectedCategory.has(item.id)"+ class="h-4 w-4 border-gray-300 rounded text-indigo-600 focus:ring-indigo-500"+ @input="toggleCategoryCheck(item.id)"+ />+ <span class="text-ellipsis whitespace-nowrap overflow-hidden">+ {{ item.text }}+ </span>+ <span+ class="items-center text-xs px-2 py-0.5 rounded-full bg-gray-200 text-gray-800"+ >+ {{ item.count }}+ </span>+ </label>+ </div>+ </div>+ <TableTemplateTable+ :engine="engine"+ :readonly="readonly"+ :template-list="filteredTemplateList"+ class="flex-1"+ @view="$emit('view', $event)"+ @apply="$emit('apply', $event)"+ />+ </div>+</template>++<script lang="ts" setup>+import { reactive, computed } from "vue";+import { useI18n } from "vue-i18n";+import { Engine } from "@/types/proto/v1/common";+import { SchemaTemplateSetting_TableTemplate } from "@/types/proto/v1/setting_service";++interface LocalState {+ selectedCategory: Set<string>;+}++const props = defineProps<{+ engine?: Engine;+ readonly: boolean;+ templateList: SchemaTemplateSetting_TableTemplate[];+}>();++defineEmits<{+ (event: "view", item: SchemaTemplateSetting_TableTemplate): void;+ (event: "apply", item: SchemaTemplateSetting_TableTemplate): void;+}>();++const state = reactive<LocalState>({+ selectedCategory: new Set<string>(),+});+const { t } = useI18n();++const toggleCategoryCheck = (category: string) => {+ if (state.selectedCategory.has(category)) {+ state.selectedCategory.delete(category);+ } else {+ state.selectedCategory.add(category);+ }+};++const categoryList = computed(() => {+ const categoryMap = new Map<string, number>();+ for (const template of props.templateList) {+ const num = categoryMap.get(template.category) ?? 0;+ categoryMap.set(template.category, num + 1);+ }++ const resp = [];+ for (const [category, count] of categoryMap.entries()) {+ resp.push({+ id: category,+ text: category || t("schema-template.form.unclassified"),+ count,+ });+ }+ return resp;+});++const filteredTemplateList = computed(() => {+ if (state.selectedCategory.size === 0) {+ return props.templateList;+ }+ return props.templateList.filter((template) =>+ state.selectedCategory.has(template.category)+ );+});+</script>diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex a606289e9c..0fa7203c01 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -2848,6 +2848,7 @@"self": "Schema template","field-template": {"self": "Field Template",+ "add": "Add field template","description": "You can pre-define the field template, then apply the template during the schema change."},"column-type-restriction": {@@ -2863,7 +2864,11 @@"one-allowed-type-per-line": "One allowed data type per line"}},- "add-field": "Add field template",+ "table-template": {+ "self": "Table Template",+ "add": "Add table template",+ "description": "You can pre-define the table template, then apply the template during the schema change."+ },"search-by-name-or-comment": "Search by name or comment","form": {"category": "Category",@@ -2873,7 +2878,8 @@"column-type": "Column type","default-value": "Default value","comment": "Comment",- "nullable": "Nullable"+ "nullable": "Nullable",+ "table-name": "Table name"},"classification": {"self": "Data classification",diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex 7e3b476471..dc56f39352 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -2845,6 +2845,7 @@"self": "Plantilla de esquema","field-template": {"self": "Plantilla de campo",+ "add": "Agregar plantilla de campo","description": "Predefina la plantilla de campo, luego aplique la plantilla durante el cambio de esquema."},"column-type-restriction": {@@ -2860,7 +2861,11 @@"one-allowed-type-per-line": "Un tipo permitido por línea"}},- "add-field": "Agregar plantilla de campo",+ "table-template": {+ "self": "Plantilla de tabla",+ "add": "Agregar plantilla de tabla",+ "description": "Puede predefinir la plantilla de tabla y luego aplicar la plantilla durante el cambio de esquema."+ },"search-by-name-or-comment": "Buscar por nombre o comentario","form": {"category": "Categoría",@@ -2870,7 +2875,8 @@"column-type": "Tipo de columna","default-value": "Valor por defecto","comment": "Comentario",- "nullable": "Anulable"+ "nullable": "Anulable",+ "table-name": "Nombre de la tabla"},"classification": {"self": "Clasificación de datos",diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex f85443ca15..939c563da2 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -2841,7 +2841,8 @@"self": "Schema 模板","field-template": {"self": "字段模板",- "description": "预定义 Schema 模板,之后可以在变更或设计 Schema 时应用这些模板。"+ "add": "新增字段模板",+ "description": "预定义字段模板,之后可以在变更或设计 Schema 时应用这些模板。"},"column-type-restriction": {"self": "列类型约束",@@ -2856,7 +2857,11 @@"one-allowed-type-per-line": "每行放一个允许的数据类型"}},- "add-field": "新增字段模板",+ "table-template": {+ "self": "表模板",+ "add": "新增表模板",+ "description": "预定义表模板,之后可以在变更或设计 Schema 时应用这些模板。"+ },"search-by-name-or-comment": "根据名称或备注搜索","form": {"category": "分类",@@ -2866,7 +2871,8 @@"column-type": "字段类型","default-value": "默认值","comment": "备注",- "nullable": "可为空"+ "nullable": "可为空",+ "table-name": "表名"},"classification": {"self": "数据分类分级",diff --git a/frontend/src/types/v1/schemaEditor/atomType.ts b/frontend/src/types/v1/schemaEditor/atomType.tsindex f11a73cb96..f6b3f8394d 100644--- a/frontend/src/types/v1/schemaEditor/atomType.ts+++ b/frontend/src/types/v1/schemaEditor/atomType.ts@@ -58,7 +58,8 @@ export interface Schema {}export const convertColumnMetadataToColumn = (- columnMetadata: ColumnMetadata+ columnMetadata: ColumnMetadata,+ status: Status = "normal"): Column => {return {id: uuidv1(),@@ -69,12 +70,13 @@ export const convertColumnMetadataToColumn = (userComment: columnMetadata.userComment,default: columnMetadata.default,classification: columnMetadata.classification,- status: "normal",+ status,};};export const convertTableMetadataToTable = (- tableMetadata: TableMetadata+ tableMetadata: TableMetadata,+ status: Status = "normal"): Table => {const table: Table = {id: uuidv1(),@@ -85,14 +87,14 @@ export const convertTableMetadataToTable = (dataSize: tableMetadata.dataSize,comment: tableMetadata.comment,columnList: tableMetadata.columns.map((column) =>- convertColumnMetadataToColumn(column)+ convertColumnMetadataToColumn(column, status)),primaryKey: {name: "",columnIdList: [],},foreignKeyList: [],- status: "normal",+ status,};for (const indexMetadata of tableMetadata.indexes) {diff --git a/frontend/src/views/SchemaTemplate/FieldTemplates.vue b/frontend/src/views/SchemaTemplate/FieldTemplates.vueindex 4a7dd212b3..2b0224c554 100644--- a/frontend/src/views/SchemaTemplate/FieldTemplates.vue+++ b/frontend/src/views/SchemaTemplate/FieldTemplates.vue@@ -15,7 +15,7 @@:disabled="!hasPermission"@click="createSchemaTemplate">- {{ $t("schema-template.add-field") }}+ {{ $t("schema-template.field-template.add") }}</NButton></div></div>@@ -51,14 +51,15 @@</div><FieldTemplateView:engine="engine"- :readonly="!hasPermission || readonly"+ :readonly="!hasPermission || !!readonly":template-list="filteredTemplateList"@view="editSchemaTemplate"- @apply="(template: SchemaTemplateSetting_FieldTemplate) => $emit('apply', template)"+ @apply="$emit('apply', $event)"/></div><Drawer :show="state.showDrawer" @close="state.showDrawer = false"><FieldTemplateForm+ :readonly="!hasPermission || !!readonly":create="!state.template.column?.name":template="state.template"@dismiss="state.showDrawer = false"diff --git a/frontend/src/views/SchemaTemplate/TableTemplates.vue b/frontend/src/views/SchemaTemplate/TableTemplates.vuenew file mode 100644index 0000000000..129bf35d41--- /dev/null+++ b/frontend/src/views/SchemaTemplate/TableTemplates.vue@@ -0,0 +1,194 @@+<template>+ <div class="w-full space-y-4 text-sm">+ <FeatureAttention+ feature="bb.feature.schema-template"+ custom-class="my-4"+ />+ <div v-if="!readonly" class="space-y-4">+ <div class="flex items-center justify-between gap-x-6">+ <div class="flex-1 textinfolabel">+ {{ $t("schema-template.table-template.description") }}+ </div>+ <div>+ <NButton+ type="primary"+ :disabled="!hasPermission"+ @click="createSchemaTemplate"+ >+ {{ $t("schema-template.table-template.add") }}+ </NButton>+ </div>+ </div>+ </div>+ <div class="flex items-center gap-x-5 my-4 pb-5 border-b">+ <template v-if="showEngineFilter">+ <label+ v-for="item in engineList"+ :key="item"+ class="flex items-center gap-x-1 text-sm text-gray-600"+ >+ <input+ type="checkbox"+ :value="item"+ :checked="state.selectedEngine.has(item)"+ class="h-4 w-4 border-gray-300 rounded text-indigo-600 focus:ring-indigo-500"+ @input="toggleEngineCheck(item)"+ />+ <EngineIcon :engine="item" custom-class="ml-0 mr-1" />+ <span+ class="items-center text-xs px-2 py-0.5 rounded-full bg-gray-200 text-gray-800"+ >+ {{ countTemplateByEngine(item) }}+ </span>+ </label>+ </template>+ <BBTableSearch+ ref="searchField"+ class="ml-auto w-72"+ :placeholder="$t('schema-template.search-by-name-or-comment')"+ @change-text="(val: string) => state.searchText = val"+ />+ </div>+ <TableTemplateView+ :engine="engine"+ :readonly="!hasPermission || !!readonly"+ :template-list="filteredTemplateList"+ @view="editSchemaTemplate"+ @apply="$emit('apply', $event)"+ />+ </div>+ <Drawer :show="state.showDrawer" @close="state.showDrawer = false">+ <TableTemplateForm+ :readonly="!hasPermission || !!readonly"+ :create="!state.template.table?.name"+ :template="state.template"+ @dismiss="state.showDrawer = false"+ />+ </Drawer>+ <FeatureModal+ feature="bb.feature.schema-template"+ :open="state.showFeatureModal"+ @cancel="state.showFeatureModal = false"+ />+</template>++<script lang="ts" setup>+import { NButton } from "naive-ui";+import { v1 as uuidv1 } from "uuid";+import { reactive, computed, onMounted } from "vue";+import { engineList } from "@/components/SchemaTemplate/utils";+import { Drawer } from "@/components/v2";+import { featureToRef, useSettingV1Store } from "@/store";+import { Engine } from "@/types/proto/v1/common";+import { TableMetadata } from "@/types/proto/v1/database_service";+import { SchemaTemplateSetting_TableTemplate } from "@/types/proto/v1/setting_service";+import { useWorkspacePermissionV1 } from "@/utils";++interface LocalState {+ template: SchemaTemplateSetting_TableTemplate;+ showDrawer: boolean;+ showFeatureModal: boolean;+ searchText: string;+ selectedEngine: Set<Engine>;+}++const props = defineProps<{+ engine?: Engine;+ readonly?: boolean;+ showEngineFilter?: boolean;+}>();++defineEmits<{+ (event: "apply", item: SchemaTemplateSetting_TableTemplate): void;+}>();++const initialTemplate = (): SchemaTemplateSetting_TableTemplate => ({+ id: uuidv1(),+ engine: props.engine ?? Engine.MYSQL,+ category: "",+ table: TableMetadata.fromPartial({+ name: "",+ comment: "",+ columns: [],+ }),+});++const state = reactive<LocalState>({+ showDrawer: false,+ showFeatureModal: false,+ template: initialTemplate(),+ searchText: "",+ selectedEngine: new Set<Engine>(),+});++onMounted(() => {+ if (props.engine) {+ state.selectedEngine.add(props.engine);+ }+});++const hasFeature = featureToRef("bb.feature.schema-template");+const hasPermission = useWorkspacePermissionV1(+ "bb.permission.workspace.manage-general"+);++const createSchemaTemplate = () => {+ if (!hasFeature.value) {+ state.showFeatureModal = true;+ return;+ }+ state.template = initialTemplate();+ state.showDrawer = true;+};++const editSchemaTemplate = (template: SchemaTemplateSetting_TableTemplate) => {+ state.template = template;+ state.showDrawer = true;+};++const toggleEngineCheck = (engine: Engine) => {+ if (state.selectedEngine.has(engine)) {+ state.selectedEngine.delete(engine);+ } else {+ state.selectedEngine.add(engine);+ }+};++const settingStore = useSettingV1Store();++const schemaTemplateList = computed(() => {+ const setting = settingStore.getSettingByName("bb.workspace.schema-template");+ return setting?.value?.schemaTemplateSettingValue?.tableTemplates ?? [];+});++const countTemplateByEngine = (engine: Engine) => {+ return schemaTemplateList.value.filter(+ (template) => template.engine === engine+ ).length;+};++const filteredTemplateList = computed(() => {+ if (state.selectedEngine.size === 0) {+ return schemaTemplateList.value.filter(filterTemplateByKeyword);+ }+ return schemaTemplateList.value.filter(+ (template) =>+ state.selectedEngine.has(template.engine) &&+ filterTemplateByKeyword(template)+ );+});++const filterTemplateByKeyword = (+ template: SchemaTemplateSetting_TableTemplate+) => {+ const keyword = state.searchText.trim().toLowerCase();+ if (!keyword) return true;+ if (template.table?.name.toLowerCase().includes(keyword)) {+ return true;+ }+ if (template.table?.comment.toLowerCase().includes(keyword)) {+ return true;+ }+ return false;+};+</script>diff --git a/frontend/src/views/SettingWorkspaceSchemaTemplate.vue b/frontend/src/views/SettingWorkspaceSchemaTemplate.vueindex 3366db8fff..fe9ffbf747 100644--- a/frontend/src/views/SettingWorkspaceSchemaTemplate.vue+++ b/frontend/src/views/SettingWorkspaceSchemaTemplate.vue@@ -6,6 +6,12 @@><FieldTemplates :show-engine-filter="true" /></NTabPane>+ <NTabPane+ name="TABLE_TEMPLATE"+ :tab="$t('schema-template.table-template.self')"+ >+ <TableTemplates :show-engine-filter="true" />+ </NTabPane><NTabPanename="COLUMN_TYPE_RESTRICTION":tab="$t('schema-template.column-type-restriction.self')"@@ -21,9 +27,10 @@ import { reactive, watch } from "vue";import { useRoute, useRouter } from "vue-router";import ColumnTypes from "@/views/SchemaTemplate/ColumnTypes.vue";import FieldTemplates from "@/views/SchemaTemplate/FieldTemplates.vue";+import TableTemplates from "@/views/SchemaTemplate/TableTemplates.vue";interface LocalState {- selectedTab: "FIELD_TEMPLATE" | "COLUMN_TYPE_RESTRICTION";+ selectedTab: "FIELD_TEMPLATE" | "COLUMN_TYPE_RESTRICTION" | "TABLE_TEMPLATE";}const route = useRoute();@@ -34,11 +41,17 @@ const state = reactive<LocalState>({watch(() => route.hash,- () => {- if (route.hash === "#column-type-restriction") {- state.selectedTab = "COLUMN_TYPE_RESTRICTION";- } else {- state.selectedTab = "FIELD_TEMPLATE";+ (hash) => {+ switch (hash) {+ case "#column-type-restriction":+ state.selectedTab = "COLUMN_TYPE_RESTRICTION";+ break;+ case "#table-template":+ state.selectedTab = "TABLE_TEMPLATE";+ break;+ default:+ state.selectedTab = "FIELD_TEMPLATE";+ break;}},{@@ -48,11 +61,17 @@ watch(watch(() => state.selectedTab,- () => {- if (state.selectedTab === "COLUMN_TYPE_RESTRICTION") {- router.push({ hash: "#column-type-restriction" });- } else if (state.selectedTab === "FIELD_TEMPLATE") {- router.push({ hash: "" });+ (tab) => {+ switch (tab) {+ case "COLUMN_TYPE_RESTRICTION":+ router.push({ hash: "#column-type-restriction" });+ break;+ case "TABLE_TEMPLATE":+ router.push({ hash: "#table-template" });+ break;+ default:+ router.push({ hash: "" });+ break;}});