Skip to content

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

feat(sql-editor): alter the DML schema with statements from SQL editor (#382)

Yunwei Xiaod57a3d8b06b0
diff --git a/frontend/src/components/MonacoEditor/sqlParser.ts b/frontend/src/components/MonacoEditor/sqlParser.ts
index 3afa60e7cf..52a3e6fb8f 100644
--- a/frontend/src/components/MonacoEditor/sqlParser.ts
+++ b/frontend/src/components/MonacoEditor/sqlParser.ts
@@ -6,7 +6,7 @@ type ParseResult = {
error: Error | null;
};
-const parseSQL = (sql: string): ParseResult => {
+export const parseSQL = (sql: string): ParseResult => {
const parser = new Parser();
try {
@@ -17,11 +17,12 @@ const parseSQL = (sql: string): ParseResult => {
}
};
-export const isSelectStatement = (sql: string) => {
- const { data } = parseSQL(sql);
-
+export const isValidStatement = (data: ParseResult["data"]) => {
// if parser returns the null AST. it's an invalid sql statement
- if (data === null) return true;
+ return data !== null;
+};
+
+export const isSelectStatement = (data: ParseResult["data"]) => {
// if the sql statement is an object, it's a single sql statement
if (isObject(data) && !isArray(data)) {
return data.type.toLowerCase() === "select";
@@ -32,4 +33,14 @@ export const isSelectStatement = (sql: string) => {
}
};
+export const isMultipleStatements = (data: ParseResult["data"]) => {
+ // if the sql statement is an array and it's more than one statement
+ return isArray(data) && data.length > 1;
+};
+
+export const transformSQL = (data: AST | AST[], database = "MySQL") => {
+ const parser = new Parser();
+ return parser.sqlify(data, { database });
+};
+
export default parseSQL;
diff --git a/frontend/src/composables/useExecuteSQL.ts b/frontend/src/composables/useExecuteSQL.ts
index c467873607..63c5ee6143 100644
--- a/frontend/src/composables/useExecuteSQL.ts
+++ b/frontend/src/composables/useExecuteSQL.ts
@@ -1,64 +1,86 @@
-import { ref } from "vue";
+import { reactive } from "vue";
import { isEmpty } from "lodash-es";
import { useStore } from "vuex";
-import { isSelectStatement } from "../components/MonacoEditor/sqlParser";
+import { useI18n } from "vue-i18n";
+
+import {
+ parseSQL,
+ transformSQL,
+ isSelectStatement,
+ isMultipleStatements,
+} from "../components/MonacoEditor/sqlParser";
const useExecuteSQL = () => {
const store = useStore();
- const isLoadingData = ref(false);
+ const { t } = useI18n();
+ const state = reactive({
+ isLoadingData: false,
+ });
+
+ const notify = (type: string, title: string, description?: string) => {
+ store.dispatch("notification/pushNotification", {
+ module: "bytebase",
+ style: type,
+ title,
+ description,
+ });
+ };
const execute = async () => {
+ if (state.isLoadingData) {
+ notify("INFO", t("common.tips"), t("sql-editor.can-not-execute-query"));
+ }
+
const queryStatement = store.state.sqlEditor.queryStatement;
const selectedStatement = store.state.sqlEditor.selectedStatement;
const sqlStatement = selectedStatement || queryStatement;
+ const { data } = parseSQL(sqlStatement);
+
if (isEmpty(sqlStatement)) {
- store.dispatch("notification/pushNotification", {
- module: "bytebase",
- style: "CRITICAL",
- title: "Please input your SQL codes in the editor",
- });
+ notify("CRITICAL", t("sql-editor.notify-empty-statement"));
return;
}
- if (!isSelectStatement(sqlStatement)) {
- store.dispatch("notification/pushNotification", {
- module: "bytebase",
- style: "CRITICAL",
- title: "Only SELECT statements are allowed",
+ if (data !== null && !isSelectStatement(data)) {
+ store.dispatch("sqlEditor/setSqlEditorState", {
+ isShowExecutingHint: true,
});
return;
}
+
+ if (isMultipleStatements(data)) {
+ notify(
+ "INFO",
+ t("common.tips"),
+ t("sql-editor.notify-multiple-statements")
+ );
+ }
+
try {
- isLoadingData.value = true;
+ state.isLoadingData = true;
store.dispatch("sqlEditor/setIsExecuting", true);
+ // remove the comment from the sql statement in front-end
+ const statement = data !== null ? transformSQL(data) : sqlStatement;
const res = await store.dispatch("sqlEditor/executeQuery", {
- statement: sqlStatement,
+ statement,
});
- isLoadingData.value = false;
+ state.isLoadingData = false;
store.dispatch("sqlEditor/setIsExecuting", false);
if (res.error) {
- store.dispatch("notification/pushNotification", {
- module: "bytebase",
- style: "CRITICAL",
- title: res.error,
- });
+ notify("CRITICAL", res.error);
return;
}
} catch (error) {
- isLoadingData.value = false;
+ state.isLoadingData = false;
store.dispatch("sqlEditor/setIsExecuting", false);
- store.dispatch("notification/pushNotification", {
- module: "bytebase",
- style: "CRITICAL",
- title: error,
- });
+ notify("CRITICAL", error as string);
}
};
return {
- isLoadingData,
+ state,
execute,
};
};
diff --git a/frontend/src/locales/en.yml b/frontend/src/locales/en.yml
index 534fb44b59..9eee4f023f 100644
--- a/frontend/src/locales/en.yml
+++ b/frontend/src/locales/en.yml
@@ -158,6 +158,7 @@ common:
share: Share
or: or
export: Export
+ tips: Tips
error-page:
go-back-home: Go back home
anomaly-center: Anomaly Center
@@ -1042,6 +1043,18 @@ sql-editor:
no-rows-found: No rows found
download-as-csv: Download as CSV
download-as-json: Download as JSON
+ only-select-allowed: Only {select} statements are allowed to execute.
+ want-to-change-schema: If you want to {changeschema}.
+ change-schema: change schema
+ go-to-alter-schema: You can click the {alterschema} button, and submit an issue.
+ table-schema-placeholder: Select a table to see its schema
+ notify-empty-statement: Please input your SQL statements in the editor
+ notify-multiple-statements: >-
+ Multiple SQL statements detected.
+ SQL Editor only executes the first statement.
+ You can select another statement and execute it individually.
+ goto-alter-schema-hint: Please select a database connection from the top of the editor
+ can-not-execute-query: Can not execute query when loading data.
label:
error:
key-necessary: Key is required
diff --git a/frontend/src/locales/zh-CN.yml b/frontend/src/locales/zh-CN.yml
index 54f2b283bc..234c2879af 100644
--- a/frontend/src/locales/zh-CN.yml
+++ b/frontend/src/locales/zh-CN.yml
@@ -158,6 +158,7 @@ common:
share: 分享
or: 或者
export: 导出
+ tips: 提示信息
error-page:
go-back-home: 回到主页
anomaly-center: 异常中心
@@ -911,6 +912,15 @@ sql-editor:
no-rows-found: 无数据
download-as-csv: 下载为 CSV 格式
download-as-json: 下载为 JSON 格式
+ only-select-allowed: 只允许执行 {select} 语句
+ want-to-change-schema: 如果您想要 {changeschema}
+ change-schema: 变更 Schema
+ go-to-alter-schema: 您可以点击 “{alterschema}” 按钮,提交一个工单
+ table-schema-placeholder: 选择一个表进行查看 Schema
+ notify-empty-statement: 请在编辑器中输入 SQL 语句
+ notify-multiple-statements: 检测到您输入了多条 SQL 语句。SQL 编辑器只支持执行第一条语句。您可以选择其他语句单独执行。
+ goto-alter-schema-hint: 请从编辑器顶部选择一个数据库连接
+ can-not-execute-query: 加载数据时无法执行查询
label:
error:
key-necessary: 需要指定 Key
diff --git a/frontend/src/plugins/naive-ui.ts b/frontend/src/plugins/naive-ui.ts
index 87f1d6226e..233ce0ebab 100644
--- a/frontend/src/plugins/naive-ui.ts
+++ b/frontend/src/plugins/naive-ui.ts
@@ -1,6 +1,7 @@
import type { App } from "vue";
import {
create,
+ NAlert,
NButton,
NButtonGroup,
NCascader,
@@ -23,6 +24,7 @@ import {
const naive = create({
components: [
+ NAlert,
NButton,
NButtonGroup,
NCascader,
diff --git a/frontend/src/store/modules/sqlEditor.ts b/frontend/src/store/modules/sqlEditor.ts
index b6c3df8d9e..78afbc9fd0 100644
--- a/frontend/src/store/modules/sqlEditor.ts
+++ b/frontend/src/store/modules/sqlEditor.ts
@@ -11,6 +11,10 @@ import {
} from "../../types";
import * as types from "../mutation-types";
import { makeActions } from "../actions";
+import {
+ parseSQL,
+ transformSQL,
+} from "../../components/MonacoEditor/sqlParser";
const state: () => SqlEditorState = () => ({
connectionTree: [],
@@ -30,6 +34,7 @@ const state: () => SqlEditorState = () => ({
selectedStatement: "",
isExecuting: false,
queryResult: null,
+ isShowExecutingHint: false,
});
const getters = {
@@ -86,7 +91,7 @@ const getters = {
findProjectIdByDatabaseId:
(state: SqlEditorState, getter: any) =>
(databaseId: DatabaseId): ProjectId => {
- let projectId = 0;
+ let projectId = 1;
const databaseListByProjectId =
getter.connectionInfo.databaseListByProjectId;
for (const [id, databaseList] of databaseListByProjectId) {
@@ -107,6 +112,11 @@ const getters = {
isEmptyStatement(state: SqlEditorState) {
return isEmpty(state.queryStatement);
},
+ parsedStatement(state: SqlEditorState) {
+ const sqlStatement = state.selectedStatement || state.queryStatement;
+ const { data } = parseSQL(sqlStatement);
+ return data !== null ? transformSQL(data) : sqlStatement;
+ },
};
const mutations = {
diff --git a/frontend/src/types/store.ts b/frontend/src/types/store.ts
index 7bdd4079c7..170c91bb4c 100644
--- a/frontend/src/types/store.ts
+++ b/frontend/src/types/store.ts
@@ -194,6 +194,7 @@ export interface SqlEditorState {
selectedStatement: string;
isExecuting: boolean;
queryResult: Record<string, any>[] | null;
+ isShowExecutingHint: boolean;
}
export type SqlEditorGetters = typeof sqlEditorStore.getters;
export type SqlEditorActions = typeof sqlEditorStore.actions;
diff --git a/frontend/src/views/SqlEditor/AsidePanel/TableSchema.vue b/frontend/src/views/SqlEditor/AsidePanel/TableSchema.vue
index c4aa3ce4ed..e654314fca 100644
--- a/frontend/src/views/SqlEditor/AsidePanel/TableSchema.vue
+++ b/frontend/src/views/SqlEditor/AsidePanel/TableSchema.vue
@@ -11,7 +11,7 @@
<div class="action-edit flex items-center">
<NTooltip trigger="hover">
<template #trigger>
- <NButton text @click="handleEditorSchema">
+ <NButton text @click="gotoAlterSchema">
<heroicons-outline:pencil-alt class="w-4 h-4" />
</NButton>
</template>
@@ -59,7 +59,7 @@
</div>
</div>
<div v-else class="h-full flex justify-center items-center">
- Select a table to see its schema
+ {{ $t("sql-editor.table-schema-placeholder") }}
</div>
</template>
@@ -98,7 +98,7 @@ const tableInfo = ref();
const ctx = connectionContext.value;
const router = useRouter();
-const handleEditorSchema = () => {
+const gotoAlterSchema = () => {
const projectId = findProjectIdByDatabaseId.value(ctx.selectedDatabaseId);
const databaseList =
connectionInfo.value.databaseListByProjectId.get(projectId);
diff --git a/frontend/src/views/SqlEditor/EditorPanel/EditorAction.vue b/frontend/src/views/SqlEditor/EditorPanel/EditorAction.vue
index 9753784668..f2db7c51b5 100644
--- a/frontend/src/views/SqlEditor/EditorPanel/EditorAction.vue
+++ b/frontend/src/views/SqlEditor/EditorPanel/EditorAction.vue
@@ -3,7 +3,7 @@
<div class="actions-left w-1/2">
<NButton
type="primary"
- :disabled="isEmptyStatement"
+ :disabled="isEmptyStatement || executeState.isLoadingData"
@click="handleRunQuery"
>
<mdi:play class="h-5 w-5" /> {{ $t("common.run") }} (⌘+⏎)
@@ -72,7 +72,7 @@ const { setConnectionContext } = useNamespacedActions<SqlEditorActions>(
const selectedConnection = ref();
const isSeletedDatabase = ref(false);
-const { execute } = useExecuteSQL();
+const { execute, state: executeState } = useExecuteSQL();
const handleRunQuery = () => {
execute();
diff --git a/frontend/src/views/SqlEditor/EditorPanel/EditorPanel.vue b/frontend/src/views/SqlEditor/EditorPanel/EditorPanel.vue
index 0151b56277..10157a2324 100644
--- a/frontend/src/views/SqlEditor/EditorPanel/EditorPanel.vue
+++ b/frontend/src/views/SqlEditor/EditorPanel/EditorPanel.vue
@@ -3,10 +3,41 @@
<EditorAction />
<QueryEditor />
+
+ <BBModal
+ v-if="isShowExecutingHint"
+ :title="$t('common.tips')"
+ @close="handleClose"
+ >
+ <ExecuteHint @close="handleClose" />
+ </BBModal>
</div>
</template>
<script lang="ts" setup>
+import {
+ useNamespacedState,
+ useNamespacedActions,
+} from "vuex-composition-helpers";
+
+import { SqlEditorState, SqlEditorActions } from "../../../types";
import EditorAction from "./EditorAction.vue";
import QueryEditor from "./QueryEditor.vue";
+import ExecuteHint from "./ExecuteHint.vue";
+
+const { isShowExecutingHint } = useNamespacedState<SqlEditorState>(
+ "sqlEditor",
+ ["isShowExecutingHint"]
+);
+
+const { setSqlEditorState } = useNamespacedActions<SqlEditorActions>(
+ "sqlEditor",
+ ["setSqlEditorState"]
+);
+
+const handleClose = () => {
+ setSqlEditorState({
+ isShowExecutingHint: false,
+ });
+};
</script>
diff --git a/frontend/src/views/SqlEditor/EditorPanel/ExecuteHint.vue b/frontend/src/views/SqlEditor/EditorPanel/ExecuteHint.vue
new file mode 100644
index 0000000000..5efd9763a3
--- /dev/null
+++ b/frontend/src/views/SqlEditor/EditorPanel/ExecuteHint.vue
@@ -0,0 +1,109 @@
+<template>
+ <div class="execute-hint w-160">
+ <NAlert type="info">
+ <section class="space-y-2">
+ <p>
+ <i18n-t keypath="sql-editor.only-select-allowed">
+ <template #select>
+ <strong>SELECT</strong>
+ </template>
+ </i18n-t>
+ </p>
+ <p>
+ <i18n-t keypath="sql-editor.want-to-change-schema">
+ <template #changeschema>
+ <NButton text :href="docLink" type="primary" target="_blank">{{
+ $t("sql-editor.change-schema")
+ }}</NButton>
+ </template>
+ </i18n-t>
+ </p>
+ <p>
+ <i18n-t keypath="sql-editor.go-to-alter-schema">
+ <template #alterschema>
+ <strong>{{ $t("quick-action.alter-schema") }}</strong>
+ </template>
+ </i18n-t>
+ </p>
+ </section>
+ </NAlert>
+
+ <div class="execute-hint-content mt-4 flex justify-end space-x-2">
+ <NButton @click="handleColse">{{ $t("common.close") }}</NButton>
+ <NButton type="primary" @click="gotoAlterSchema">{{
+ $t("quick-action.alter-schema")
+ }}</NButton>
+ </div>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { defineEmits } from "vue";
+import { useRouter } from "vue-router";
+import { useStore } from "vuex";
+import { useI18n } from "vue-i18n";
+
+import {
+ useNamespacedGetters,
+ useNamespacedState,
+} from "vuex-composition-helpers";
+
+import type { SqlEditorState, SqlEditorGetters } from "../../../types";
+
+const emit = defineEmits<{
+ (e: "close"): void;
+}>();
+
+const router = useRouter();
+const store = useStore();
+const { t } = useI18n();
+
+const { findProjectIdByDatabaseId, parsedStatement } =
+ useNamespacedGetters<SqlEditorGetters>("sqlEditor", [
+ "findProjectIdByDatabaseId",
+ "parsedStatement",
+ ]);
+const { connectionContext } = useNamespacedState<SqlEditorState>("sqlEditor", [
+ "connectionContext",
+]);
+
+const ctx = connectionContext.value;
+
+const docLink =
+ "https://docs.bytebase.com/concepts/schema-change-workflow#ui-workflow";
+
+const handleColse = () => {
+ emit("close");
+};
+
+const gotoAlterSchema = () => {
+ if (ctx.databaseId === 0) {
+ store.dispatch("notification/pushNotification", {
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("sql-editor.goto-alter-schema-hint"),
+ });
+ return;
+ }
+
+ emit("close");
+
+ const projectId = findProjectIdByDatabaseId.value(ctx.databaseId as number);
+
+ router.push({
+ name: "workspace.issue.detail",
+ params: {
+ issueSlug: "new",
+ },
+ query: {
+ template: "bb.issue.database.schema.update",
+ name: `[${ctx.databaseName}] Alter schema`,
+ project: projectId,
+ databaseList: ctx.databaseId,
+ sql: parsedStatement.value,
+ },
+ });
+};
+</script>
+
+<style scoped></style>
diff --git a/frontend/src/views/SqlEditor/QuerySelector.vue b/frontend/src/views/SqlEditor/QuerySelector.vue
index aaf5904be0..58107d81c9 100644
--- a/frontend/src/views/SqlEditor/QuerySelector.vue
+++ b/frontend/src/views/SqlEditor/QuerySelector.vue
@@ -53,7 +53,7 @@
</template>
<script lang="ts" setup>
-import { ref } from "vue";
+import { ref, watch } from "vue";
import {
useNamespacedState,
useNamespacedActions,
@@ -66,6 +66,7 @@ import {
AnyTabInfo,
EditorSelectorActions,
SqlEditorState,
+ SqlEditorActions,
} from "../../types";
import { isDev } from "../../utils";
@@ -83,6 +84,10 @@ const { addTab, setActiveTab, removeTab, updateTab } =
const { queryStatement } = useNamespacedState<SqlEditorState>("sqlEditor", [
"queryStatement",
]);
+const { setSqlEditorState } = useNamespacedActions<SqlEditorActions>(
+ "sqlEditor",
+ ["setSqlEditorState"]
+);
const enterTabIdx = ref(-1);
@@ -116,6 +121,17 @@ debouncedWatch(
debounce: 333,
}
);
+
+// initial tab state
+watch(
+ () => activeTab.value,
+ (tab) => {
+ setSqlEditorState({
+ queryStatement: tab.queries,
+ queryResult: null,
+ });
+ }
+);
</script>
<style scoped>