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: implement the schema review in frontend (#1124)
ecmadao2e140a79aad0
diff --git a/frontend/src/assets/illustration/no-data.webp b/frontend/src/assets/illustration/no-data.webpnew file mode 100644index 0000000000..72a2453b99Binary files /dev/null and b/frontend/src/assets/illustration/no-data.webp differdiff --git a/frontend/src/components/Breadcrumb.vue b/frontend/src/components/Breadcrumb.vueindex 87b6c9cc98..755bf3a64c 100644--- a/frontend/src/components/Breadcrumb.vue+++ b/frontend/src/components/Breadcrumb.vue@@ -103,6 +103,7 @@ export default defineComponent({const dataSourceSlug = routeSlug.dataSourceSlug;const migrationHistory = routeSlug.migrationHistorySlug;const versionControlSlug = routeSlug.vcsSlug;+ const schemaReviewPolicySlug = routeSlug.schemaReviewPolicySlug;const list: Array<BreadcrumbItem> = [];if (environmentSlug) {@@ -154,6 +155,11 @@ export default defineComponent({name: t("common.version-control"),path: "/setting/version-control",});+ } else if (schemaReviewPolicySlug) {+ list.push({+ name: t("schema-review-policy.title"),+ path: "/setting/schema-review-policy",+ });}if (currentRoute.value.meta.title) {diff --git a/frontend/src/components/DatabaseSchemaReview/SchemaReviewConfig.vue b/frontend/src/components/DatabaseSchemaReview/SchemaReviewConfig.vuenew file mode 100644index 0000000000..74decc9c8e--- /dev/null+++ b/frontend/src/components/DatabaseSchemaReview/SchemaReviewConfig.vue@@ -0,0 +1,140 @@+<template>+ <div>+ <SchemaReviewTemplates+ :required="true"+ v-if="selectRuleList.length === 0"+ :template-list="templateList"+ :title="$t('schema-review-policy.create.basic-info.choose-template')"+ @select="(index) => onTemplateApply(index)"+ />+ <div class="mb-5" v-if="selectRuleList.length > 0">+ <div+ class="flex cursor-pointer items-center px-2 text-indigo-500"+ @click="state.openTemplate = !state.openTemplate"+ >+ <heroicons-solid:chevron-right+ class="w-5 h-5 transform transition-all"+ :class="state.openTemplate ? 'rotate-90' : ''"+ />+ <span class="ml-1 text-sm font-medium">+ {{ $t("schema-review-policy.create.configure-rule.change-template") }}+ </span>+ </div>+ <SchemaReviewTemplates+ v-if="state.openTemplate"+ :required="false"+ :template-list="templateList"+ :selected-template-index="selectedTemplateIndex"+ @select="(index) => onTemplateApply(index)"+ class="mx-8 mt-5"+ />+ </div>+ <div :class="selectRuleList.length > 0 ? 'border-b-1 border-gray-200' : ''">+ <ul role="list" class="divide-y divide-gray-200">+ <li v-for="rule in selectRuleList" :key="rule.type">+ <SchemaRuleConfig+ :selected-rule="rule"+ :active="rule.type === state.activeRuleType"+ @activate="onRuleActivate"+ @level-change="(level) => onLevelChange(rule, level)"+ @payload-change="(val) => onPayloadChange(rule, val)"+ />+ </li>+ </ul>+ </div>+ </div>+</template>++<script lang="ts" setup>+import { PropType, reactive } from "vue";+import {+ RuleType,+ RuleLevel,+ RuleTemplate,+ RuleTemplatePayload,+ SchemaReviewPolicyTemplate,+} from "../../types/schemaSystem";++interface LocalState {+ activeRuleType: RuleType | null;+ openTemplate: boolean;+}++const props = defineProps({+ selectRuleList: {+ required: true,+ type: Object as PropType<RuleTemplate[]>,+ },+ templateList: {+ required: true,+ type: Object as PropType<SchemaReviewPolicyTemplate[]>,+ },+ selectedTemplateIndex: {+ required: true,+ type: Number,+ },+});++const emit = defineEmits(["apply-template", "change"]);++const state = reactive<LocalState>({+ activeRuleType: null,+ openTemplate: false,+});++const onTemplateApply = (index: number) => {+ emit("apply-template", index);+ state.activeRuleType = null;+};++const onRuleActivate = (type: RuleType) => {+ if (type === state.activeRuleType) {+ state.activeRuleType = null;+ } else {+ state.activeRuleType = type;+ }+};++const onPayloadChange = (rule: RuleTemplate, data: (string | string[])[]) => {+ if (!rule.componentList) {+ return;+ }++ const newRule: RuleTemplate = {+ ...rule,+ componentList: rule.componentList.reduce((list, component, index) => {+ let val = data[index];+ switch (component.payload.type) {+ case "STRING_ARRAY":+ list.push({+ ...component,+ payload: {+ ...component.payload,+ value: data[index] as string[],+ },+ });+ break;+ default:+ list.push({+ ...component,+ payload: {+ ...component.payload,+ value: data[index] as string,+ },+ });+ break;+ }+ return list;+ }, [] as RuleTemplatePayload[]),+ };++ emit("change", newRule);+};++const onLevelChange = (rule: RuleTemplate, level: RuleLevel) => {+ emit("change", {+ ...rule,+ level,+ });+};+</script>diff --git a/frontend/src/components/DatabaseSchemaReview/SchemaReviewCreation.vue b/frontend/src/components/DatabaseSchemaReview/SchemaReviewCreation.vuenew file mode 100644index 0000000000..4f70016653--- /dev/null+++ b/frontend/src/components/DatabaseSchemaReview/SchemaReviewCreation.vue@@ -0,0 +1,346 @@+<template>+ <div>+ <BBStepTab+ class="my-4"+ :step-item-list="STEP_LIST"+ :allow-next="allowNext"+ :finish-title="$t(`common.confirm-and-${reviewId ? 'update' : 'add'}`)"+ @try-change-step="tryChangeStep"+ @try-finish="tryFinishSetup"+ @cancel="onCancel"+ >+ <template #0>+ <SchemaReviewInfo+ :name="state.name"+ :selected-environment="state.selectedEnvironment"+ :available-environment-list="availableEnvironmentList"+ :template-list="TEMPLATE_LIST"+ :selected-template-index="state.templateIndex"+ :is-edit="!!reviewId"+ @select-template="tryApplyTemplate"+ @name-change="(val) => (state.name = val)"+ @env-change="(env) => onEnvChange(env)"+ class="py-5"+ />+ </template>+ <template #1>+ <SchemaReviewConfig+ class="py-5"+ :select-rule-list="state.selectedRuleList"+ :template-list="TEMPLATE_LIST"+ :selected-template-index="state.templateIndex"+ @change="onRuleChange"+ @apply-template="tryApplyTemplate"+ />+ </template>+ <template #2>+ <SchemaReviewPreview+ :name="state.name"+ :is-preview-step="true"+ :selected-rule-list="state.selectedRuleList"+ :selected-environment="state.selectedEnvironment"+ class="py-5"+ />+ </template>+ </BBStepTab>+ <BBAlert+ v-if="state.showAlertModal"+ style="CRITICAL"+ :ok-text="$t('common.confirm')"+ :title="+ $t('schema-review-policy.create.configure-rule.confirm-override-title')+ "+ :description="+ $t(+ 'schema-review-policy.create.configure-rule.confirm-override-description'+ )+ "+ @ok="+ () => {+ state.showAlertModal = false;+ state.ruleUpdated = false;+ onTemplateApply(state.pendingApplyTemplateIndex);+ }+ "+ @cancel="state.showAlertModal = false"+ >+ </BBAlert>+ </div>+</template>++<script lang="ts" setup>+import { reactive, computed, withDefaults } from "vue";+import { useI18n } from "vue-i18n";+import { useRouter } from "vue-router";+import { BBStepTabItem } from "../../bbkit/types";+import {+ RuleType,+ ruleTemplateList,+ RuleLevel,+ Environment,+ RuleTemplate,+ SchemaReviewPolicyTemplate,+ convertRuleTemplateToPolicyRule,+} from "../../types";+import {+ useCurrentUser,+ pushNotification,+ useEnvironmentList,+ useSchemaSystemStore,+} from "@/store";+import { isOwner, isDBA } from "../../utils";++interface LocalState {+ currentStep: number;+ name: string;+ selectedEnvironment: Environment;+ selectedRuleList: RuleTemplate[];+ ruleUpdated: boolean;+ showAlertModal: boolean;+ templateIndex: number;+ pendingApplyTemplateIndex: number;+}++const props = withDefaults(+ defineProps<{+ reviewId?: number;+ name?: string;+ selectedEnvironment?: Environment;+ selectedRuleList?: RuleTemplate[];+ }>(),+ {+ reviewId: undefined,+ name: "",+ selectedEnvironment: undefined,+ selectedRuleList: () => [],+ }+);++const emit = defineEmits(["cancel"]);++const { t } = useI18n();+const router = useRouter();+const store = useSchemaSystemStore();+const currentUser = useCurrentUser();++const hasPermission = computed(() => {+ return isOwner(currentUser.value.role) || isDBA(currentUser.value.role);+});++const getRuleListWithLevel = (+ typeList: RuleType[],+ level: RuleLevel+): RuleTemplate[] => {+ return typeList.reduce((res, type) => {+ const rule = ruleTemplateList.find((r) => r.type === type);+ if (!rule) {+ return res;+ }++ res.push({+ ...rule,+ level,+ });+ return res;+ }, [] as RuleTemplate[]);+};++// TODO: i18n+const TEMPLATE_LIST: SchemaReviewPolicyTemplate[] = [+ {+ name: "Schema review for Prod",+ imagePath: new URL("../../assets/plan-enterprise.png", import.meta.url)+ .href,+ ruleList: [+ ...getRuleListWithLevel(["engine.mysql.use-innodb"], RuleLevel.ERROR),+ ...getRuleListWithLevel(+ [+ "naming.table",+ "naming.column",+ "naming.index.pk",+ "naming.index.uk",+ "naming.index.idx",+ ],+ RuleLevel.WARNING+ ),+ ...getRuleListWithLevel(+ [+ "query.select.no-select-all",+ "query.where.require",+ "query.where.no-leading-wildcard-like",+ "table.require-pk",+ ],+ RuleLevel.ERROR+ ),+ ...getRuleListWithLevel(+ ["column.required", "column.no-null"],+ RuleLevel.WARNING+ ),+ ],+ },+ {+ name: "Schema review for Dev",+ imagePath: new URL("../../assets/plan-free.png", import.meta.url).href,+ ruleList: [+ ...getRuleListWithLevel(["engine.mysql.use-innodb"], RuleLevel.ERROR),+ ...getRuleListWithLevel(+ [+ "naming.table",+ "naming.column",+ "naming.index.pk",+ "naming.index.uk",+ "naming.index.idx",+ "query.select.no-select-all",+ "query.where.require",+ "query.where.no-leading-wildcard-like",+ ],+ RuleLevel.WARNING+ ),+ ...getRuleListWithLevel(["table.require-pk"], RuleLevel.ERROR),+ ...getRuleListWithLevel(+ ["column.required", "column.no-null"],+ RuleLevel.WARNING+ ),+ ],+ },+];++const BASIC_INFO_STEP = 0;+const CONFIGURE_RULE_STEP = 1;+const PREVIEW_STEP = 2;+const ROUTE_NAME = "setting.workspace.schema-review-policy";+const DEFAULT_TEMPLATE_INDEX = 0;++const STEP_LIST: BBStepTabItem[] = [+ { title: t("schema-review-policy.create.basic-info.name") },+ { title: t("schema-review-policy.create.configure-rule.name") },+ { title: t("schema-review-policy.create.preview.name") },+];++const state = reactive<LocalState>({+ currentStep: BASIC_INFO_STEP,+ name:+ props.name ||+ t("schema-review-policy.create.basic-info.display-name-default"),+ selectedEnvironment: props.selectedEnvironment,+ selectedRuleList: props.selectedRuleList.length+ ? [...props.selectedRuleList]+ : [...TEMPLATE_LIST[DEFAULT_TEMPLATE_INDEX].ruleList],+ ruleUpdated: false,+ showAlertModal: false,+ templateIndex: props.reviewId ? -1 : DEFAULT_TEMPLATE_INDEX,+ pendingApplyTemplateIndex: -1,+});++const availableEnvironmentList = computed((): Environment[] => {+ const environmentList = useEnvironmentList(["NORMAL"]);++ const filteredList = store.availableEnvironments(+ environmentList.value,+ props.reviewId+ );++ return filteredList;+});++const onCancel = () => {+ if (props.reviewId) {+ emit("cancel");+ } else {+ router.push({+ name: ROUTE_NAME,+ });+ }+};++const allowNext = computed((): boolean => {+ switch (state.currentStep) {+ case BASIC_INFO_STEP:+ return (+ !!state.name &&+ state.selectedRuleList.length > 0 &&+ !!state.selectedEnvironment+ );+ case CONFIGURE_RULE_STEP:+ return state.selectedRuleList.length > 0;+ case PREVIEW_STEP:+ return true;+ }+ return false;+});++const tryChangeStep = (+ oldStep: number,+ newStep: number,+ allowChangeCallback: () => void+) => {+ state.currentStep = newStep;+ allowChangeCallback();+};++const tryFinishSetup = (allowChangeCallback: () => void) => {+ if (!hasPermission.value) {+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("schema-review-policy.no-permission"),+ });+ }+ const review = {+ name: state.name,+ environmentId: state.selectedEnvironment?.id,+ ruleList: state.selectedRuleList.map((rule) =>+ convertRuleTemplateToPolicyRule(rule)+ ),+ };++ if (props.reviewId) {+ store.updateReviewPolicy(props.reviewId, review);+ } else {+ store.addReviewPolicy(review);+ }++ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t(+ `schema-review-policy.${props.reviewId ? "update" : "create"}-review`+ ),+ });++ allowChangeCallback();+ onCancel();+};++const onEnvChange = (env: Environment) => {+ state.selectedEnvironment = env;+};++const onTemplateApply = (index: number) => {+ if (index < 0 || index >= TEMPLATE_LIST.length) {+ return;+ }+ state.templateIndex = index;+ state.pendingApplyTemplateIndex = -1;+ state.selectedRuleList = [...TEMPLATE_LIST[index].ruleList];+};++const tryApplyTemplate = (index: number) => {+ if (state.ruleUpdated || props.reviewId) {+ state.showAlertModal = true;+ state.pendingApplyTemplateIndex = index;+ return;+ }+ onTemplateApply(index);+};++const onRuleChange = (rule: RuleTemplate) => {+ const index = state.selectedRuleList.findIndex((r) => r.type === rule.type);+ state.selectedRuleList = [+ ...state.selectedRuleList.slice(0, index),+ rule,+ ...state.selectedRuleList.slice(index + 1),+ ];+ state.ruleUpdated = true;+};+</script>diff --git a/frontend/src/components/DatabaseSchemaReview/SchemaReviewEmptyView.vue b/frontend/src/components/DatabaseSchemaReview/SchemaReviewEmptyView.vuenew file mode 100644index 0000000000..3c3d600b95--- /dev/null+++ b/frontend/src/components/DatabaseSchemaReview/SchemaReviewEmptyView.vue@@ -0,0 +1,27 @@+<template>+ <div class="bg-white rounded-lg px-5 py-6 sm:px-6">+ <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" />+ <h3 class="mt-2 font-medium text-gray-900">+ {{ $t("schema-review-policy.no-policy-set") }}+ </h3>+ <div class="mt-6">+ <button+ type="button"+ class="inline-flex items-center px-4 py-2 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"+ @click="$emit('create')"+ >+ {{ $t("schema-review-policy.add-review") }}+ </button>+ </div>+ </div>+ </div>+ </div>+</template>++<script lang="ts" setup>+defineEmits(["create"]);+</script>diff --git a/frontend/src/components/DatabaseSchemaReview/SchemaReviewInfo.vue b/frontend/src/components/DatabaseSchemaReview/SchemaReviewInfo.vuenew file mode 100644index 0000000000..0c1a1c4cf3--- /dev/null+++ b/frontend/src/components/DatabaseSchemaReview/SchemaReviewInfo.vue@@ -0,0 +1,172 @@+<template>+ <div class="space-y-9">+ <div>+ <label class="textlabel">+ {{ $t("schema-review-policy.create.basic-info.display-name") }}+ <span style="color: red">*</span>+ </label>+ <p class="mt-1 textinfolabel">+ {{ $t("schema-review-policy.create.basic-info.display-name-label") }}+ </p>+ <BBTextField+ class="mt-2 w-full"+ placeholder="Database review name"+ :value="name"+ @input="(e) => onNameChange(e)"+ />+ </div>+ <div>+ <label class="textlabel">+ {{ $t("schema-review-policy.create.basic-info.environments") }}+ <span style="color: red">*</span>+ </label>+ <p class="mt-1 textinfolabel mb-5">+ {{ $t("schema-review-policy.create.basic-info.environments-label") }}+ </p>+ <BBAttention+ v-if="availableEnvironmentList.length === 0"+ :style="'WARN'"+ :title="$t('common.environment')"+ :description="+ $t(+ 'schema-review-policy.create.basic-info.no-available-environment-desc'+ )+ "+ class="mb-5"+ />+ <div class="flex flex-wrap gap-x-3">+ <div+ v-for="env in environmentList"+ :key="env.id"+ :class="[+ 'flex items-center',+ env.disabled+ ? 'cursor-not-allowed text-gray-400'+ : 'cursor-pointer text-gray-600',+ ]"+ >+ <input+ type="radio"+ :id="`${env.id}`"+ :value="env.id"+ :disabled="env.disabled"+ :checked="env.id === selectedEnvironment?.id"+ @change="$emit('env-change', env)"+ class="h-4 w-4 border-gray-300 rounded text-indigo-600 focus:ring-indigo-500"+ :class="env.disabled ? 'cursor-not-allowed' : 'cursor-pointer'"+ />+ <label+ :for="`${env.id}`"+ class="ml-2 items-center text-sm"+ :class="env.disabled ? 'cursor-not-allowed' : 'cursor-pointer'"+ >+ {{ env.displayName }}+ </label>+ </div>+ </div>+ </div>+ <div>+ <div class="mt-5" v-if="isEdit">+ <div+ class="flex cursor-pointer items-center text-indigo-500"+ @click="state.openTemplate = !state.openTemplate"+ >+ <heroicons-solid:chevron-right+ class="w-5 h-5 transform transition-all"+ :class="state.openTemplate ? 'rotate-90' : ''"+ />+ <span class="ml-l text-sm font-medium">+ {{+ $t("schema-review-policy.create.configure-rule.change-template")+ }}+ </span>+ </div>+ <SchemaReviewTemplates+ v-if="state.openTemplate"+ :required="false"+ :template-list="templateList"+ :selected-template-index="selectedTemplateIndex"+ @select="(index) => $emit('select-template', index)"+ class="mx-5 mt-5"+ />+ </div>+ <SchemaReviewTemplates+ v-else+ :required="true"+ :template-list="templateList"+ :selected-template-index="selectedTemplateIndex"+ :title="$t('schema-review-policy.create.basic-info.choose-template')"+ @select="(index) => $emit('select-template', index)"+ />+ </div>+ </div>+</template>++<script lang="ts" setup>+import { PropType, reactive, computed } from "vue";+import { useSchemaSystemStore, useEnvironmentList } from "@/store";+import { Environment, SchemaReviewPolicyTemplate } from "../../types";+import { environmentName } from "../../utils";++interface LocalEnvironment extends Environment {+ disabled: boolean;+ displayName: string;+}++interface LocalState {+ openTemplate: boolean;+}++const props = defineProps({+ name: {+ required: true,+ type: String,+ },+ selectedEnvironment: {+ required: false,+ default: undefined,+ type: Object as PropType<Environment>,+ },+ availableEnvironmentList: {+ required: true,+ type: Array as PropType<Environment[]>,+ },+ templateList: {+ required: true,+ type: Object as PropType<SchemaReviewPolicyTemplate[]>,+ },+ selectedTemplateIndex: {+ required: true,+ type: Number,+ },+ isEdit: {+ required: true,+ type: Boolean,+ },+});++const emit = defineEmits(["name-change", "env-change", "select-template"]);++const state = reactive<LocalState>({+ openTemplate: false,+});++const store = useSchemaSystemStore();++const environmentList = computed((): LocalEnvironment[] => {+ const environmentList = useEnvironmentList(["NORMAL"]);+ const availableIdSet = new Set(+ props.availableEnvironmentList.map((env) => env.id)+ );++ return environmentList.value.map((env) => ({+ ...env,+ disabled: !availableIdSet.has(env.id),+ displayName: environmentName(env),+ }));+});++const onNameChange = (event: Event) => {+ emit("name-change", (<HTMLInputElement>event.target).value);+};+</script>diff --git a/frontend/src/components/DatabaseSchemaReview/SchemaReviewPreview.vue b/frontend/src/components/DatabaseSchemaReview/SchemaReviewPreview.vuenew file mode 100644index 0000000000..476883f0dc--- /dev/null+++ b/frontend/src/components/DatabaseSchemaReview/SchemaReviewPreview.vue@@ -0,0 +1,134 @@+<template>+ <div class="flex gap-x-20">+ <aside class="hidden lg:block">+ <div class="space-y-6">+ <h1 class="text-left text-2xl font-semibold">Rules</h1>+ <fieldset v-for="(category, index) in categoryList" :key="index">+ <div class="block text-sm font-medium text-gray-900">+ {{+ $t(`schema-review-policy.category.${category.id.toLowerCase()}`)+ }}+ </div>+ <div+ v-for="(rule, ruleIndex) in category.ruleList"+ :key="ruleIndex"+ class="pt-2 flex items-center text-sm group"+ >+ <a+ :href="`#${rule.type.replace(/\./g, '-')}`"+ class="text-gray-600 hover:underline cursor-pointer"+ >+ {{ rule.type }}+ </a>+ </div>+ </fieldset>+ </div>+ </aside>+ <div class="flex-1">+ <div class="mb-5" v-if="name">+ <h1 class="text-left text-3xl font-bold mb-2">+ {{ name }}+ </h1>+ </div>+ <div v-if="selectedEnvironment" class="flex flex-wrap gap-x-3 mb-9">+ <span class="font-semibold">{{ $t("common.environment") }}</span>+ <BBBadge+ :text="environmentName(selectedEnvironment)"+ :can-remove="false"+ />+ </div>+ <BBAttention+ v-else-if="isPreviewStep"+ class="my-5"+ :style="`WARN`"+ :title="+ $t('schema-review-policy.create.basic-info.no-linked-environments')+ "+ />+ <div v-for="category in categoryList" :key="category.id" class="pb-4">+ <a+ :href="`#${category.id.replace(/\./g, '-')}`"+ :id="category.id.replace(/\./g, '-')"+ class="text-left text-2xl text-indigo-600 font-semibold hover:underline"+ >+ {{ $t(`schema-review-policy.category.${category.id.toLowerCase()}`) }}+ </a>+ <div v-for="rule in category.ruleList" :key="rule.type" class="py-4">+ <div class="sm:flex sm:items-center sm:space-x-4">+ <a+ :href="`#${rule.type.replace(/\./g, '-')}`"+ :id="rule.type.replace(/\./g, '-')"+ class="text-left text-xl hover:underline whitespace-nowrap"+ >+ {{ rule.type }}+ </a>+ <div class="mt-3 flex items-center space-x-2 sm:mt-0">+ <SchemaRuleLevelBadge :level="rule.level" />+ <BBBadge+ :text="$t(`engine.${rule.engine.toLowerCase()}`)"+ :can-remove="false"+ />+ </div>+ </div>+ <p class="py-2 text-gray-400">{{ rule.description }}</p>+ <ul role="list" class="space-y-4 list-disc list-inside">+ <li+ v-for="(component, i) in rule.componentList"+ :key="i"+ class="leading-8"+ >+ {{ component.title }}:+ <span+ v-if="+ component.payload.type === 'STRING' ||+ component.payload.type === 'TEMPLATE'+ "+ class="bg-gray-100 rounded text-sm font-semibold p-2"+ >+ {{ component.payload.value ?? component.payload.default }}+ </span>+ <div+ v-else-if="component.payload.type === 'STRING_ARRAY'"+ class="flex flex-wrap gap-3 ml-5 mt-3"+ >+ <span+ v-for="(val, j) in component.payload.value ??+ component.payload.default"+ :key="`${i}-${j}`"+ class="bg-gray-100 rounded text-sm font-semibold p-2"+ >+ {{ val }}+ </span>+ </div>+ </li>+ </ul>+ </div>+ </div>+ </div>+ </div>+</template>++<script lang="ts" setup>+import { computed } from "vue";+import { RuleTemplate, convertToCategoryList, Environment } from "../../types";+import { environmentName } from "../../utils";++const props = withDefaults(+ defineProps<{+ name?: string;+ isPreviewStep?: boolean;+ selectedEnvironment?: Environment;+ selectedRuleList?: RuleTemplate[];+ }>(),+ {+ name: "",+ isPreviewStep: false,+ selectedEnvironment: undefined,+ selectedRuleList: () => [],+ }+);++const categoryList = computed(() => {+ return convertToCategoryList(props.selectedRuleList);+});+</script>diff --git a/frontend/src/components/DatabaseSchemaReview/components/SchemaReviewCard.vue b/frontend/src/components/DatabaseSchemaReview/components/SchemaReviewCard.vuenew file mode 100644index 0000000000..f7a5bb80aa--- /dev/null+++ b/frontend/src/components/DatabaseSchemaReview/components/SchemaReviewCard.vue@@ -0,0 +1,85 @@+<template>+ <div+ class="divide-y divide-block-border border border-block-border rounded-sm"+ >+ <div class="flex py-2 px-4 justify-between">+ <div class="flex flex-row space-x-2 items-center">+ <h3 class="text-lg leading-6 font-medium text-main">+ {{ review.name }}+ </h3>+ </div>+ <button+ type="button"+ class="btn-normal py-2 px-4"+ @click.prevent="emit('click', review)"+ >+ {{ $t("common.view") }}+ </button>+ </div>+ <div class="border-t border-block-border">+ <dl class="divide-y divide-block-border">+ <div class="grid grid-cols-4 gap-4 px-4 py-2 items-center">+ <dt class="text-sm font-medium text-control-light">+ {{ $t("common.environment") }}+ </dt>+ <dd class="mt-1 flex gap-x-2 text-sm text-main col-span-2">+ <BBBadge+ v-if="review.environmentId"+ :text="envStore.getEnvironmentNameById(review.environmentId)"+ :can-remove="false"+ />+ <span class="text-yellow-700" v-else>+ {{+ $t(+ "schema-review-policy.create.basic-info.no-linked-environments"+ )+ }}+ </span>+ </dd>+ </div>+ <div class="grid grid-cols-4 gap-4 px-4 py-2 items-center">+ <dt class="text-sm font-medium text-control-light">+ {{ $t("common.created-at") }}+ </dt>+ <dd class="mt-1 flex text-sm text-main col-span-2">+ {{ humanizeTs(review.createdTs) }}+ </dd>+ </div>+ <div class="grid grid-cols-4 gap-4 px-4 py-2 items-center">+ <dt class="text-sm font-medium text-control-light">+ {{ $t("common.updated-at") }}+ </dt>+ <dd class="mt-1 flex text-sm text-main col-span-2">+ {{ humanizeTs(review.updatedTs) }}+ </dd>+ </div>+ <div class="grid grid-cols-4 gap-4 px-4 py-2 items-center">+ <dt class="text-sm font-medium text-control-light">+ {{ $t("common.creator") }}+ </dt>+ <dd class="mt-1 flex text-sm text-main col-span-2">+ {{ review.creator.name }}+ </dd>+ </div>+ </dl>+ </div>+ </div>+</template>++<script lang="ts" setup>+import { PropType } from "vue";+import { useRouter } from "vue-router";+import { DatabaseSchemaReviewPolicy } from "../../../types/schemaSystem";+import { useEnvironmentStore } from "@/store";++const props = defineProps({+ review: {+ required: true,+ type: Object as PropType<DatabaseSchemaReviewPolicy>,+ },+});+const emit = defineEmits(["click"]);++const router = useRouter();+const envStore = useEnvironmentStore();+</script>diff --git a/frontend/src/components/DatabaseSchemaReview/components/SchemaReviewCategoryTabFilter.vue b/frontend/src/components/DatabaseSchemaReview/components/SchemaReviewCategoryTabFilter.vuenew file mode 100644index 0000000000..6a93510769--- /dev/null+++ b/frontend/src/components/DatabaseSchemaReview/components/SchemaReviewCategoryTabFilter.vue@@ -0,0 +1,78 @@+<template>+ <BBTabFilter+ :tab-item-list="tabItemList"+ :selected-index="state.selectedIndex"+ @select-index="+ (index) => {+ state.selectedIndex = index;+ $emit('select', index == 0 ? null : categoryList[index - 1].id);+ }+ "+ />+</template>++<script lang="ts" setup>+import { computed, reactive, PropType, watch } from "vue";+import { BBTabFilterItem } from "../../../bbkit/types";+import { useI18n } from "vue-i18n";+import { CategoryType } from "../../../types/schemaSystem";++export interface CategoryFilterItem {+ id: CategoryType;+ name: string;+}++interface LocalState {+ selectedIndex: number;+}++const props = defineProps({+ selected: {+ required: false,+ default: undefined,+ type: String,+ },+ categoryList: {+ required: true,+ type: Object as PropType<CategoryFilterItem[]>,+ },+});++const emit = defineEmits(["select"]);++const { t } = useI18n();++const getSelectedIndex = (): number => {+ return props.selected+ ? props.categoryList.findIndex((c) => c.id === props.selected) + 1+ : 0;+};+const state = reactive<LocalState>({+ selectedIndex: getSelectedIndex(),+});++watch(+ () => props.selected,+ () => {+ state.selectedIndex = getSelectedIndex();+ }+);++const tabItemList = computed((): BBTabFilterItem[] => {+ const list: BBTabFilterItem[] = [+ {+ title: t("common.all"),+ alert: false,+ },+ ];+ list.push(+ ...props.categoryList.map((category) => {+ return {+ title: category.name,+ alert: false,+ };+ })+ );+ return list;+});+</script>diff --git a/frontend/src/components/DatabaseSchemaReview/components/SchemaReviewTemplates.vue b/frontend/src/components/DatabaseSchemaReview/components/SchemaReviewTemplates.vuenew file mode 100644index 0000000000..598a071eab--- /dev/null+++ b/frontend/src/components/DatabaseSchemaReview/components/SchemaReviewTemplates.vue@@ -0,0 +1,58 @@+<template>+ <div>+ <p class="textlabel" v-if="title">+ {{ title }}+ <span v-if="required" style="color: red">*</span>+ </p>+ <div+ class="flex flex-col sm:flex-row justify-start items-center gap-x-10 gap-y-10 mt-4"+ >+ <div+ v-for="(template, index) in templateList"+ :key="template.name"+ class="relative border border-gray-300 hover:bg-gray-100 rounded-lg p-6 transition-all flex flex-col justify-center items-center w-full sm:max-w-xs"+ :class="+ index == selectedTemplateIndex+ ? 'bg-gray-100'+ : 'bg-transparent cursor-pointer'+ "+ @click="$emit('select', index)"+ >+ <img class="h-24" :src="template.imagePath" alt="" />+ <span class="text-lg lg:text-xl mt-4">{{ template.name }}</span>+ <heroicons-solid:check-circle+ v-if="index == selectedTemplateIndex"+ class="w-7 h-7 text-gray-500 absolute top-3 left-3"+ />+ </div>+ </div>+ </div>+</template>++<script lang="ts" setup>+import { PropType } from "vue";+import { SchemaReviewPolicyTemplate } from "../../../types/schemaSystem";++const props = defineProps({+ templateList: {+ required: true,+ type: Object as PropType<SchemaReviewPolicyTemplate[]>,+ },+ selectedTemplateIndex: {+ required: false,+ default: -1,+ type: Number,+ },+ title: {+ required: false,+ default: "",+ type: String,+ },+ required: {+ required: true,+ type: Boolean,+ },+});++const emit = defineEmits(["select"]);+</script>diff --git a/frontend/src/components/DatabaseSchemaReview/components/SchemaRuleConfig.vue b/frontend/src/components/DatabaseSchemaReview/components/SchemaRuleConfig.vuenew file mode 100644index 0000000000..9ed527442e--- /dev/null+++ b/frontend/src/components/DatabaseSchemaReview/components/SchemaRuleConfig.vue@@ -0,0 +1,178 @@+<template>+ <div>+ <div+ class="flex justify-center items-center py-4 px-2 group cursor-pointer hover:bg-gray-100"+ :class="active ? 'bg-gray-100' : ''"+ @click="$emit('activate', selectedRule.type)"+ >+ <heroicons-solid:chevron-right+ class="w-5 h-5 transform transition-all"+ :class="active ? 'rotate-90' : ''"+ />++ <div class="flex-1 flex flex-col ml-3">+ <div class="flex mb-2 items-center space-x-2">+ <h1 class="text-base font-semibold text-gray-900">+ {{ selectedRule.type }}+ </h1>+ <BBBadge+ :text="$t(`engine.${selectedRule.engine.toLowerCase()}`)"+ :can-remove="false"+ />+ <SchemaRuleLevelBadge :level="selectedRule.level" />+ </div>+ <div class="text-sm text-gray-400">+ {{ selectedRule.description }}+ </div>+ </div>+ </div>+ <div v-if="active" class="px-10 py-5 text-sm">+ <div class="mb-7">+ <p class="mb-3">{{ $t("schema-review-policy.error-level.name") }}</p>+ <div class="flex gap-x-3">+ <div+ v-for="(level, index) in LEVEL_LIST"+ :key="index"+ class="flex items-center"+ >+ <input+ :id="`level-${level}`"+ :value="level"+ type="radio"+ :checked="level === selectedRule.level"+ @input="emit('level-change', level)"+ class="h-4 w-4 border-gray-300 rounded text-indigo-600 focus:ring-indigo-500"+ />+ <label+ :for="`level-${level}`"+ class="ml-2 items-center text-sm text-gray-600"+ >+ {{+ $t(`schema-review-policy.error-level.${level.toLowerCase()}`)+ }}+ </label>+ </div>+ </div>+ </div>+ <div+ v-for="(config, index) in selectedRule.componentList"+ :key="index"+ class="mb-7"+ >+ <p class="mb-3">+ {{ config.title }}+ </p>+ <input+ v-if="config.payload.type == 'STRING'"+ v-model="state.payload[index]"+ type="text"+ class="shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-full border-gray-300 rounded-md"+ :placeholder="config.payload.default"+ />+ <div+ v-else-if="+ config.payload.type == 'STRING_ARRAY' &&+ Array.isArray(state.payload[index])+ "+ >+ <div class="flex flex-wrap gap-4 mb-4">+ <BBBadge+ v-for="(val, i) in state.payload[index]"+ :key="`${index}-${i}`"+ :text="val"+ @remove="() => removeFromList(index, val)"+ />+ </div>+ <input+ type="text"+ pattern="[a-z]+"+ class="shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-full border-gray-300 rounded-md"+ placeholder="Input the value then press enter to add"+ @keyup.enter="(e) => pushToList(index, e)"+ />+ </div>+ <InputWithTemplate+ v-else-if="config.payload.type == 'TEMPLATE'"+ :template-list="config.payload.templateList"+ :value="getStringPayload(index)"+ @change="(val) => (state.payload[index] = val)"+ />+ </div>+ </div>+ </div>+</template>++<script lang="ts" setup>+import { reactive, PropType, watch } from "vue";+import {+ LEVEL_LIST,+ RuleTemplate,+ RuleTemplatePayload,+} from "../../../types/schemaSystem";++type PayloadValueList = (string | string[])[];+interface LocalState {+ payload: PayloadValueList;+}++const initStatePayload = (+ componentList: RuleTemplatePayload[] | undefined+): PayloadValueList => {+ return (componentList ?? []).reduce((res, component) => {+ res.push(component.payload.value ?? component.payload.default);+ return res;+ }, [] as PayloadValueList);+};++const props = defineProps({+ selectedRule: {+ required: true,+ type: Object as PropType<RuleTemplate>,+ },+ active: {+ require: true,+ type: Boolean,+ },+});++const emit = defineEmits(["activate", "payload-change", "level-change"]);++const state = reactive<LocalState>({+ payload: initStatePayload(props.selectedRule.componentList),+});++watch(+ () => state.payload,+ (val) => emit("payload-change", val),+ { deep: true }+);++const removeFromList = (i: number, val: any) => {+ if (!Array.isArray(state.payload[i])) {+ return;+ }++ const values = state.payload[i] as string[];+ const index = values.indexOf(val);+ if (index < 0) {+ return;+ }++ state.payload[i] = [...values.slice(0, index), ...values.slice(index + 1)];+};++const pushToList = (i: number, e: any) => {+ if (!Array.isArray(state.payload[i])) {+ return;+ }++ const val = e.target.value.trim();+ (state.payload[i] as string[]).push(val);++ e.target.value = "";+};++const getStringPayload = (i: number): string => {+ return state.payload[i] as string;+};+</script>diff --git a/frontend/src/components/DatabaseSchemaReview/components/SchemaRuleLevelBadge.vue b/frontend/src/components/DatabaseSchemaReview/components/SchemaRuleLevelBadge.vuenew file mode 100644index 0000000000..e826172f9b--- /dev/null+++ b/frontend/src/components/DatabaseSchemaReview/components/SchemaRuleLevelBadge.vue@@ -0,0 +1,31 @@+<template>+ <BBBadge+ :text="$t(`schema-review-policy.error-level.${level.toLowerCase()}`)"+ :can-remove="false"+ :style="style"+ />+</template>++<script lang="ts" setup>+import { PropType, computed } from "vue";+import { RuleLevel } from "../../../types/schemaSystem";+import { BBAttentionStyle } from "../../../bbkit/types";++const props = defineProps({+ level: {+ required: true,+ type: String as PropType<RuleLevel>,+ },+});++const style = computed((): BBAttentionStyle => {+ switch (props.level) {+ case RuleLevel.ERROR:+ return "CRITICAL";+ case RuleLevel.WARNING:+ return "WARN";+ default:+ return "INFO";+ }+});+</script>diff --git a/frontend/src/components/InputWithTemplate/InputWithTemplate.vue b/frontend/src/components/InputWithTemplate/InputWithTemplate.vueindex f74323b53c..b3f2f6d940 100644--- a/frontend/src/components/InputWithTemplate/InputWithTemplate.vue+++ b/frontend/src/components/InputWithTemplate/InputWithTemplate.vue@@ -2,7 +2,7 @@<div class="border border-gray-300 rounded"><div class="flex flex-wrap gap-4 p-3 bg-gray-50 rounded"><div- v-for="template in templates"+ v-for="template in templateList":key="template.id"class="px-4 py-1 rounded text-sm font-sm font-normal border border-gray-300 bg-gray-100 cursor-pointer tooltip-wrapper"@click="() => onTemplateAdd(template)"@@ -66,7 +66,7 @@ const props = defineProps({default: "",type: String,},- templates: {+ templateList: {require: true,default: () => [],type: Array as PropType<Template[]>,@@ -75,7 +75,7 @@ const props = defineProps({const emit = defineEmits(["change"]);-const templateInputs = getTemplateInputs(props.value, props.templates);+const templateInputs = getTemplateInputs(props.value, props.templateList);let inputData = "";if (diff --git a/frontend/src/components/InputWithTemplate/utils.ts b/frontend/src/components/InputWithTemplate/utils.tsindex d7af8f31ff..a33f3d5f15 100644--- a/frontend/src/components/InputWithTemplate/utils.ts+++ b/frontend/src/components/InputWithTemplate/utils.ts@@ -11,12 +11,12 @@ const TEMPLATE_BRACKET_RIGHT = "}}";// "{{abc{{}}{{template}}}}" -> [{value: "{{abc{{}}", type: "string"}, {value: "template", type: "template"}, {value: "}}", type: "string"}]export const getTemplateInputs = (value: string,- templates: Template[]+ templateList: Template[]): TemplateInput[] => {let start = 0;let end = 0;const res: TemplateInput[] = [];- const templateSet = new Set<string>(templates.map((t) => t.id));+ const templateSet = new Set<string>(templateList.map((t) => t.id));while (end <= value.length - 1) {if (diff --git a/frontend/src/locales/en.yml b/frontend/src/locales/en.ymlindex 72f401701f..188e35f8ea 100644--- a/frontend/src/locales/en.yml+++ b/frontend/src/locales/en.yml@@ -1,6 +1,6 @@common:when: When- view: view+ view: Viewyou: yougeneral: Generalslack: Slack@@ -100,6 +100,7 @@ common:new: Newadd: Addconfirm-and-add: Confirm and add+ confirm-and-update: Confirm and updatequery: Querytransfer: Transfermigration: Migration@@ -180,6 +181,8 @@ common:file-selector:type-limit: Only support {extension} filesize-limit: File size should less than {size} MiB+ enable: Enable+ disable: Disableerror-page:go-back-home: Go back homeanomaly-center: Anomaly Center@@ -1389,3 +1392,52 @@ subscription:title: Enterprise Planlabel: Early accessdesc: Large organization, has dedicated DBA group to manage database fleet+engine:+ mysql: MySQL+ common: Common+schema-review-policy:+ title: Schema Review+ no-policy-set: No schema review policy+ add-review: Add policy+ search-rule-name: Search rule name+ remove-review: Successfully removed the review policy.+ create-review: Successfully created the review policy.+ update-review: Successfully updated the review policy.+ filter: Filter+ no-permission: Only DBA or Owner has permission to create or update review policy.+ disable: Disable schema review policy+ enable: Enable schema review policy+ delete: Delete schema review policy+ category:+ engine: Engine+ naming: Naming+ query: Query+ table: Table+ column: Column+ error-level:+ name: Error Level+ error: Error+ warning: Warning+ disabled: Disabled+ create:+ breadcrumb: Create schema review policy+ basic-info:+ name: Basic info+ display-name: Display name+ display-name-default: Schema review policy+ display-name-label: >-+ A display name to help identifying among different review policies.+ environments: Environments+ environments-label: Apply the review policy to the selected environments. One environment can only link one policy.+ environments-select: Select environments+ no-linked-environments: No linked environment+ no-available-environment: No available environment+ no-available-environment-desc: No available environment. One environment can only link one schema review policy.+ choose-template: Choose template+ configure-rule:+ name: Configure rule+ change-template: Change the template+ confirm-override-title: Confirm change+ confirm-override-description: Your rules will be overridden+ preview:+ name: Previewdiff --git a/frontend/src/locales/zh-CN.yml b/frontend/src/locales/zh-CN.ymlindex aaf1acfbf9..6f1fc661c0 100644--- a/frontend/src/locales/zh-CN.yml+++ b/frontend/src/locales/zh-CN.yml@@ -100,6 +100,7 @@ common:new: 创建add: 添加confirm-and-add: 确认并添加+ confirm-and-update: 确认并更新query: 查询transfer: 转移migration: 迁移@@ -180,6 +181,8 @@ common:file-selector:type-limit: 仅支持 {extension} 类型的文件size-limit: 文件大小需小于 {size} MiB+ enable: 开启+ disable: 禁用error-page:go-back-home: 回到主页anomaly-center: 异常中心@@ -1218,3 +1221,51 @@ subscription:title: 企业版label: 预览版desc: 大型组织,有专属 DBA 团队来管理数据库+engine:+ mysql: MySQL+ common: 通用+schema-review-policy:+ title: Schema 审核策略+ no-policy-set: 没有 schema 审核策略+ add-review: 新增审核策略+ search-rule-name: 搜索规则名称+ remove-review: 审核策略已删除+ create-review: 审核策略已创建+ update-review: 审核策略已更新+ filter: 筛选+ no-permission: 仅 DBA 或所有者有权限创建或更新审核策略。+ disable: 停用审查策略+ enable: 开启审查策略+ delete: 删除审核策略+ category:+ engine: 引擎+ naming: 命名+ query: 查询+ table: 表+ column: 列+ error-level:+ name: 错误等级+ error: 错误+ warning: 警告+ disabled: 禁用+ create:+ breadcrumb: 创建审核策略+ basic-info:+ name: 基本信息+ display-name: 名称+ display-name-label: 用以区分不同审核策略的名称。+ display-name-default: Schema 审核策略+ environments: 环境+ environments-label: 将该审核策略应用于哪些环境。一个环境只能关联一个审核策略。+ environments-select: 选择环境+ no-linked-environments: 没有选择环境+ no-available-environment: 没有可供选择的环境+ no-available-environment-desc: 没有可供选择的环境。一个环境只能关联一个审核策略。+ choose-template: 选择模板+ configure-rule:+ name: 配置规则+ change-template: 更改模板+ confirm-override-title: 规则变更+ confirm-override-description: 之前的规则将会被覆盖+ preview:+ name: 预览diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.tsindex 8373a1d8e1..27edabcc6c 100644--- a/frontend/src/router/index.ts+++ b/frontend/src/router/index.ts@@ -40,6 +40,7 @@ import {useVCSStore,useProjectWebhookStore,useDataSourceStore,+ useSchemaSystemStore,useProjectStore,useTableStore,useSQLEditorStore,@@ -373,6 +374,41 @@ const routes: Array<RouteRecordRaw> = [import("../views/SettingWorkspaceIntegrationSlack.vue"),props: true,},+ {+ path: "schema-review-policy",+ name: "setting.workspace.schema-review-policy",+ meta: {+ title: () => t("schema-review-policy.title"),+ },+ component: () =>+ import("../views/SettingWorkspaceSchemaReview.vue"),+ props: true,+ },+ {+ path: "schema-review-policy/new",+ name: "setting.workspace.schema-review-policy.create",+ meta: {+ title: () => t("schema-review-policy.create.breadcrumb"),+ },+ component: () =>+ import("../views/SettingWorkspaceSchemaReviewCreate.vue"),+ props: true,+ },+ {+ path: "schema-review-policy/:schemaReviewPolicySlug",+ name: "setting.workspace.schema-review-policy.detail",+ meta: {+ title: (route: RouteLocationNormalized) => {+ const slug = route.params.schemaReviewPolicySlug as string;+ return useSchemaSystemStore().getReviewPolicyById(+ idFromSlug(slug)+ ).name;+ },+ },+ component: () =>+ import("../views/SettingWorkspaceSchemaReviewDetail.vue"),+ props: true,+ },],},{@@ -904,7 +940,8 @@ router.beforeEach((to, from, next) => {to.name === "workspace.environment" ||to.name === "sql-editor.home" ||(to.name?.toString().startsWith("setting") &&- to.name?.toString() != "setting.workspace.version-control.detail")+ to.name?.toString() != "setting.workspace.version-control.detail" &&+ to.name?.toString() != "setting.workspace.schema-review-policy.detail")) {next();return;@@ -931,6 +968,7 @@ router.beforeEach((to, from, next) => {const vcsSlug = routerSlug.vcsSlug;const connectionSlug = routerSlug.connectionSlug;const sheetSlug = routerSlug.sheetSlug;+ const schemaReviewPolicySlug = routerSlug.schemaReviewPolicySlug;if (principalId) {usePrincipalStore()@@ -1139,6 +1177,22 @@ router.beforeEach((to, from, next) => {return;}+ if (schemaReviewPolicySlug) {+ useSchemaSystemStore()+ .fetchReviewPolicyById(idFromSlug(schemaReviewPolicySlug))+ .then(() => {+ next();+ })+ .catch((error) => {+ next({+ name: "error.404",+ replace: false,+ });+ throw error;+ });+ return;+ }+if (connectionSlug) {const [, instanceId, , databaseId] = connectionSlug.split("_");useSQLEditorStore()diff --git a/frontend/src/store/modules/environment.ts b/frontend/src/store/modules/environment.tsindex 77e007127d..0e03879614 100644--- a/frontend/src/store/modules/environment.ts+++ b/frontend/src/store/modules/environment.ts@@ -15,6 +15,7 @@ import {} from "@/types";import { usePolicyStore } from "./policy";import { getPrincipalFromIncludedList } from "./principal";+import { environmentName } from "../../utils";function convert(environment: ResourceObject,@@ -68,6 +69,10 @@ export const useEnvironmentStore = defineStore("environment", {}return unknown("ENVIRONMENT") as Environment;},+ getEnvironmentNameById(environmentId: EnvironmentId): string {+ const env = this.getEnvironmentById(environmentId);+ return environmentName(env);+ },upsertEnvironmentList(environmentList: Environment[]) {for (const environment of environmentList) {const i = this.environmentList.findIndex(diff --git a/frontend/src/store/modules/index.ts b/frontend/src/store/modules/index.tsindex ce10725d50..971220acac 100644--- a/frontend/src/store/modules/index.ts+++ b/frontend/src/store/modules/index.ts@@ -38,3 +38,4 @@ export * from "./task";export * from "./uistate";export * from "./vcs";export * from "./view";+export * from "./schemaSystem";diff --git a/frontend/src/store/modules/router.ts b/frontend/src/store/modules/router.tsindex 33ae7e846a..16b8299bda 100644--- a/frontend/src/store/modules/router.ts+++ b/frontend/src/store/modules/router.ts@@ -167,6 +167,19 @@ export const useRouterStore = defineStore("router", {}}+ {+ // /setting/schema-review-policy/:schemaReviewPolicyId+ // Total 2 elements, 2nd element is the schema review id+ const schemaReviewComponents = currentRoute.path.match(+ "/setting/schema-review-policy/([0-9a-zA-Z_-]+)"+ ) || ["/", undefined];+ if (schemaReviewComponents[1]) {+ return {+ schemaReviewPolicySlug: schemaReviewComponents[1],+ };+ }+ }+{// /sql-editor/:connectionSlug/:sheetSlug// match this route firstdiff --git a/frontend/src/store/modules/schemaSystem.ts b/frontend/src/store/modules/schemaSystem.tsnew file mode 100644index 0000000000..53a1aa24f5--- /dev/null+++ b/frontend/src/store/modules/schemaSystem.ts@@ -0,0 +1,112 @@+import axios from "axios";+import {+ empty,+ unknown,+ SchemaReviewPolicyId,+ EMPTY_ID,+ UNKNOWN_ID,+ Environment,+ DatabaseSchemaReviewPolicy,+ DatabaseSchemaReviewPolicyCreate,+ DatabaseSchemaReviewPolicyPatch,+} from "../../types";+import { defineStore } from "pinia";+import { useCurrentUser } from "./auth";++interface SchemaSystemState {+ reviewPolicyList: DatabaseSchemaReviewPolicy[];+}++export const useSchemaSystemStore = defineStore("schemaSystem", {+ state: (): SchemaSystemState => ({+ reviewPolicyList: [],+ }),+ actions: {+ availableEnvironments(+ environmentList: Environment[],+ reviewPolicyId: SchemaReviewPolicyId | undefined+ ): Environment[] {+ const envMap = environmentList.reduce((map, env) => {+ map.set(env.id, env);+ return map;+ }, new Map<number, Environment>());++ for (const reviewPolicy of this.reviewPolicyList) {+ if (reviewPolicy.id === reviewPolicyId || !reviewPolicy.environmentId) {+ continue;+ }+ if (envMap.has(reviewPolicy.environmentId)) {+ envMap.delete(reviewPolicy.environmentId);+ }+ }++ return [...envMap.values()];+ },+ addReviewPolicy(review: DatabaseSchemaReviewPolicyCreate) {+ // TODO: need update after backend is implemented+ const user = useCurrentUser();+ this.reviewPolicyList.push({+ ...review,+ id: this.reviewPolicyList.length + 1,+ creator: user.value,+ updater: user.value,+ rowStatus: "NORMAL",+ createdTs: new Date().getTime() / 1000,+ updatedTs: new Date().getTime() / 1000,+ });+ },+ removeReviewPolicy(id: SchemaReviewPolicyId) {+ // TODO: need update after backend is implemented+ const index = this.reviewPolicyList.findIndex((g) => g.id === id);+ if (index < 0) {+ return;+ }+ this.reviewPolicyList = [+ ...this.reviewPolicyList.slice(0, index),+ ...this.reviewPolicyList.slice(index + 1),+ ];+ },+ updateReviewPolicy(+ id: SchemaReviewPolicyId,+ review: DatabaseSchemaReviewPolicyPatch+ ) {+ // TODO: need update after backend is implemented+ const index = this.reviewPolicyList.findIndex((g) => g.id === id);+ if (index < 0) {+ return;+ }+ this.reviewPolicyList = [+ ...this.reviewPolicyList.slice(0, index),+ {+ ...this.reviewPolicyList[index],+ ...review,+ },+ ...this.reviewPolicyList.slice(index + 1),+ ];+ },+ getReviewPolicyById(id: SchemaReviewPolicyId): DatabaseSchemaReviewPolicy {+ if (id === EMPTY_ID) {+ return empty("SCHEMA_REVIEW") as DatabaseSchemaReviewPolicy;+ }++ return (+ this.reviewPolicyList.find((g) => g.id === id) ||+ (unknown("SCHEMA_REVIEW") as DatabaseSchemaReviewPolicy)+ );+ },++ async fetchReviewPolicyList(): Promise<DatabaseSchemaReviewPolicy[]> {+ throw new Error("function haven't implement yet");+ },+ async fetchReviewPolicyById(+ id: SchemaReviewPolicyId+ ): Promise<DatabaseSchemaReviewPolicy> {+ // TODO: should remove this after the backend is implemented+ const review = this.getReviewPolicyById(id);+ if (review.id === UNKNOWN_ID || review.id === EMPTY_ID) {+ throw new Error(`review ${id} not found`);+ }+ return review;+ },+ },+});diff --git a/frontend/src/types/common.ts b/frontend/src/types/common.tsindex 5ab474b11a..61000776b7 100644--- a/frontend/src/types/common.ts+++ b/frontend/src/types/common.ts@@ -24,6 +24,7 @@ import { VCS } from "./vcs";import { DeploymentConfig } from "./deployment";import { DefaultApporvalPolicy } from "./policy";import { Sheet } from "./sheet";+import { DatabaseSchemaReviewPolicy } from "./schemaSystem";// System bot idexport const SYSTEM_BOT_ID = 1;@@ -72,6 +73,7 @@ export type RouterSlug = {vcsSlug?: string;connectionSlug?: string;sheetSlug?: string;+ schemaReviewPolicySlug?: string;};// Quick Action Type@@ -135,7 +137,8 @@ export type ResourceType =| "REPOSITORY"| "ANOMALY"| "DEPLOYMENT_CONFIG"- | "SHEET";+ | "SHEET"+ | "SCHEMA_REVIEW";interface ResourceMaker {(type: "PRINCIPAL"): Principal;@@ -161,6 +164,7 @@ interface ResourceMaker {(type: "ANOMALY"): Anomaly;(type: "DEPLOYMENT_CONFIG"): DeploymentConfig;(type: "SHEET"): Sheet;+ (type: "SCHEMA_REVIEW"): DatabaseSchemaReviewPolicy;}const makeUnknown = (type: ResourceType) => {@@ -485,6 +489,16 @@ const makeUnknown = (type: ResourceType) => {visibility: "PRIVATE",};+ const UNKNOWN_SCHEMA_REVIEW_POLICY: DatabaseSchemaReviewPolicy = {+ id: UNKNOWN_ID,+ name: "",+ creator: UNKNOWN_PRINCIPAL,+ updater: UNKNOWN_PRINCIPAL,+ createdTs: 0,+ updatedTs: 0,+ ruleList: [],+ };+switch (type) {case "PRINCIPAL":return UNKNOWN_PRINCIPAL;@@ -532,6 +546,8 @@ const makeUnknown = (type: ResourceType) => {return UNKNOWN_DEPLOYMENT_CONFIG;case "SHEET":return UNKNOWN_SHEET;+ case "SCHEMA_REVIEW":+ return UNKNOWN_SCHEMA_REVIEW_POLICY;}};export const unknown = makeUnknown as ResourceMaker;@@ -856,6 +872,16 @@ const makeEmpty = (type: ResourceType) => {visibility: "PRIVATE",};+ const EMPTY_SCHEMA_REVIEW_POLICY: DatabaseSchemaReviewPolicy = {+ id: EMPTY_ID,+ name: "",+ creator: EMPTY_PRINCIPAL,+ updater: EMPTY_PRINCIPAL,+ createdTs: 0,+ updatedTs: 0,+ ruleList: [],+ };+switch (type) {case "PRINCIPAL":return EMPTY_PRINCIPAL;@@ -903,6 +929,8 @@ const makeEmpty = (type: ResourceType) => {return EMPTY_DEPLOYMENT_CONFIG;case "SHEET":return EMPTY_SHEET;+ case "SCHEMA_REVIEW":+ return EMPTY_SCHEMA_REVIEW_POLICY;}};export const empty = makeEmpty as ResourceMaker;diff --git a/frontend/src/types/id.ts b/frontend/src/types/id.tsindex 0cf41e7a41..1966be8481 100644--- a/frontend/src/types/id.ts+++ b/frontend/src/types/id.ts@@ -70,6 +70,8 @@ export type CommandRegisterId = string;export type SheetId = IdType;+export type SchemaReviewPolicyId = IdType;+// This references to the object id, which can be used as a container.// Currently, only issue can be used a container.// The type is used by Activity and Messagediff --git a/frontend/src/types/index.ts b/frontend/src/types/index.tsindex dc19d35465..c5ec716d39 100644--- a/frontend/src/types/index.ts+++ b/frontend/src/types/index.ts@@ -39,3 +39,4 @@ export * from "./sqlEditor";export * from "./tab";export * from "./subscription";export * from "./sheet";+export * from "./schemaSystem";diff --git a/frontend/src/types/schemaSystem.ts b/frontend/src/types/schemaSystem.tsnew file mode 100644index 0000000000..6b04285fb7--- /dev/null+++ b/frontend/src/types/schemaSystem.ts@@ -0,0 +1,521 @@+import { SchemaReviewPolicyId } from "./id";+import { Principal } from "./principal";+import { RowStatus } from "./common";++// The engine type for rule template+export type SchemaRuleEngineType = "MYSQL" | "COMMON";++// The category type for rule template+export type CategoryType = "ENGINE" | "NAMING" | "QUERY" | "TABLE" | "COLUMN";++// The rule level+export enum RuleLevel {+ DISABLED = "DISABLED",+ ERROR = "ERROR",+ WARNING = "WARNING",+}++export const LEVEL_LIST = [+ RuleLevel.ERROR,+ RuleLevel.WARNING,+ RuleLevel.DISABLED,+];++// StringPayload is the string type payload configuration options and default value.+// Used by the frontend.+interface StringPayload {+ type: "STRING";+ default: string;+ value?: string;+}++// StringArrayPayload is the string array type payload configuration options and default value.+// Used by the frontend.+interface StringArrayPayload {+ type: "STRING_ARRAY";+ default: string[];+ value?: string[];+}++// TemplatePayload is the string template type payload configuration options and default value.+// Used by the frontend.+interface TemplatePayload {+ type: "TEMPLATE";+ default: string;+ templateList: { id: string; description?: string }[];+ value?: string;+}++// RuleTemplatePayload is the rule configuration options and default value.+// Used by the frontend.+export interface RuleTemplatePayload {+ title: string;+ description: string;+ payload: StringPayload | TemplatePayload | StringArrayPayload;+}++// The identifier for rule template+export type RuleType =+ | "engine.mysql.use-innodb"+ | "table.require-pk"+ | "naming.table"+ | "naming.column"+ | "naming.index.pk"+ | "naming.index.uk"+ | "naming.index.idx"+ | "column.required"+ | "column.no-null"+ | "query.select.no-select-all"+ | "query.where.require"+ | "query.where.no-leading-wildcard-like";++// The naming format rule payload.+// Used by the backend.+interface NamingFormatPayload {+ format: string;+}++// The naming format rule payload.+// Used by the backend.+interface RequiredColumnPayload {+ columnList: string[];+}++// The SchemaPolicyRule stores the rule configuration by users.+// Used by the backend+export interface SchemaPolicyRule {+ type: RuleType;+ level: RuleLevel;+ payload?: NamingFormatPayload | RequiredColumnPayload;+}++// The API for schema review policy in backend.+// TODO: just use the existed Policy entity+export interface DatabaseSchemaReviewPolicy {+ id: SchemaReviewPolicyId;++ // Standard fields+ creator: Principal;+ createdTs: number;+ updater: Principal;+ updatedTs: number;+ rowStatus: RowStatus;++ // Domain specific fields+ name: string;+ ruleList: SchemaPolicyRule[];+ environmentId: number;+}++// DatabaseSchemaReviewPolicyCreate is the API message for create review policy.+// TODO: just use the existed PolicyUpsert entity+export interface DatabaseSchemaReviewPolicyCreate {+ // Domain specific fields+ name: string;+ ruleList: SchemaPolicyRule[];+ environmentId: number;+}++// DatabaseSchemaReviewPolicyPatch is the API message for patch review policy.+// TODO: just use the existed PolicyUpsert entity+export type DatabaseSchemaReviewPolicyPatch = {+ // Domain specific fields+ name?: string;+ ruleList?: SchemaPolicyRule[];+ environmentId?: number;+ rowStatus?: RowStatus;+};++// RuleTemplate is the rule template. Used by the frontend+export interface RuleTemplate {+ type: RuleType;+ category: CategoryType;+ engine: SchemaRuleEngineType;+ description: string;+ componentList: RuleTemplatePayload[];+ level: RuleLevel;+}++// SchemaReviewPolicyTemplate is the rule template set+export interface SchemaReviewPolicyTemplate {+ name: string;+ imagePath: string;+ ruleList: RuleTemplate[];+}++// RULE_TEMPLATE_PAYLOAD_MAP is the relationship mapping for the rule type and payload.+// Used by frontend to get different rule payload configurations.+export const RULE_TEMPLATE_PAYLOAD_MAP: Map<RuleType, RuleTemplatePayload[]> =+ new Map([+ [+ "naming.table",+ [+ {+ title: "Table name format",+ description: "",+ payload: {+ type: "STRING",+ default: "^[a-z]+(_[a-z]+)?$",+ },+ },+ ],+ ],+ [+ "naming.column",+ [+ {+ title: "Column name format",+ description: "",+ payload: {+ type: "STRING",+ default: "^[a-z]+(_[a-z]+)?$",+ },+ },+ ],+ ],+ [+ "naming.index.pk",+ [+ {+ title: "Primary key name format",+ description: "",+ payload: {+ type: "TEMPLATE",+ default: "^pk_{{table}}_{{column_list}}$",+ templateList: [+ {+ id: "table",+ description: "The table name",+ },+ {+ id: "column_list",+ description: "Index column names, joined by _",+ },+ ],+ },+ },+ ],+ ],+ [+ "naming.index.uk",+ [+ {+ title: "Unique key name format",+ description: "",+ payload: {+ type: "TEMPLATE",+ default: "^uk_{{table}}_{{column_list}}$",+ templateList: [+ {+ id: "table",+ description: "The table name",+ },+ {+ id: "column_list",+ description: "Index column names, joined by _",+ },+ ],+ },+ },+ ],+ ],+ [+ "naming.index.idx",+ [+ {+ title: "Index name format",+ description: "",+ payload: {+ type: "TEMPLATE",+ default: "^idx_{{table}}_{{column_list}}$",+ templateList: [+ {+ id: "table",+ description: "The table name",+ },+ {+ id: "column_list",+ description: "Index column names, joined by _",+ },+ ],+ },+ },+ ],+ ],+ [+ "column.required",+ [+ {+ title: "Required column names",+ description: "",+ payload: {+ type: "STRING_ARRAY",+ default: [+ "id",+ "created_ts",+ "updated_ts",+ "creator_id",+ "updater_id",+ ],+ },+ },+ ],+ ],+ ]);++// ruleTemplateList stores the default value for each rule template+// TODO: i18n+export const ruleTemplateList: RuleTemplate[] = [+ {+ type: "engine.mysql.use-innodb",+ category: "ENGINE",+ engine: "MYSQL",+ description: "Require InnoDB as the storage engine.",+ level: RuleLevel.ERROR,+ componentList: [],+ },+ {+ type: "table.require-pk",+ category: "TABLE",+ engine: "COMMON",+ description: "Require the table to have a primary key.",+ level: RuleLevel.ERROR,+ componentList: [],+ },+ {+ type: "naming.table",+ category: "NAMING",+ engine: "COMMON",+ description: "Enforce the table name format. Default snake_lower_case.",+ componentList: RULE_TEMPLATE_PAYLOAD_MAP.get("naming.table") ?? [],+ level: RuleLevel.ERROR,+ },+ {+ type: "naming.column",+ category: "NAMING",+ engine: "COMMON",+ description: "Enforce the column name format. Default snake_lower_case.",+ componentList: RULE_TEMPLATE_PAYLOAD_MAP.get("naming.column") ?? [],+ level: RuleLevel.ERROR,+ },+ {+ type: "naming.index.pk",+ category: "NAMING",+ engine: "COMMON",+ description: "Enforce the primary key name format.",+ componentList: RULE_TEMPLATE_PAYLOAD_MAP.get("naming.index.pk") ?? [],+ level: RuleLevel.ERROR,+ },+ {+ type: "naming.index.uk",+ category: "NAMING",+ engine: "COMMON",+ description: "Enforce the unique key name format.",+ componentList: RULE_TEMPLATE_PAYLOAD_MAP.get("naming.index.uk") ?? [],+ level: RuleLevel.ERROR,+ },+ {+ type: "naming.index.idx",+ category: "NAMING",+ engine: "COMMON",+ description: "Enforce the index name format.",+ componentList: RULE_TEMPLATE_PAYLOAD_MAP.get("naming.index.idx") ?? [],+ level: RuleLevel.ERROR,+ },+ {+ type: "column.required",+ category: "COLUMN",+ engine: "COMMON",+ description: "Enforce the required columns in each table.",+ componentList: RULE_TEMPLATE_PAYLOAD_MAP.get("column.required") ?? [],+ level: RuleLevel.ERROR,+ },+ {+ type: "column.no-null",+ category: "COLUMN",+ engine: "COMMON",+ description: "Columns cannot have NULL value.",+ level: RuleLevel.ERROR,+ componentList: [],+ },+ {+ type: "query.select.no-select-all",+ category: "QUERY",+ engine: "COMMON",+ description: "Disallow 'SELECT *'.",+ level: RuleLevel.ERROR,+ componentList: [],+ },+ {+ type: "query.where.require",+ category: "QUERY",+ engine: "COMMON",+ description: "Require 'WHERE' clause.",+ level: RuleLevel.ERROR,+ componentList: [],+ },+ {+ type: "query.where.no-leading-wildcard-like",+ category: "QUERY",+ engine: "COMMON",+ description:+ "Disallow leading '%' in LIKE, e.g. LIKE foo = '%x' is not allowed.",+ level: RuleLevel.ERROR,+ componentList: [],+ },+];++interface RuleCategory {+ id: CategoryType;+ ruleList: RuleTemplate[];+}++// convertToCategoryList will reduce RuleTemplate list to RuleCategory list.+export const convertToCategoryList = (+ ruleList: RuleTemplate[]+): RuleCategory[] => {+ const categoryOrder: Map<CategoryType, number> = new Map([+ ["ENGINE", 5],+ ["NAMING", 4],+ ["QUERY", 3],+ ["TABLE", 2],+ ["COLUMN", 1],+ ]);++ const dict = ruleList.reduce((dict, rule) => {+ if (!dict[rule.category]) {+ const id = rule.category.toLowerCase();+ dict[rule.category] = {+ id: rule.category,+ ruleList: [],+ };+ }+ dict[rule.category].ruleList.push(rule);+ return dict;+ }, {} as { [key: string]: RuleCategory });++ return Object.values(dict).sort(+ (c1, c2) =>+ (categoryOrder.get(c2.id as CategoryType) || 0) -+ (categoryOrder.get(c1.id as CategoryType) || 0)+ );+};++// The convertRuleTemplateToPolicyRule will convert the review policy rule to rule template for frontend useage.+// Will throw exception if we don't implement the payload handler for specific type of rule.+export const convertPolicyRuleToRuleTemplate = (+ policyRule: SchemaPolicyRule,+ ruleTemplate: RuleTemplate+): RuleTemplate => {+ if (policyRule.type !== ruleTemplate.type) {+ throw new Error(+ `The rule type is not same. policyRule:${ruleTemplate.type}, ruleTemplate:${ruleTemplate.type}`+ );+ }++ const res = { ...ruleTemplate, level: policyRule.level };++ if (ruleTemplate.componentList.length === 0) {+ return res;+ }++ switch (ruleTemplate.type) {+ case "naming.column":+ case "naming.table":+ const stringComponent = ruleTemplate.componentList[0];+ const namingRulepayload = {+ ...stringComponent.payload,+ value: (policyRule.payload as NamingFormatPayload).format,+ } as StringPayload;+ return {+ ...res,+ componentList: [+ {+ ...stringComponent,+ payload: namingRulepayload,+ },+ ],+ };+ case "naming.index.idx":+ case "naming.index.pk":+ case "naming.index.uk":+ const templateComponent = ruleTemplate.componentList[0];+ const indexRulePayload = {+ ...templateComponent.payload,+ value: (policyRule.payload as NamingFormatPayload).format,+ } as TemplatePayload;+ return {+ ...res,+ componentList: [+ {+ ...templateComponent,+ payload: indexRulePayload,+ },+ ],+ };+ case "column.required":+ const requiredColumnComponent = ruleTemplate.componentList[0];+ const requiredColumnPayload = {+ ...requiredColumnComponent.payload,+ value: (policyRule.payload as RequiredColumnPayload).columnList,+ } as StringArrayPayload;+ return {+ ...res,+ componentList: [+ {+ ...requiredColumnComponent,+ payload: requiredColumnPayload,+ },+ ],+ };+ }++ throw new Error(`Invalid rule ${ruleTemplate.type}`);+};++// The convertRuleTemplateToPolicyRule will convert rule template to review policy rule for backend useage.+// Will throw exception if we don't implement the payload handler for specific type of rule.+export const convertRuleTemplateToPolicyRule = (+ rule: RuleTemplate+): SchemaPolicyRule => {+ const base: SchemaPolicyRule = {+ type: rule.type,+ level: rule.level,+ };+ if (rule.componentList.length === 0) {+ return base;+ }++ switch (rule.type) {+ case "naming.column":+ case "naming.table":+ const stringPayload = rule.componentList[0].payload as StringPayload;+ return {+ ...base,+ payload: {+ format: stringPayload.value ?? stringPayload.default,+ },+ };+ case "naming.index.idx":+ case "naming.index.pk":+ case "naming.index.uk":+ const templatePayload = rule.componentList[0].payload as TemplatePayload;+ return {+ ...base,+ payload: {+ format: templatePayload.value ?? templatePayload.default,+ },+ };+ case "column.required":+ const stringArrayPayload = rule.componentList[0]+ .payload as StringArrayPayload;+ return {+ ...base,+ payload: {+ columnList: stringArrayPayload.value ?? stringArrayPayload.default,+ },+ };+ }++ throw new Error(`Invalid rule ${rule.type}`);+};diff --git a/frontend/src/utils/slug.ts b/frontend/src/utils/slug.tsindex 30ea14ba0b..fb97abd1ba 100644--- a/frontend/src/utils/slug.ts+++ b/frontend/src/utils/slug.ts@@ -9,6 +9,7 @@ import {Project,ProjectWebhook,VCS,+ DatabaseSchemaReviewPolicy,} from "../types";import { IdType } from "../types/id";@@ -84,6 +85,12 @@ export function vcsSlug(vcs: VCS): string {return [slug(vcs.name), vcs.id].join("-");}+export function schemaReviewPolicySlug(+ reviewPolicy: DatabaseSchemaReviewPolicy+): string {+ return [slug(reviewPolicy.name), reviewPolicy.id].join("-");+}+export function connectionSlug(database: Database): string {return [slug(database.instance.name),diff --git a/frontend/src/views/SettingSidebar.vue b/frontend/src/views/SettingSidebar.vueindex 9eebe0d227..c77f7c6330 100644--- a/frontend/src/views/SettingSidebar.vue+++ b/frontend/src/views/SettingSidebar.vue@@ -67,6 +67,12 @@class="outline-item group w-full flex items-center pl-11 pr-2 py-2">{{ $t("settings.sidebar.version-control") }}</router-link>+ <router-link+ v-if="isDev()"+ to="/setting/schema-review-policy"+ class="outline-item group w-full flex items-center pl-11 pr-2 py-2"+ >{{ $t("schema-review-policy.title") }}</router-link+ ><router-linkto="/setting/subscription"class="outline-item group w-full flex items-center pl-11 pr-2 py-2"@@ -104,6 +110,10 @@ export default defineComponent({default: "",type: String,},+ schemaReviewPolicySlug: {+ default: "",+ type: String,+ },},setup() {const routerStore = useRouterStore();diff --git a/frontend/src/views/SettingWorkspaceSchemaReview.vue b/frontend/src/views/SettingWorkspaceSchemaReview.vuenew file mode 100644index 0000000000..e7bef82f5b--- /dev/null+++ b/frontend/src/views/SettingWorkspaceSchemaReview.vue@@ -0,0 +1,71 @@+<template>+ <div class="mx-auto">+ <div v-if="store.reviewPolicyList.length > 0" class="space-y-6 my-5">+ <div class="flex justify-start mt-4" v-if="hasPermission">+ <div class="flex flex-col items-center w-28">+ <button+ class="btn-icon-primary p-3"+ @click.prevent="goToCreationView"+ >+ <heroicons-outline:plus-sm class="w-6 h-6" />+ </button>+ <h3 class="mt-1 text-base font-normal text-main tracking-tight">+ {{ $t("schema-review-policy.add-review") }}+ </h3>+ </div>+ </div>+ <template v-for="review in store.reviewPolicyList" :key="review.id">+ <SchemaReviewCard :review="review" @click="onClick" />+ </template>+ </div>+ <template v-else>+ <SchemaReviewEmptyView @create="goToCreationView" />+ </template>+ </div>+</template>++<script lang="ts" setup>+import { useRouter } from "vue-router";+import { useI18n } from "vue-i18n";+import {+ pushNotification,+ useSchemaSystemStore,+ useCurrentUser,+} from "@/store";+import { DatabaseSchemaReviewPolicy } from "../types/schemaSystem";+import { schemaReviewPolicySlug, isOwner, isDBA } from "../utils";+import { computed } from "vue";++const router = useRouter();+const store = useSchemaSystemStore();+const ROUTE_NAME = "setting.workspace.schema-review-policy";+const currentUser = useCurrentUser();+const { t } = useI18n();++const hasPermission = computed(() => {+ return isOwner(currentUser.value.role) || isDBA(currentUser.value.role);+});++const goToCreationView = () => {+ if (hasPermission.value) {+ router.push({+ name: `${ROUTE_NAME}.create`,+ });+ } else {+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("schema-review-policy.no-permission"),+ });+ }+};++const onClick = (review: DatabaseSchemaReviewPolicy) => {+ router.push({+ name: `${ROUTE_NAME}.detail`,+ params: {+ schemaReviewPolicySlug: schemaReviewPolicySlug(review),+ },+ });+};+</script>diff --git a/frontend/src/views/SettingWorkspaceSchemaReviewCreate.vue b/frontend/src/views/SettingWorkspaceSchemaReviewCreate.vuenew file mode 100644index 0000000000..88a4ba7094--- /dev/null+++ b/frontend/src/views/SettingWorkspaceSchemaReviewCreate.vue@@ -0,0 +1,5 @@+<template>+ <div class="my-4 space-y-4 divide-y divide-block-border">+ <SchemaReviewCreation :selected-rule-list="[]" />+ </div>+</template>diff --git a/frontend/src/views/SettingWorkspaceSchemaReviewDetail.vue b/frontend/src/views/SettingWorkspaceSchemaReviewDetail.vuenew file mode 100644index 0000000000..d9dc491561--- /dev/null+++ b/frontend/src/views/SettingWorkspaceSchemaReviewDetail.vue@@ -0,0 +1,387 @@+<template>+ <transition appear name="slide-from-bottom" mode="out-in">+ <SchemaReviewCreation+ v-if="state.editMode"+ :review-id="reviewPolicy.id"+ :name="reviewPolicy.name"+ :selected-environment="environment"+ :selected-rule-list="selectedRuleList"+ @cancel="state.editMode = false"+ />+ <div class="my-5" v-else>+ <div class="flex flex-col items-center justify-center md:flex-row">+ <h1 class="text-xl md:text-3xl font-semibold flex-1">+ {{ reviewPolicy.name }}+ </h1>+ <button+ v-if="hasPermission"+ type="button"+ class="btn-primary ml-5"+ @click="onEdit"+ >+ {{ $t("common.edit") }}+ </button>+ </div>+ <div class="flex flex-wrap gap-x-3 my-5" v-if="environment">+ <span class="font-semibold">{{ $t("common.environment") }}</span>+ <BBBadge :text="environment.name" :can-remove="false" />+ </div>+ <BBAttention+ v-else+ class="my-5"+ :style="`WARN`"+ :title="+ $t('schema-review-policy.create.basic-info.no-linked-environments')+ "+ />+ <div class="space-y-2 my-5">+ <span class="font-semibold">{{+ $t("schema-review-policy.filter")+ }}</span>+ <div class="flex flex-wrap gap-x-3">+ <span>{{ $t("common.database") }}:</span>+ <div+ v-for="engine in engineList"+ :key="engine.id"+ class="flex items-center"+ >+ <input+ type="checkbox"+ :id="engine.id"+ :value="engine.id"+ :checked="state.checkedEngine.has(engine.id)"+ @input="toggleCheckedEngine(engine.id)"+ class="h-4 w-4 border-gray-300 rounded text-indigo-600 focus:ring-indigo-500"+ />+ <label+ :for="engine.id"+ class="ml-2 items-center text-sm text-gray-600"+ >+ {{ $t(`engine.${engine.id.toLowerCase()}`) }}+ <span+ class="items-center px-2 py-0.5 rounded-full bg-gray-200 text-gray-800"+ >+ {{ engine.count }}+ </span>+ </label>+ </div>+ </div>+ <div class="flex flex-wrap gap-x-3">+ <span>{{ $t("schema-review-policy.error-level.name") }}:</span>+ <div+ v-for="level in errorLevelList"+ :key="level.id"+ class="flex items-center"+ >+ <input+ type="checkbox"+ :id="level.id"+ :value="level.id"+ :checked="state.checkedLevel.has(level.id)"+ @input="toggleCheckedLevel(level.id)"+ class="h-4 w-4 border-gray-300 rounded text-indigo-600 focus:ring-indigo-500"+ />+ <label+ :for="level.id"+ class="ml-2 items-center text-sm text-gray-600"+ >+ {{+ $t(`schema-review-policy.error-level.${level.id.toLowerCase()}`)+ }}+ <span+ class="items-center px-2 py-0.5 rounded-full bg-gray-200 text-gray-800"+ >+ {{ level.count }}+ </span>+ </label>+ </div>+ </div>+ </div>+ <div class="py-2 flex justify-between items-center mt-5">+ <SchemaReviewCategoryTabFilter+ :selected="state.selectedCategory"+ :category-list="categoryFilterList"+ @select="selectCategory"+ />+ <BBTableSearch+ ref="searchField"+ :placeholder="$t('schema-review-policy.search-rule-name')"+ @change-text="(text) => (state.searchText = text)"+ />+ </div>+ <SchemaReviewPreview+ :selected-rule-list="filteredSelectedRuleList"+ class="py-5"+ />+ <BBButtonConfirm+ v-if="reviewPolicy.rowStatus === 'NORMAL'"+ :style="'ARCHIVE'"+ :button-text="$t('schema-review-policy.disable')"+ confirm-description=""+ :ok-text="$t('common.disable')"+ :confirm-title="$t('common.disable') + ` '${reviewPolicy.name}'?`"+ :require-confirm="true"+ @confirm="onArchive"+ />+ <div class="flex gap-x-5" v-else>+ <BBButtonConfirm+ :style="'RESTORE'"+ :button-text="$t('schema-review-policy.enable')"+ confirm-description=""+ :ok-text="$t('common.enable')"+ :confirm-title="$t('common.enable') + ` '${reviewPolicy.name}'?`"+ :require-confirm="true"+ @confirm="onRestore"+ />+ <BBButtonConfirm+ :style="'DELETE'"+ :button-text="$t('schema-review-policy.delete')"+ :ok-text="$t('common.delete')"+ :confirm-title="$t('common.delete') + ` '${reviewPolicy.name}'?`"+ :require-confirm="true"+ @confirm="onRemove"+ />+ </div>+ </div>+ </transition>+</template>++<script lang="ts" setup>+import { computed, reactive } from "vue";+import { useI18n } from "vue-i18n";+import { useRouter } from "vue-router";+import { idFromSlug, environmentName, isOwner, isDBA } from "../utils";+import {+ RuleType,+ LEVEL_LIST,+ RuleLevel,+ RuleTemplate,+ DatabaseSchemaReviewPolicy,+ SchemaRuleEngineType,+ convertToCategoryList,+ ruleTemplateList,+ Environment,+ convertPolicyRuleToRuleTemplate,+} from "../types";+import {+ useCurrentUser,+ pushNotification,+ useEnvironmentStore,+ useSchemaSystemStore,+} from "@/store";+import { CategoryFilterItem } from "../components/DatabaseSchemaReview/components/SchemaReviewCategoryTabFilter.vue";++const props = defineProps({+ schemaReviewPolicySlug: {+ required: true,+ type: String,+ },+});++interface LocalState {+ searchText: string;+ selectedCategory?: string;+ editMode: boolean;+ checkedEngine: Set<SchemaRuleEngineType>;+ checkedLevel: Set<RuleLevel>;+}++const { t } = useI18n();+const store = useSchemaSystemStore();+const envStore = useEnvironmentStore();+const router = useRouter();+const currentUser = useCurrentUser();+const ROUTE_NAME = "setting.workspace.schema-review-policy";++const state = reactive<LocalState>({+ searchText: "",+ selectedCategory: router.currentRoute.value.query.category+ ? (router.currentRoute.value.query.category as string)+ : undefined,+ editMode: false,+ checkedEngine: new Set<SchemaRuleEngineType>(),+ checkedLevel: new Set<RuleLevel>(),+});++const hasPermission = computed(() => {+ return isOwner(currentUser.value.role) || isDBA(currentUser.value.role);+});++const reviewPolicy = computed((): DatabaseSchemaReviewPolicy => {+ return store.getReviewPolicyById(idFromSlug(props.schemaReviewPolicySlug));+});++const environment = computed((): Environment | undefined => {+ if (!reviewPolicy.value.environmentId) {+ return;+ }+ const env = envStore.getEnvironmentById(reviewPolicy.value.environmentId);+ return {+ ...env,+ name: environmentName(env),+ };+});++const ruleMap = ruleTemplateList.reduce((map, rule) => {+ map.set(rule.type, rule);+ return map;+}, new Map<RuleType, RuleTemplate>());++const selectedRuleList = computed((): RuleTemplate[] => {+ if (!reviewPolicy.value) {+ return [];+ }++ const ruleTemplateList: RuleTemplate[] = [];++ for (const policyRule of reviewPolicy.value.ruleList) {+ const rule = ruleMap.get(policyRule.type);+ if (!rule) {+ continue;+ }++ const data = convertPolicyRuleToRuleTemplate(policyRule, rule);+ if (data) {+ ruleTemplateList.push(data);+ }+ }++ return ruleTemplateList;+});++const engineList = computed(+ (): { id: SchemaRuleEngineType; count: number }[] => {+ const tmp = selectedRuleList.value.reduce((dict, rule) => {+ if (!dict[rule.engine]) {+ dict[rule.engine] = {+ id: rule.engine,+ count: 0,+ };+ }+ dict[rule.engine].count += 1;+ return dict;+ }, {} as { [id: string]: { id: SchemaRuleEngineType; count: number } });++ return Object.values(tmp);+ }+);++const errorLevelList = computed((): { id: RuleLevel; count: number }[] => {+ return LEVEL_LIST.map((level) => ({+ id: level,+ count: selectedRuleList.value.filter((rule) => rule.level === level).length,+ }));+});++const toggleCheckedEngine = (engine: SchemaRuleEngineType) => {+ if (state.checkedEngine.has(engine)) {+ state.checkedEngine.delete(engine);+ } else {+ state.checkedEngine.add(engine);+ }+};++const toggleCheckedLevel = (level: RuleLevel) => {+ if (state.checkedLevel.has(level)) {+ state.checkedLevel.delete(level);+ } else {+ state.checkedLevel.add(level);+ }+};++const categoryFilterList = computed((): CategoryFilterItem[] => {+ return convertToCategoryList(selectedRuleList.value).map((c) => ({+ id: c.id,+ name: t(`schema-review-policy.category.${c.id.toLowerCase()}`),+ }));+});++const selectCategory = (category: string) => {+ state.selectedCategory = category;+ if (category) {+ router.replace({+ name: `${ROUTE_NAME}.detail`,+ query: {+ category,+ },+ });+ } else {+ router.replace({+ name: `${ROUTE_NAME}.detail`,+ });+ }+};++const filteredSelectedRuleList = computed((): RuleTemplate[] => {+ return selectedRuleList.value.filter((selectedRule) => {+ if (+ !state.selectedCategory &&+ !state.searchText &&+ state.checkedEngine.size === 0 &&+ state.checkedLevel.size === 0+ ) {+ // Select "All"+ return true;+ }++ return (+ (!state.selectedCategory ||+ selectedRule.category === state.selectedCategory) &&+ (!state.searchText ||+ selectedRule.type+ .toLowerCase()+ .includes(state.searchText.toLowerCase())) &&+ (state.checkedEngine.size === 0 ||+ state.checkedEngine.has(selectedRule.engine)) &&+ (state.checkedLevel.size === 0 ||+ state.checkedLevel.has(selectedRule.level))+ );+ });+});++const onEdit = () => {+ state.editMode = true;+ state.searchText = "";+ state.selectedCategory = undefined;+};++const onArchive = () => {+ store.updateReviewPolicy(reviewPolicy.value.id, {+ rowStatus: "ARCHIVED",+ });+};++const onRestore = () => {+ store.updateReviewPolicy(reviewPolicy.value.id, {+ rowStatus: "NORMAL",+ });+};++const onRemove = () => {+ store.removeReviewPolicy(reviewPolicy.value.id);+ router.replace({+ name: ROUTE_NAME,+ });+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("schema-review-policy.remove-review"),+ });+};+</script>++<style scoped>+.slide-from-bottom-enter-active {+ transition: all 0.2s ease-in-out;+}++.slide-from-bottom-leave-active {+ transition: all 0.2s ease-in-out;+}++.slide-from-bottom-enter-from,+.slide-from-bottom-leave-to {+ transform: translateY(20px);+ opacity: 0;+}+</style>