Skip to content

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

feat: sql check for schema editor (#8417)

Liu Jib8da13a97ef1
diff --git a/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vue b/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vue
index 796b0d76f8..1797676be6 100644
--- a/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vue
+++ b/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vue
@@ -6,31 +6,40 @@
@close="dismissModal"
>
<div
- class="w-full flex flex-row justify-start items-center border-b pl-1 border-b-gray-300"
+ class="w-full flex flex-row justify-between items-center border-b pl-1 border-b-gray-300"
>
- <button
- class="-mb-px px-3 leading-9 rounded-t-md flex items-center text-sm text-gray-500 border border-b-0 border-transparent cursor-pointer select-none outline-none"
- :class="
- state.selectedTab === 'schema-editor' &&
- 'bg-white !border-gray-300 text-gray-800'
- "
- @click="handleChangeTab('schema-editor')"
- >
- {{ $t("schema-editor.self") }}
- <div class="ml-1">
- <BBBetaBadge />
- </div>
- </button>
- <button
- class="-mb-px px-3 leading-9 rounded-t-md text-sm text-gray-500 border border-b-0 border-transparent cursor-pointer select-none outline-none"
- :class="
- state.selectedTab === 'raw-sql' &&
- 'bg-white !border-gray-300 text-gray-800'
- "
- @click="handleChangeTab('raw-sql')"
- >
- {{ $t("schema-editor.raw-sql") }}
- </button>
+ <div class="flex items-center flex-start">
+ <button
+ class="-mb-px px-3 leading-9 rounded-t-md flex items-center text-sm text-gray-500 border border-b-0 border-transparent cursor-pointer select-none outline-none"
+ :class="
+ state.selectedTab === 'schema-editor' &&
+ 'bg-white !border-gray-300 text-gray-800'
+ "
+ @click="handleChangeTab('schema-editor')"
+ >
+ {{ $t("schema-editor.self") }}
+ <div class="ml-1">
+ <BBBetaBadge />
+ </div>
+ </button>
+ <button
+ class="-mb-px px-3 leading-9 rounded-t-md text-sm text-gray-500 border border-b-0 border-transparent cursor-pointer select-none outline-none"
+ :class="
+ state.selectedTab === 'raw-sql' &&
+ 'bg-white !border-gray-300 text-gray-800'
+ "
+ @click="handleChangeTab('raw-sql')"
+ >
+ {{ $t("schema-editor.raw-sql") }}
+ </button>
+ </div>
+ <div class="flex items-center flex-end">
+ <SchemaEditorSQLCheckButton
+ :selected-tab="state.selectedTab"
+ :database-list="databaseList"
+ :edit-statement="state.editStatement"
+ />
+ </div>
</div>
<div class="w-full h-full max-h-full overflow-auto border-b mb-4">
<div
@@ -130,7 +139,6 @@
</template>
<script lang="ts" setup>
-import axios from "axios";
import dayjs from "dayjs";
import { cloneDeep, head, uniq } from "lodash-es";
import { computed, onMounted, PropType, reactive, ref, watch } from "vue";
@@ -149,8 +157,6 @@ import {
} from "@/store";
import {
ComposedDatabase,
- DatabaseEdit,
- DatabaseEditResult,
dialectOfEngineV1,
UNKNOWN_PROJECT_NAME,
unknownProject,
@@ -158,11 +164,6 @@ import {
import { Engine } from "@/types/proto/v1/common";
import { TenantMode } from "@/types/proto/v1/project_service";
import { allowGhostMigrationV1 } from "@/utils";
-import {
- checkHasSchemaChanges,
- diffSchema,
- mergeDiffResults,
-} from "@/utils/schemaEditor/diffSchema";
import { validateDatabaseEdit } from "@/utils/schemaEditor/validate";
import MonacoEditor from "../MonacoEditor";
import {
@@ -170,6 +171,8 @@ import {
validateDatabaseMetadata,
} from "../SchemaEditorV1/utils";
import GhostDialog from "./GhostDialog.vue";
+import SchemaEditorSQLCheckButton from "./SchemaEditorSQLCheckButton/SchemaEditorSQLCheckButton.vue";
+import { getDatabaseEditListWithSchemaEditor, postDatabaseEdit } from "./utils";
const MAX_UPLOAD_FILE_SIZE_MB = 1;
@@ -314,42 +317,6 @@ const handleSyncSQLFromSchemaEditor = async () => {
statementFromSchemaEditor.value = state.editStatement;
};
-const getDatabaseEditListWithSchemaEditor = () => {
- const databaseEditList: DatabaseEdit[] = [];
- for (const databaseSchema of Array.from(
- schemaEditorV1Store.resourceMap["database"].values()
- )) {
- const database = databaseSchema.database;
- for (const schema of databaseSchema.schemaList) {
- const originSchema = databaseSchema.originSchemaList.find(
- (originSchema) => originSchema.id === schema.id
- );
- if (!originSchema) {
- continue;
- }
-
- const diffSchemaResult = diffSchema(database.name, originSchema, schema);
- if (checkHasSchemaChanges(diffSchemaResult)) {
- const index = databaseEditList.findIndex(
- (edit) => String(edit.databaseId) === database.uid
- );
- if (index !== -1) {
- databaseEditList[index] = {
- databaseId: Number(database.uid),
- ...mergeDiffResults([diffSchemaResult, databaseEditList[index]]),
- };
- } else {
- databaseEditList.push({
- databaseId: Number(database.uid),
- ...diffSchemaResult,
- });
- }
- }
- }
- }
- return databaseEditList;
-};
-
const fetchDatabaseEditStatementMapWithSchemaEditor = async () => {
const databaseEditList = getDatabaseEditListWithSchemaEditor();
const databaseEditMap: Map<string, string> = new Map();
@@ -590,17 +557,6 @@ const generateIssueName = (
return issueNameParts.join(" ");
};
-const postDatabaseEdit = async (databaseEdit: DatabaseEdit) => {
- const resData = (
- await axios.post(
- `/api/database/${databaseEdit.databaseId}/edit`,
- databaseEdit
- )
- ).data;
- const databaseEditResult = resData.data.attributes as DatabaseEditResult;
- return databaseEditResult;
-};
-
watch(
() => getDatabaseEditListWithSchemaEditor(),
() => {
diff --git a/frontend/src/components/AlterSchemaPrepForm/SchemaEditorSQLCheckButton/SchemaEditorSQLCheckButton.vue b/frontend/src/components/AlterSchemaPrepForm/SchemaEditorSQLCheckButton/SchemaEditorSQLCheckButton.vue
new file mode 100644
index 0000000000..44025c2150
--- /dev/null
+++ b/frontend/src/components/AlterSchemaPrepForm/SchemaEditorSQLCheckButton/SchemaEditorSQLCheckButton.vue
@@ -0,0 +1,47 @@
+<template>
+ <SQLCheckButton
+ v-if="show"
+ :database="database"
+ :statement="statement"
+ :errors="errors"
+ :button-props="{
+ size: 'small',
+ }"
+ 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 { debounce } from "lodash-es";
+import { ref, toRefs, watch } from "vue";
+import { ComposedDatabase } from "@/types";
+import { useSchemaEditorSQLCheck } from "./useSchemaEditorSQLCheck";
+
+const props = defineProps<{
+ selectedTab: "raw-sql" | "schema-editor";
+ databaseList: ComposedDatabase[];
+ editStatement: string;
+}>();
+
+const { show, database, watchKey, getStatement } = useSchemaEditorSQLCheck(
+ toRefs(props)
+);
+const errors = ref<string[]>([]);
+const statement = ref("");
+
+const update = async () => {
+ const result = await getStatement();
+ errors.value = result.errors;
+ statement.value = result.statement;
+};
+
+watch(watchKey, debounce(update, 250));
+update();
+</script>
diff --git a/frontend/src/components/AlterSchemaPrepForm/SchemaEditorSQLCheckButton/index.ts b/frontend/src/components/AlterSchemaPrepForm/SchemaEditorSQLCheckButton/index.ts
new file mode 100644
index 0000000000..e33d3e7bb4
--- /dev/null
+++ b/frontend/src/components/AlterSchemaPrepForm/SchemaEditorSQLCheckButton/index.ts
@@ -0,0 +1,3 @@
+import SchemaEditorSQLCheckButton from "./SchemaEditorSQLCheckButton.vue";
+
+export default SchemaEditorSQLCheckButton;
diff --git a/frontend/src/components/AlterSchemaPrepForm/SchemaEditorSQLCheckButton/useSchemaEditorSQLCheck.ts b/frontend/src/components/AlterSchemaPrepForm/SchemaEditorSQLCheckButton/useSchemaEditorSQLCheck.ts
new file mode 100644
index 0000000000..76768f7410
--- /dev/null
+++ b/frontend/src/components/AlterSchemaPrepForm/SchemaEditorSQLCheckButton/useSchemaEditorSQLCheck.ts
@@ -0,0 +1,154 @@
+import { cloneDeep } from "lodash-es";
+import { Ref, computed } from "vue";
+import {
+ mergeSchemaEditToMetadata,
+ validateDatabaseMetadata,
+} from "@/components/SchemaEditorV1/utils";
+import { schemaDesignServiceClient } from "@/grpcweb";
+import { t } from "@/plugins/i18n";
+import { useDBSchemaV1Store, useSchemaEditorV1Store } from "@/store";
+import { ComposedDatabase } from "@/types";
+import { Engine } from "@/types/proto/v1/common";
+import {
+ getDatabaseEditListWithSchemaEditor,
+ postDatabaseEdit,
+} from "../utils";
+
+export const useSchemaEditorSQLCheck = (params: {
+ selectedTab: Ref<"raw-sql" | "schema-editor">;
+ databaseList: Ref<ComposedDatabase[]>;
+ editStatement: Ref<string>;
+}) => {
+ const { selectedTab, databaseList, editStatement } = params;
+ const schemaEditorV1Store = useSchemaEditorV1Store();
+ const dbSchemaV1Store = useDBSchemaV1Store();
+
+ const show = computed(() => {
+ // SQL Check is highly related to the databases' environments.
+ // By now we cannot handle mixed environments correctly.
+ // so we just support SQL Check when editing single database's schema.
+ return databaseList.value.length === 1;
+ });
+
+ const database = computed(() => {
+ return databaseList.value[0];
+ });
+
+ const watchKey = computed(() => {
+ if (selectedTab.value === "raw-sql") {
+ return editStatement.value;
+ } else {
+ return JSON.stringify(getDatabaseEditListWithSchemaEditor());
+ }
+ });
+
+ const fetchDatabaseEditStatement = async (): Promise<{
+ errors: string[];
+ statement: string;
+ }> => {
+ const databaseEditList = getDatabaseEditListWithSchemaEditor();
+ if (databaseEditList.length !== 1) {
+ return {
+ errors: [t("schema-editor.nothing-changed")],
+ statement: "",
+ };
+ }
+ const databaseEdit = databaseEditList[0];
+ const db = database.value;
+ // Use `SchemaDesignService.DiffMetadata` for MySQL as we only support MySQL for now.
+ if (db.instanceEntity.engine === Engine.MYSQL) {
+ const databaseSchema = schemaEditorV1Store.resourceMap["database"].get(
+ db.name
+ );
+ if (!databaseSchema) {
+ return { errors: [], statement: "" };
+ }
+ const metadata = await dbSchemaV1Store.getOrFetchDatabaseMetadata(
+ db.name,
+ false /* !skipCache */,
+ true /* silent */
+ );
+ const mergedMetadata = mergeSchemaEditToMetadata(
+ databaseSchema.schemaList,
+ cloneDeep(metadata)
+ );
+ const validationMessages = validateDatabaseMetadata(mergedMetadata);
+ if (validationMessages.length > 0) {
+ return {
+ errors: validationMessages,
+ statement: "",
+ };
+ }
+ try {
+ const { diff } = await schemaDesignServiceClient.diffMetadata(
+ {
+ sourceMetadata: metadata,
+ targetMetadata: mergedMetadata,
+ engine: db.instanceEntity.engine,
+ },
+ {
+ silent: true,
+ }
+ );
+ if (diff.length === 0) {
+ return {
+ errors: [t("schema-editor.nothing-changed")],
+ statement: "",
+ };
+ }
+ return {
+ errors: [],
+ statement: diff,
+ };
+ } catch {
+ return {
+ errors: [t("schema-editor.message.invalid-schema")],
+ statement: "",
+ };
+ }
+ } else {
+ // Use legacy `DatabaseEdit` for non-MySQL databases.
+ const databaseEditResult = await postDatabaseEdit(
+ databaseEdit,
+ true /* silent */
+ );
+ if (databaseEditResult.validateResultList.length > 0) {
+ return {
+ errors: databaseEditResult.validateResultList.map((v) => v.message),
+ statement: "",
+ };
+ }
+ const { statement } = databaseEditResult;
+ if (statement.length === 0) {
+ return {
+ errors: [t("schema-editor.nothing-changed")],
+ statement: "",
+ };
+ }
+ return {
+ errors: [],
+ statement,
+ };
+ }
+ };
+
+ const getStatement = async () => {
+ if (selectedTab.value === "raw-sql") {
+ const statement = editStatement.value;
+ if (statement.length === 0) {
+ return {
+ errors: [t("schema-editor.nothing-changed")],
+ statement: "",
+ };
+ }
+ return {
+ errors: [],
+ statement,
+ };
+ } else {
+ return fetchDatabaseEditStatement();
+ }
+ };
+
+ return { show, database, watchKey, getStatement };
+};
diff --git a/frontend/src/components/AlterSchemaPrepForm/utils.ts b/frontend/src/components/AlterSchemaPrepForm/utils.ts
new file mode 100644
index 0000000000..2902491999
--- /dev/null
+++ b/frontend/src/components/AlterSchemaPrepForm/utils.ts
@@ -0,0 +1,65 @@
+import axios from "axios";
+import { useSilentRequest } from "@/plugins/silent-request";
+import { useSchemaEditorV1Store } from "@/store";
+import { DatabaseEdit, DatabaseEditResult } from "@/types";
+import {
+ checkHasSchemaChanges,
+ diffSchema,
+ mergeDiffResults,
+} from "@/utils/schemaEditor/diffSchema";
+
+export const getDatabaseEditListWithSchemaEditor = () => {
+ const schemaEditorV1Store = useSchemaEditorV1Store();
+
+ const databaseEditList: DatabaseEdit[] = [];
+ for (const databaseSchema of Array.from(
+ schemaEditorV1Store.resourceMap["database"].values()
+ )) {
+ const database = databaseSchema.database;
+ for (const schema of databaseSchema.schemaList) {
+ const originSchema = databaseSchema.originSchemaList.find(
+ (originSchema) => originSchema.id === schema.id
+ );
+ if (!originSchema) {
+ continue;
+ }
+
+ const diffSchemaResult = diffSchema(database.name, originSchema, schema);
+ if (checkHasSchemaChanges(diffSchemaResult)) {
+ const index = databaseEditList.findIndex(
+ (edit) => String(edit.databaseId) === database.uid
+ );
+ if (index !== -1) {
+ databaseEditList[index] = {
+ databaseId: Number(database.uid),
+ ...mergeDiffResults([diffSchemaResult, databaseEditList[index]]),
+ };
+ } else {
+ databaseEditList.push({
+ databaseId: Number(database.uid),
+ ...diffSchemaResult,
+ });
+ }
+ }
+ }
+ }
+ return databaseEditList;
+};
+
+export const postDatabaseEdit = async (
+ databaseEdit: DatabaseEdit,
+ silent = false
+) => {
+ const request = () => {
+ const post = () =>
+ axios.post(`/api/database/${databaseEdit.databaseId}/edit`, databaseEdit);
+ if (silent) {
+ return useSilentRequest(post);
+ }
+ return post();
+ };
+
+ const resData = (await request()).data;
+ const databaseEditResult = resData.data.attributes as DatabaseEditResult;
+ return databaseEditResult;
+};
diff --git a/frontend/src/store/modules/v1/dbSchema.ts b/frontend/src/store/modules/v1/dbSchema.ts
index c71a2d6796..830dbd3566 100644
--- a/frontend/src/store/modules/v1/dbSchema.ts
+++ b/frontend/src/store/modules/v1/dbSchema.ts
@@ -25,7 +25,8 @@ export const useDBSchemaV1Store = defineStore("dbSchema_v1", {
actions: {
async getOrFetchDatabaseMetadata(
name: string,
- skipCache = false
+ skipCache = false,
+ silent = false
): Promise<DatabaseMetadata> {
const databaseId = getInstanceAndDatabaseId(name)[1];
if (
@@ -53,9 +54,14 @@ export const useDBSchemaV1Store = defineStore("dbSchema_v1", {
// Send a request and cache it.
const promise = databaseServiceClient
- .getDatabaseMetadata({
- name: `${name}/metadata`,
- })
+ .getDatabaseMetadata(
+ {
+ name: `${name}/metadata`,
+ },
+ {
+ silent,
+ }
+ )
.then((res) => {
this.databaseMetadataByName.set(name, res);
return res;