Skip to content

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

feat(frontend): sql check for branching (#8400)

Liu Ji87d40b912dcc
diff --git a/frontend/src/components/Branch/BranchDetailView.vue b/frontend/src/components/Branch/BranchDetailView.vue
index a884009d22..1414be074d 100644
--- a/frontend/src/components/Branch/BranchDetailView.vue
+++ b/frontend/src/components/Branch/BranchDetailView.vue
@@ -71,7 +71,12 @@
</div>
</div>
</div>
- <div class="w-full flex flex-row justify-end gap-2">
+ <div class="flex-1 flex flex-row justify-end gap-2">
+ <SchemaDesignSQLCheckButton
+ class="justify-end"
+ :schema-design="schemaDesign"
+ />
+
<template v-if="!state.isEditing">
<NButton @click="handleEdit">{{ $t("common.edit") }}</NButton>
</template>
@@ -141,6 +146,7 @@ import {
import { projectV1Slug } from "@/utils";
import { getBaselineMetadataOfBranch } from "../SchemaEditorV1/utils/branch";
import MergeBranchPanel from "./MergeBranchPanel.vue";
+import SchemaDesignSQLCheckButton from "./SchemaDesignSQLCheckButton.vue";
import {
generateForkedBranchName,
mergeSchemaEditToMetadata,
diff --git a/frontend/src/components/Branch/SchemaDesignSQLCheckButton.vue b/frontend/src/components/Branch/SchemaDesignSQLCheckButton.vue
new file mode 100644
index 0000000000..07a0db2f41
--- /dev/null
+++ b/frontend/src/components/Branch/SchemaDesignSQLCheckButton.vue
@@ -0,0 +1,153 @@
+<template>
+ <SQLCheckButton
+ v-if="database"
+ :database="database"
+ :statement="statement"
+ :errors="errors"
+ class="justify-end"
+ >
+ <template #result="{ advices, isRunning }">
+ <SQLCheckSummary
+ v-if="advices !== undefined && !isRunning"
+ :database="database"
+ :advices="advices"
+ />
+ </template>
+ </SQLCheckButton>
+</template>
+
+<script lang="ts" setup>
+import { cloneDeep, debounce } from "lodash-es";
+import { computed, ref, watch } from "vue";
+import { useI18n } from "vue-i18n";
+import { SQLCheckButton, SQLCheckSummary } from "@/components/SQLCheck";
+import { schemaDesignServiceClient } from "@/grpcweb";
+import { useDatabaseV1Store, useSchemaEditorV1Store } from "@/store";
+import { DatabaseMetadata } from "@/types/proto/v1/database_service";
+import { SchemaDesign } from "@/types/proto/v1/schema_design_service";
+import { getBaselineMetadataOfBranch } from "../SchemaEditorV1/utils/branch";
+import { mergeSchemaEditToMetadata, validateDatabaseMetadata } from "./utils";
+
+const props = defineProps<{
+ schemaDesign: SchemaDesign;
+}>();
+const { t } = useI18n();
+const databaseStore = useDatabaseV1Store();
+const schemaEditorV1Store = useSchemaEditorV1Store();
+
+const database = computed(() => {
+ return databaseStore.getDatabaseByName(props.schemaDesign.baselineDatabase);
+});
+
+const sourceMetadata = computed(() => {
+ const branch = props.schemaDesign;
+
+ return getBaselineMetadataOfBranch(branch);
+});
+
+const editingMetadata = computed(() => {
+ const branchSchema = schemaEditorV1Store.resourceMap["branch"].get(
+ props.schemaDesign.name
+ );
+ if (!branchSchema) {
+ return undefined;
+ }
+ const baselineMetadata = getBaselineMetadataOfBranch(branchSchema.branch);
+ const metadata = mergeSchemaEditToMetadata(
+ branchSchema.schemaList,
+ cloneDeep(baselineMetadata)
+ );
+
+ return metadata;
+});
+
+const targetMetadata = ref<DatabaseMetadata>();
+const statement = ref("");
+const errors = ref<string[]>([]);
+
+const evaluateTargetMetadataAndDiff = async () => {
+ const metadata = editingMetadata.value;
+
+ const setState = (
+ metadata: DatabaseMetadata | undefined,
+ stmt: string,
+ errs: string[]
+ ) => {
+ targetMetadata.value = metadata;
+ statement.value = stmt;
+ errors.value = errs;
+ };
+
+ if (!metadata) {
+ setState(undefined, "", [t("schema-editor.message.invalid-schema")]);
+ return;
+ }
+ const validationMessages = validateDatabaseMetadata(metadata);
+ if (validationMessages.length > 0) {
+ setState(undefined, "", validationMessages);
+ return;
+ }
+
+ // Prepare to diff
+ setState(metadata, "", []);
+ const db = database.value;
+ const source = sourceMetadata.value;
+ const target = targetMetadata.value;
+ if (!db) return;
+ if (!source) return;
+ if (!target) return;
+
+ try {
+ const diffResponse = await schemaDesignServiceClient.diffMetadata(
+ {
+ sourceMetadata: source,
+ targetMetadata: target,
+ engine: db.instanceEntity.engine,
+ },
+ {
+ silent: true,
+ }
+ );
+ const diff = diffResponse.diff;
+ const errs = diff.length === 0 ? [t("schema-editor.nothing-changed")] : [];
+ setState(metadata, diff, errs);
+ } catch {
+ // The grpc error message is too long not readable. So we won't use it here.
+ setState(metadata, "", [t("schema-editor.message.invalid-schema")]);
+ }
+};
+
+watch(
+ editingMetadata,
+ (metadata) => {
+ if (!metadata) {
+ errors.value = [t("schema-editor.message.invalid-schema")];
+ } else {
+ errors.value = validateDatabaseMetadata(metadata);
+ }
+ },
+ {
+ immediate: true,
+ }
+);
+
+const watchKey = computed(() => {
+ return [
+ database.value?.name,
+ JSON.stringify(
+ DatabaseMetadata.toJSON(
+ sourceMetadata.value ?? DatabaseMetadata.fromPartial({})
+ )
+ ),
+ JSON.stringify(
+ DatabaseMetadata.toJSON(
+ editingMetadata.value ?? DatabaseMetadata.fromPartial({})
+ )
+ ),
+ ].join("\n");
+});
+
+evaluateTargetMetadataAndDiff();
+// Won't update too frequently since this costs pretty high.
+watch(watchKey, debounce(evaluateTargetMetadataAndDiff, 250));
+</script>
diff --git a/frontend/src/components/IssueV1/components/SQLCheckSection/SQLCheckBadge.vue b/frontend/src/components/IssueV1/components/SQLCheckSection/SQLCheckBadge.vue
index d89c526043..e9ddbde8a6 100644
--- a/frontend/src/components/IssueV1/components/SQLCheckSection/SQLCheckBadge.vue
+++ b/frontend/src/components/IssueV1/components/SQLCheckSection/SQLCheckBadge.vue
@@ -25,6 +25,7 @@
<SQLCheckPanel
v-if="showDetailPanel"
+ :database="database"
:advices="advices"
@close="showDetailPanel = false"
/>
@@ -33,8 +34,9 @@
<script setup lang="ts">
import { computed, ref } from "vue";
+import { SQLCheckPanel } from "@/components/SQLCheck";
import { Advice, Advice_Status } from "@/types/proto/v1/sql_service";
-import SQLCheckPanel from "./SQLCheckPanel.vue";
+import { databaseForTask, useIssueContext } from "../../logic";
const props = defineProps<{
isRunning: boolean;
@@ -45,8 +47,13 @@ defineEmits<{
(event: "click"): void;
}>();
+const { issue, selectedTask } = useIssueContext();
const showDetailPanel = ref(false);
+const database = computed(() => {
+ return databaseForTask(issue.value, selectedTask.value);
+});
+
const status = computed(() => {
const { isRunning, advices } = props;
if (isRunning) {
diff --git a/frontend/src/components/SQLCheck/SQLCheckButton.vue b/frontend/src/components/SQLCheck/SQLCheckButton.vue
index 6318c9bf94..01be527ef7 100644
--- a/frontend/src/components/SQLCheck/SQLCheckButton.vue
+++ b/frontend/src/components/SQLCheck/SQLCheckButton.vue
@@ -1,55 +1,63 @@
<template>
<div class="flex flex-row items-center gap-2">
- <slot name="result" :advices="advices" :is-running="isRunning">
- <div class="flex flex-col text-xs">
- <span>statement: {{ statement }}</span>
- <pre v-for="(advice, i) in advices" :key="i">{{
- Advice.toJSON(advice)
- }}</pre>
- </div>
- </slot>
+ <slot name="result" :advices="advices" :is-running="isRunning" />
- <NButton
- style="--n-padding: 0 14px 0 10px"
- :disabled="statement.trim().length === 0"
- :style="buttonStyle"
- v-bind="buttonProps"
- @click="runChecks"
- >
- <template #icon>
- <BBSpin v-if="isRunning" class="w-4 h-4" />
- <heroicons-outline:play v-else class="w-4 h-4" />
+ <NTooltip :disabled="!errors || errors.length === 0">
+ <template #trigger>
+ <NButton
+ style="--n-padding: 0 14px 0 10px"
+ :disabled="disabled"
+ :style="buttonStyle"
+ tag="div"
+ v-bind="buttonProps"
+ @click="runChecks"
+ >
+ <template #icon>
+ <BBSpin v-if="isRunning" class="w-4 h-4" />
+ <heroicons-outline:play v-else class="w-4 h-4" />
+ </template>
+ <template #default>
+ <template v-if="isRunning">
+ {{ $t("task.checking") }}
+ </template>
+ <template v-else>
+ {{ $t("task.run-checks") }}
+ </template>
+ </template>
+ </NButton>
</template>
<template #default>
- <template v-if="isRunning">
- {{ $t("task.checking") }}
- </template>
- <template v-else>
- {{ $t("task.run-checks") }}
- </template>
+ <ErrorList :errors="errors ?? []" />
</template>
- </NButton>
+ </NTooltip>
</div>
</template>
<script lang="ts" setup>
-import { ButtonProps, NButton } from "naive-ui";
-import { ref } from "vue";
+import { ButtonProps, NButton, NTooltip } from "naive-ui";
+import { computed, ref } from "vue";
import { CSSProperties } from "vue";
import { sqlServiceClient } from "@/grpcweb";
import { ComposedDatabase } from "@/types";
import { Advice } from "@/types/proto/v1/sql_service";
+import ErrorList from "../misc/ErrorList.vue";
const props = defineProps<{
statement: string;
database: ComposedDatabase;
buttonProps?: ButtonProps;
buttonStyle?: string | CSSProperties;
+ errors?: string[];
}>();
const isRunning = ref(false);
const advices = ref<Advice[]>();
+const disabled = computed(() => {
+ if (!props.statement) return true;
+ return props.errors && props.errors.length > 0;
+});
+
const runChecks = async () => {
const { statement, database } = props;
isRunning.value = true;
diff --git a/frontend/src/components/IssueV1/components/SQLCheckSection/SQLCheckDetail.vue b/frontend/src/components/SQLCheck/SQLCheckDetail.vue
similarity index 94%
rename from frontend/src/components/IssueV1/components/SQLCheckSection/SQLCheckDetail.vue
rename to frontend/src/components/SQLCheck/SQLCheckDetail.vue
index 086353af8d..44a22609ee 100644
--- a/frontend/src/components/IssueV1/components/SQLCheckSection/SQLCheckDetail.vue
+++ b/frontend/src/components/SQLCheck/SQLCheckDetail.vue
@@ -33,7 +33,7 @@
</div>
<div class="bb-grid-cell">
<div>
- <span>{{ row.advice.content }}</span>
+ <span>{{ row.content }}</span>
<template v-if="getActiveRule(row.advice.title as RuleType)">
<span
class="ml-1 normal-link"
@@ -71,11 +71,11 @@ import { computed, reactive } from "vue";
import { useI18n } from "vue-i18n";
import { BBGridColumn, BBGridRow, BBGrid } from "@/bbkit";
import { LocalizedSQLRuleErrorCodes } from "@/components/Issue/const";
-import { databaseForTask, useIssueContext } from "@/components/IssueV1/logic";
import { SQLRuleEditDialog } from "@/components/SQLReview/components";
import { PayloadValueType } from "@/components/SQLReview/components/RuleConfigComponents";
import { useReviewPolicyByEnvironmentId } from "@/store";
import {
+ ComposedDatabase,
GeneralErrorCode,
RuleTemplate,
RuleType,
@@ -103,6 +103,7 @@ type TableRow = {
advice: Advice;
category: string;
title: string;
+ content: string;
link: ErrorCodeLink | undefined;
};
@@ -112,6 +113,7 @@ type LocalState = {
};
const props = defineProps<{
+ database: ComposedDatabase;
advices: Advice[];
}>();
@@ -120,7 +122,6 @@ const state = reactive<LocalState>({
activeRule: undefined,
activeResultDefinition: undefined,
});
-const { issue, selectedTask } = useIssueContext();
const statusIconClass = (status: Advice_Status) => {
switch (status) {
@@ -189,11 +190,13 @@ const errorCodeLink = (advice: Advice): ErrorCodeLink | undefined => {
const tableRows = computed(() => {
return props.advices.map<TableRow>((advice) => {
const [category, title] = categoryAndTitle(advice);
+ const content = advice.content.trim();
const link = errorCodeLink(advice);
return {
advice,
category,
title,
+ content,
link,
};
});
@@ -226,13 +229,10 @@ const COLUMN_LIST = computed(() => {
return [STATUS, TITLE, CONTENT];
});
-const reviewPolicy = useReviewPolicyByEnvironmentId(
- computed(() => {
- const task = selectedTask.value;
- const database = databaseForTask(issue.value, task);
- return database.effectiveEnvironmentEntity.uid;
- })
+const environmentUID = computed(
+ () => props.database.effectiveEnvironmentEntity.uid
);
+const reviewPolicy = useReviewPolicyByEnvironmentId(environmentUID);
const getActiveRule = (type: RuleType): PreviewSQLReviewRule | undefined => {
const rule = reviewPolicy.value?.ruleList.find((rule) => rule.type === type);
if (!rule) {
diff --git a/frontend/src/components/IssueV1/components/SQLCheckSection/SQLCheckPanel.vue b/frontend/src/components/SQLCheck/SQLCheckPanel.vue
similarity index 77%
rename from frontend/src/components/IssueV1/components/SQLCheckSection/SQLCheckPanel.vue
rename to frontend/src/components/SQLCheck/SQLCheckPanel.vue
index 4e09b7e8a6..b4efaa2359 100644
--- a/frontend/src/components/IssueV1/components/SQLCheckSection/SQLCheckPanel.vue
+++ b/frontend/src/components/SQLCheck/SQLCheckPanel.vue
@@ -6,15 +6,17 @@
container-class="!pt-0 -mt-px"
@close="$emit('close')"
>
- <SQLCheckDetail :advices="advices" />
+ <SQLCheckDetail :database="database" :advices="advices" />
</BBModal>
</template>
<script setup lang="ts">
+import { ComposedDatabase } from "@/types";
import { Advice } from "@/types/proto/v1/sql_service";
import SQLCheckDetail from "./SQLCheckDetail.vue";
defineProps<{
+ database: ComposedDatabase;
advices: Advice[];
}>();
diff --git a/frontend/src/components/SQLCheck/SQLCheckSummary.vue b/frontend/src/components/SQLCheck/SQLCheckSummary.vue
new file mode 100644
index 0000000000..454ee58e22
--- /dev/null
+++ b/frontend/src/components/SQLCheck/SQLCheckSummary.vue
@@ -0,0 +1,61 @@
+<template>
+ <div v-if="summary.warningCount === 0 && summary.errorCount === 0">
+ <heroicons:check class="w-4 h-4 text-success" />
+ </div>
+ <NButton v-else quaternary size="small" @click="showDetailPanel = true">
+ <div class="inline-flex items-center gap-x-1">
+ <heroicons:exclamation-circle class="w-4 h-4 text-error" />
+ <span>{{ summary.errorCount }}</span>
+ <heroicons:exclamation-triangle class="w-4 h-4 text-warning" />
+ <span>{{ summary.warningCount }}</span>
+ </div>
+ </NButton>
+
+ <SQLCheckPanel
+ v-if="showDetailPanel"
+ :database="database"
+ :advices="advices"
+ @close="showDetailPanel = false"
+ />
+</template>
+
+<script setup lang="ts">
+import { NButton } from "naive-ui";
+import { computed, ref } from "vue";
+import { ComposedDatabase } from "@/types";
+import { Advice, Advice_Status } from "@/types/proto/v1/sql_service";
+import SQLCheckPanel from "./SQLCheckPanel.vue";
+
+type Summary = {
+ successCount: number;
+ warningCount: number;
+ errorCount: number;
+};
+
+const props = defineProps<{
+ database: ComposedDatabase;
+ advices: Advice[];
+}>();
+
+const showDetailPanel = ref(false);
+
+const summary = computed(() => {
+ const summary: Summary = {
+ successCount: 0,
+ warningCount: 0,
+ errorCount: 0,
+ };
+ props.advices.forEach((advice) => {
+ if (advice.status === Advice_Status.SUCCESS) {
+ summary.successCount++;
+ }
+ if (advice.status === Advice_Status.WARNING) {
+ summary.warningCount++;
+ }
+ if (advice.status === Advice_Status.ERROR) {
+ summary.errorCount++;
+ }
+ });
+ return summary;
+});
+</script>
diff --git a/frontend/src/components/SQLCheck/index.ts b/frontend/src/components/SQLCheck/index.ts
index 0daadef86c..fde01094ba 100644
--- a/frontend/src/components/SQLCheck/index.ts
+++ b/frontend/src/components/SQLCheck/index.ts
@@ -1,3 +1,5 @@
import SQLCheckButton from "./SQLCheckButton.vue";
+import SQLCheckPanel from "./SQLCheckPanel.vue";
+import SQLCheckSummary from "./SQLCheckSummary.vue";
-export { SQLCheckButton };
+export { SQLCheckButton, SQLCheckPanel, SQLCheckSummary };
diff --git a/frontend/src/components/misc/ErrorList.vue b/frontend/src/components/misc/ErrorList.vue
new file mode 100644
index 0000000000..da82a653fe
--- /dev/null
+++ b/frontend/src/components/misc/ErrorList.vue
@@ -0,0 +1,23 @@
+<template>
+ <ul
+ class="flex flex-col whitespace-nowrap"
+ :class="[errors.length > 1 && bullets && 'list-disc pl-4']"
+ >
+ <li v-for="(error, i) in errors" :key="i">
+ <slot name="prefix" />
+ {{ error }}
+ </li>
+ </ul>
+</template>
+
+<script setup lang="ts">
+withDefaults(
+ defineProps<{
+ errors: string[];
+ bullets?: boolean;
+ }>(),
+ {
+ bullets: true,
+ }
+);
+</script>
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 5d02597bea..cb6adf9736 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -2082,7 +2082,8 @@
"duplicated-column-name": "Duplicated column name",
"invalid-column-type": "Invalid column type",
"schema-not-found": "Schema not found",
- "failed-to-fetch-database-schema": "Failed to fetch database schema"
+ "failed-to-fetch-database-schema": "Failed to fetch database schema",
+ "invalid-schema": "Invalid schema"
},
"confirm-to-close": {
"title": "Confirm to close",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index aea4bc9218..01b81f1033 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -2078,7 +2078,8 @@
"duplicated-column-name": "Nombre de columna duplicado",
"invalid-column-type": "Tipo de columna inválido",
"schema-not-found": "Esquema no encontrado",
- "failed-to-fetch-database-schema": "Error al obtener el esquema de la base de datos"
+ "failed-to-fetch-database-schema": "Error al obtener el esquema de la base de datos",
+ "invalid-schema": "Esquema no válido"
},
"confirm-to-close": {
"title": "Confirmar para cerrar",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 400bcbf344..3ad5524e44 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -2078,7 +2078,8 @@
"duplicated-column-name": "重复的列名",
"invalid-column-type": "无效的列类型",
"schema-not-found": "找不到 Schema",
- "failed-to-fetch-database-schema": "请求数据库 Schema 失败"
+ "failed-to-fetch-database-schema": "请求数据库 Schema 失败",
+ "invalid-schema": "无效的 Schema"
},
"confirm-to-close": {
"title": "确定关闭?",