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: support raw SQL in sync schema (#7370)
boojack409ccc424b71
diff --git a/frontend/src/store/modules/v1/sheet.ts b/frontend/src/store/modules/v1/sheet.tsindex 8559cb941c..feb05068db 100644--- a/frontend/src/store/modules/v1/sheet.ts+++ b/frontend/src/store/modules/v1/sheet.ts@@ -146,6 +146,18 @@ export const useSheetV1Store = defineStore("sheet_v1", {return;}},+ async fetchSheetByUid(uid: SheetId, raw = false) {+ try {+ const sheet = await sheetServiceClient.getSheet({+ name: `${projectNamePrefix}-/${sheetNamePrefix}${uid}`,+ raw,+ });+ this.sheetByName.set(sheet.name, sheet);+ return sheet;+ } catch {+ return;+ }+ },getSheetByName(name: string) {const sheet = this.sheetByName.get(name);return sheet;diff --git a/frontend/src/views/SyncDatabaseSchema/RawSQLEditor.vue b/frontend/src/views/SyncDatabaseSchema/RawSQLEditor.vuenew file mode 100644index 0000000000..feeb58770c--- /dev/null+++ b/frontend/src/views/SyncDatabaseSchema/RawSQLEditor.vue@@ -0,0 +1,255 @@+<template>+ <div class="w-full h-auto flex flex-col justify-start items-start">+ <div class="w-full h-auto shrink-0 flex flex-row justify-between items-end">+ <div class="flex flex-col justify-start items-start gap-y-2">+ <div class="flex flex-row justify-start items-center">+ <span class="mr-2 w-20 shrink-0 text-sm">{{+ $t("common.project")+ }}</span>+ <ProjectSelect+ :project="state.projectId"+ :disabled="viewMode"+ @update:project="handleProjectSelect"+ />+ </div>+ <div class="flex flex-row justify-start items-center">+ <span class="mr-2 w-20 shrink-0 text-sm">{{+ $t("database.engine")+ }}</span>+ <NSelect+ v-model:value="state.engine"+ :disabled="viewMode"+ :consistent-menu-width="false"+ :options="engineSelectorOptions"+ @update:value="handleEngineChange"+ />+ </div>+ </div>+ <div+ v-if="!viewMode"+ class="flex flex-row justify-end items-center space-x-3"+ >+ <label+ for="sql-file-input"+ class="text-sm border px-3 leading-8 flex items-center rounded cursor-pointer hover:opacity-80 disabled:cursor-not-allowed disabled:opacity-60"+ >+ <heroicons-outline:arrow-up-tray+ class="w-4 h-auto mr-1 text-gray-500"+ />+ {{ $t("issue.upload-sql") }}+ <input+ id="sql-file-input"+ type="file"+ accept=".sql,.txt,application/sql,text/plain"+ class="hidden"+ @change="handleUploadFile"+ />+ </label>+ </div>+ </div>+ <BBAttention+ v-if="isSheetOversized && !viewMode"+ :class="'my-2'"+ :style="`WARN`"+ :title="$t('issue.statement-from-sheet-warning')"+ >+ <template v-if="sheet?.name" #action>+ <DownloadSheetButton :sheet="sheet.name" size="small" />+ </template>+ </BBAttention>+ <div class="mt-4 w-full h-96 overflow-hidden">+ <MonacoEditor+ class="w-full h-full border"+ :value="state.editStatement"+ :auto-focus="true"+ :language="'sql'"+ :readonly="viewMode"+ :dialect="dialectOfEngineV1(state.engine)"+ @change="handleStatementChange"+ />+ </div>+ </div>+</template>++<script lang="ts" setup>+import { NSelect } from "naive-ui";+import { computed, onMounted, nextTick, reactive } from "vue";+import { useI18n } from "vue-i18n";+import { useNotificationStore, useSheetV1Store } from "@/store";+import {+ DEFAULT_PROJECT_V1_NAME,+ UNKNOWN_ID,+ dialectOfEngineV1,+} from "@/types";+import DownloadSheetButton from "@/components/Sheet/DownloadSheetButton.vue";+import { Engine } from "@/types/proto/v1/common";+import { engineNameV1 } from "@/utils";+import {+ Sheet_Source,+ Sheet_Type,+ Sheet_Visibility,+} from "@/types/proto/v1/sheet_service";+import { useDebounceFn } from "@vueuse/core";+import MonacoEditor from "@/components/MonacoEditor";+import { ProjectSelect } from "@/components/v2";+import { RawSQLState } from "./types";++const MAX_UPLOAD_FILE_SIZE_MB = 1;++interface LocalState {+ projectId?: string;+ engine: Engine;+ editStatement: string;+}++const props = defineProps<{+ projectId?: string;+ engine: Engine;+ statement?: string;+ sheetId?: number;+ viewMode?: boolean;+}>();++const emit = defineEmits<{+ (event: "update", rawSQLState: RawSQLState): void;+}>();++const { t } = useI18n();+const notificationStore = useNotificationStore();+const sheetStore = useSheetV1Store();+const state = reactive<LocalState>({+ projectId: props.projectId,+ engine: props.engine || Engine.MYSQL,+ editStatement: props.statement || "",+});++const availableEngines = computed(() => {+ return [Engine.MYSQL, Engine.POSTGRES];+});++const engineSelectorOptions = computed(() => {+ return availableEngines.value.map((engine) => {+ return {+ label: engineNameV1(engine),+ value: engine,+ };+ });+});++const sheet = computed(() => {+ return sheetStore.getSheetByUid(props.sheetId || UNKNOWN_ID);+});++const isSheetOversized = computed(() => {+ if (!sheet.value) {+ return false;+ }+ return (+ new TextDecoder().decode(sheet.value.content).length <+ sheet.value.contentSize+ );+});++onMounted(async () => {+ if (props.sheetId) {+ const sheet = await sheetStore.getOrFetchSheetByUid(props.sheetId);+ if (sheet) {+ const statement = new TextDecoder().decode(sheet.content);+ state.editStatement = statement;+ }+ }+});++const handleProjectSelect = (uid: string | undefined) => {+ if (!uid || uid === String(UNKNOWN_ID)) return;+ state.projectId = uid;+ update();+};++const handleEngineChange = () => {+ nextTick(() => {+ update();+ });+};++const handleUploadFile = (e: Event) => {+ const target = e.target as HTMLInputElement;+ const file = (target.files || [])[0];+ const cleanup = () => {+ // Note that once selected a file, selecting the same file again will not+ // trigger <input type="file">'s change event.+ // So we need to do some cleanup stuff here.+ target.files = null;+ target.value = "";+ };++ if (!file) {+ return cleanup();+ }+ if (file.size > MAX_UPLOAD_FILE_SIZE_MB * 1024 * 1024) {+ notificationStore.pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("issue.upload-sql-file-max-size-exceeded", {+ size: `${MAX_UPLOAD_FILE_SIZE_MB}MB`,+ }),+ });+ return cleanup();+ }+ const fr = new FileReader();+ fr.onload = async () => {+ const statement = fr.result as string;+ const sheet = await sheetStore.createSheet(DEFAULT_PROJECT_V1_NAME, {+ name: file.name,+ content: new TextEncoder().encode(statement),+ visibility: Sheet_Visibility.VISIBILITY_PROJECT,+ source: Sheet_Source.SOURCE_BYTEBASE_ARTIFACT,+ type: Sheet_Type.TYPE_SQL,+ });+ const sheetId = sheetStore.getSheetUid(sheet.name);+ await handleStatementChange(statement);+ update(sheetId);+ };+ fr.onerror = () => {+ notificationStore.pushNotification({+ module: "bytebase",+ style: "WARN",+ title: `Read file error`,+ description: String(fr.error),+ });+ return;+ };+ fr.readAsText(file);++ cleanup();+};++const handleStatementChange = async (statement: string) => {+ await handleUpdateSheet(statement);+ state.editStatement = statement;+ update();+};++const handleUpdateSheet = useDebounceFn(async (statement: string) => {+ if (!sheet.value) {+ return;+ }++ await sheetStore.patchSheet({+ name: sheet.value.name,+ content: new TextEncoder().encode(statement),+ });+}, 1000);++const update = (sheetId?: number) => {+ if (sheet.value) {+ sheetId = sheetStore.getSheetUid(sheet.value?.name);+ }+ emit("update", {+ projectId: state.projectId,+ engine: state.engine,+ statement: state.editStatement,+ sheetId: sheetId,+ });+};+</script>diff --git a/frontend/src/views/SyncDatabaseSchema/RawSQLEditorPanel.vue b/frontend/src/views/SyncDatabaseSchema/RawSQLEditorPanel.vuenew file mode 100644index 0000000000..5f61eff90c--- /dev/null+++ b/frontend/src/views/SyncDatabaseSchema/RawSQLEditorPanel.vue@@ -0,0 +1,49 @@+<template>+ <NDrawer+ :show="true"+ width="auto"+ :auto-focus="false"+ :close-on-esc="true"+ @update:show="(show: boolean) => !show && emit('dismiss')"+ >+ <NDrawerContent+ :title="$t('schema-designer.quick-action')"+ :closable="true"+ class="w-192"+ >+ <RawSQLEditor+ :view-mode="true"+ :project-id="rawSqlState.projectId"+ :engine="rawSqlState.engine"+ :statement="rawSqlState.statement"+ :sheet-id="rawSqlState.sheetId"+ />++ <template #footer>+ <div class="flex-1 flex items-center justify-between">+ <div></div>++ <div class="flex items-center justify-end gap-x-3">+ <NButton @click.prevent="emit('dismiss')">+ {{ $t("common.close") }}+ </NButton>+ </div>+ </div>+ </template>+ </NDrawerContent>+ </NDrawer>+</template>++<script lang="ts" setup>+import { NDrawer, NDrawerContent } from "naive-ui";+import RawSQLEditor from "./RawSQLEditor.vue";+import { RawSQLState } from "./types";++defineProps<{+ rawSqlState: RawSQLState;+}>();++const emit = defineEmits<{+ (event: "dismiss"): void;+}>();+</script>diff --git a/frontend/src/views/SyncDatabaseSchema/SelectTargetDatabasesView.vue b/frontend/src/views/SyncDatabaseSchema/SelectTargetDatabasesView.vueindex 58014805f9..26a2fdc76a 100644--- a/frontend/src/views/SyncDatabaseSchema/SelectTargetDatabasesView.vue+++ b/frontend/src/views/SyncDatabaseSchema/SelectTargetDatabasesView.vue@@ -33,8 +33,10 @@<aclass="normal-link inline-flex items-center":href="`/db/${databaseV1Slug(getSourceDatabase()!)}`"- >{{ getSourceDatabase()!.databaseName }}</a>+ <EngineIcon class="mr-1" :engine="engine" />+ {{ getSourceDatabase()!.databaseName }}+ </a></div><divv-if="databaseSourceSchema.changeHistory.uid !== String(UNKNOWN_ID)"@@ -43,12 +45,15 @@<aclass="normal-link inline-flex items-center":href="changeHistoryLink(databaseSourceSchema.changeHistory)"- >{{ databaseSourceSchema.changeHistory.version }}</a>+ {{ databaseSourceSchema.changeHistory.version }}+ </a></div></div></template>- <template v-else>+ <template+ v-else-if="sourceSchemaType === 'SCHEMA_DESIGN' && selectedSchemaDesign"+ ><div><span>{{ $t("common.project") }} - </span><a@@ -63,10 +68,31 @@class="normal-link inline-flex items-center"@click="state.showViewSchemaDesignPanel = true">+ <EngineIcon class="mr-1" :engine="engine" />{{ selectedSchemaDesign?.title || "Unknown" }}</span></div></template>+ <template v-else>+ <div>+ <span>{{ $t("common.project") }} - </span>+ <a+ class="normal-link inline-flex items-center"+ :href="`/project/${projectV1Slug(project)}`"+ >{{ project.title }}</a+ >+ </div>+ <div>+ <span>{{ "Schema" }} - </span>+ <span+ class="normal-link inline-flex items-center"+ @click="state.showViewRawSQLPanel = true"+ >+ <EngineIcon class="mr-1" :engine="engine" />+ <span>{{ "Raw SQL" }}</span>+ </span>+ </div>+ </template></div><div@@ -221,6 +247,13 @@:view-mode="true"@dismiss="state.showViewSchemaDesignPanel = false"/>++ <RawSQLEditorPanel+ v-if="state.showViewRawSQLPanel && rawSqlState"+ :raw-sql-state="rawSqlState"+ :view-mode="true"+ @dismiss="state.showViewRawSQLPanel = false"+ /></template><script lang="ts" setup>@@ -234,7 +267,8 @@ import {pushNotification,useDatabaseV1Store,useEnvironmentV1Store,- useProjectV1ByUID,+ useProjectV1Store,+ useSheetV1Store,} from "@/store";import { ComposedDatabase, UNKNOWN_ID } from "@/types";import { changeHistoryLink, databaseV1Slug, projectV1Slug } from "@/utils";@@ -243,9 +277,10 @@ import DiffViewPanel from "./DiffViewPanel.vue";import { Engine, engineToJSON } from "@/types/proto/v1/common";import { InstanceV1EngineIcon } from "@/components/v2";import { ChangeHistory } from "@/types/proto/v1/database_service";-import { SourceSchemaType } from "./types";+import { RawSQLState, SourceSchemaType } from "./types";import EditSchemaDesignPanel from "@/components/SchemaDesigner/EditSchemaDesignPanel.vue";import { useSchemaDesignStore } from "@/store/modules/schemaDesign";+import RawSQLEditorPanel from "./RawSQLEditorPanel.vue";interface DatabaseSourceSchema {environmentId: string;@@ -260,6 +295,7 @@ interface LocalState {selectedDatabaseIdList: string[];showSelectDatabasePanel: boolean;showViewSchemaDesignPanel: boolean;+ showViewRawSQLPanel: boolean;}const props = defineProps<{@@ -267,12 +303,14 @@ const props = defineProps<{sourceSchemaType: SourceSchemaType;databaseSourceSchema?: DatabaseSourceSchema;schemaDesignName?: string;+ rawSqlState?: RawSQLState;}>();const { t } = useI18n();const environmentV1Store = useEnvironmentV1Store();const databaseStore = useDatabaseV1Store();const schemaDesignStore = useSchemaDesignStore();+const sheetStore = useSheetV1Store();const diffViewerRef = ref<HTMLDivElement>();const state = reactive<LocalState>({isLoading: true,@@ -281,6 +319,7 @@ const state = reactive<LocalState>({selectedDatabaseId: undefined,selectedDatabaseIdList: [],showViewSchemaDesignPanel: false,+ showViewRawSQLPanel: false,});const databaseSchemaCache = reactive<Record<string, string>>({});const databaseDiffCache = reactive<@@ -292,8 +331,10 @@ const databaseDiffCache = reactive<}>>({});+const project = computed(() => {+ return useProjectV1Store().getProjectByUID(props.projectId);+});-const { project } = useProjectV1ByUID(props.projectId);const selectedSchemaDesign = computed(() => {if (!props.schemaDesignName) {return undefined;@@ -303,8 +344,19 @@ const selectedSchemaDesign = computed(() => {const sourceDatabaseSchema = computed(() => {if (props.sourceSchemaType === "SCHEMA_HISTORY_VERSION") {return props.databaseSourceSchema?.changeHistory.schema || "";- } else {+ } else if (props.sourceSchemaType === "SCHEMA_DESIGN") {return selectedSchemaDesign.value?.schema || "";+ } else if (props.sourceSchemaType === "RAW_SQL") {+ let statement = props.rawSqlState?.statement || "";+ if (props.rawSqlState?.sheetId) {+ const sheet = sheetStore.getSheetByUid(props.rawSqlState.sheetId);+ if (sheet) {+ statement = new TextDecoder().decode(sheet.content);+ }+ }+ return statement;+ } else {+ return "";}});const engine = computed(() => {@@ -314,8 +366,10 @@ const engine = computed(() => {).instanceEntity.engine;} else if (props.sourceSchemaType === "SCHEMA_DESIGN") {return selectedSchemaDesign.value!.engine;+ } else if (props.sourceSchemaType === "RAW_SQL") {+ return props.rawSqlState!.engine;} else {- return Engine.MYSQL;+ return Engine.ENGINE_UNSPECIFIED;}});const targetDatabaseList = computed(() => {@@ -372,8 +426,13 @@ const shownDatabaseList = computed(() => {);});-onMounted(() => {+onMounted(async () => {state.isLoading = false;++ // Prepare raw sql statement from sheet.+ if (props.rawSqlState?.sheetId) {+ await sheetStore.fetchSheetByUid(props.rawSqlState?.sheetId);+ }});const getSourceDatabase = () => {diff --git a/frontend/src/views/SyncDatabaseSchema/TargetDatabasesSelectPanel.vue b/frontend/src/views/SyncDatabaseSchema/TargetDatabasesSelectPanel.vueindex 34da56ea35..574df1eccc 100644--- a/frontend/src/views/SyncDatabaseSchema/TargetDatabasesSelectPanel.vue+++ b/frontend/src/views/SyncDatabaseSchema/TargetDatabasesSelectPanel.vue@@ -131,11 +131,7 @@ import {NDrawer,NDrawerContent,} from "naive-ui";-import {- useDatabaseV1Store,- useEnvironmentV1Store,- useProjectV1Store,-} from "@/store";+import { useDatabaseV1Store, useEnvironmentV1Store } from "@/store";import { ComposedDatabase } from "@/types";import { Environment } from "@/types/proto/v1/environment_service";import { EnvironmentV1Name, InstanceV1Name } from "@/components/v2";@@ -167,10 +163,9 @@ const state = reactive<LocalState>({});const databaseListGroupByEnvironment = computed(() => {- const project = useProjectV1Store().getProjectByUID(props.projectId);const databaseList =- databaseStore- .databaseListByProject(project.name)+ databaseStore.databaseList+ .filter((db) => db.projectEntity.uid === props.projectId).filter((db) => db.databaseName.includes(state.searchText)).filter((db) => db.instanceEntity.engine === props.engine) || [];const listByEnv = environmentV1Store.environmentList.map((environment) => {diff --git a/frontend/src/views/SyncDatabaseSchema/index.vue b/frontend/src/views/SyncDatabaseSchema/index.vueindex d0fa5734f0..b6fba860f5 100644--- a/frontend/src/views/SyncDatabaseSchema/index.vue+++ b/frontend/src/views/SyncDatabaseSchema/index.vue@@ -29,6 +29,7 @@:value="'SCHEMA_DESIGN'":label="$t('schema-designer.schema-design')"/>+ <NRadio :value="'RAW_SQL'" :label="'Raw SQL'" /></NRadioGroup></div><DatabaseSchemaSelector@@ -44,6 +45,14 @@(schemaDesignState.selectedSchemaDesign = schemaDesign)"/>+ <RawSQLEditor+ v-if="state.sourceSchemaType === 'RAW_SQL'"+ :project-id="rawSQLState.projectId"+ :engine="rawSQLState.engine"+ :statement="rawSQLState.statement"+ :sheet-id="rawSQLState.sheetId"+ @update="handleRawSQLStateChange"+ /></template><template #1><SelectTargetDatabasesView@@ -52,6 +61,7 @@:source-schema-type="state.sourceSchemaType":database-source-schema="(changeHistorySourceSchemaState as any)":schema-design-name="schemaDesignState.selectedSchemaDesign?.name"+ :raw-sql-state="rawSQLState"/></template></BBStepTab>@@ -68,13 +78,19 @@ import { useRouter } from "vue-router";import { useProjectV1Store } from "@/store";import { UNKNOWN_ID } from "@/types";import SelectTargetDatabasesView from "./SelectTargetDatabasesView.vue";-import { ChangeHistorySourceSchema, SourceSchemaType } from "./types";+import {+ ChangeHistorySourceSchema,+ RawSQLState,+ SourceSchemaType,+} from "./types";import DatabaseSchemaSelector from "./DatabaseSchemaSelector.vue";import SchemaDesignSelector from "./SchemaDesignSelector.vue";import { SchemaDesign } from "@/types/proto/v1/schema_design_service";import { getProjectAndSchemaDesignSheetId } from "@/store/modules/v1/common";import { useSchemaDesignStore } from "@/store/modules/schemaDesign";import { BBStepTab } from "@/bbkit";+import RawSQLEditor from "./RawSQLEditor.vue";+import { Engine } from "@/types/proto/v1/common";const SELECT_SOURCE_SCHEMA = 0;const SELECT_TARGET_DATABASE_LIST = 1;@@ -102,10 +118,15 @@ const changeHistorySourceSchemaState = reactive<ChangeHistorySourceSchema>({});const schemaDesignState = reactive<{selectedSchemaDesign?: SchemaDesign;}>({});+const rawSQLState = reactive<RawSQLState>({+ engine: Engine.MYSQL,+ statement: "",+});+const projectId = computed(() => {if (state.sourceSchemaType === "SCHEMA_HISTORY_VERSION") {return changeHistorySourceSchemaState.projectId;- } else {+ } else if (state.sourceSchemaType === "SCHEMA_DESIGN") {if (!schemaDesignState.selectedSchemaDesign) {return undefined;}@@ -114,6 +135,8 @@ const projectId = computed(() => {);const project = projectStore.getProjectByName(`projects/${projectName}`);return project.uid;+ } else {+ return rawSQLState.projectId;}});@@ -145,8 +168,13 @@ const allowNext = computed(() => {isValidId(changeHistorySourceSchemaState.databaseId) &&!isUndefined(changeHistorySourceSchemaState.changeHistory));- } else {+ } else if (state.sourceSchemaType === "SCHEMA_DESIGN") {return !isUndefined(schemaDesignState.selectedSchemaDesign);+ } else {+ return (+ !isUndefined(rawSQLState.projectId) &&+ (rawSQLState.statement !== "" || !isUndefined(rawSQLState.sheetId))+ );}} else {if (!targetDatabaseViewRef.value) {@@ -185,6 +213,10 @@ onMounted(async () => {}});+const handleRawSQLStateChange = (state: RawSQLState) => {+ Object.assign(rawSQLState, state);+};+const tryChangeStep = async (oldStep: number,newStep: number,diff --git a/frontend/src/views/SyncDatabaseSchema/types.ts b/frontend/src/views/SyncDatabaseSchema/types.tsindex 45fccf00d2..7e8844544e 100644--- a/frontend/src/views/SyncDatabaseSchema/types.ts+++ b/frontend/src/views/SyncDatabaseSchema/types.ts@@ -1,6 +1,10 @@+import { Engine } from "@/types/proto/v1/common";import { ChangeHistory } from "@/types/proto/v1/database_service";-export type SourceSchemaType = "SCHEMA_HISTORY_VERSION" | "SCHEMA_DESIGN";+export type SourceSchemaType =+ | "SCHEMA_HISTORY_VERSION"+ | "SCHEMA_DESIGN"+ | "RAW_SQL";export interface ChangeHistorySourceSchema {projectId?: string;@@ -8,3 +12,10 @@ export interface ChangeHistorySourceSchema {databaseId?: string;changeHistory?: ChangeHistory;}++export interface RawSQLState {+ projectId?: string;+ engine: Engine;+ statement: string;+ sheetId?: number;+}