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(sql-editor): Execute query in admin mode (#3139)
Liu Jib098d4911cee
diff --git a/frontend/src/components/InstanceEngineIcon.vue b/frontend/src/components/InstanceEngineIcon.vueindex a497d20a5e..0da6fc00e1 100644--- a/frontend/src/components/InstanceEngineIcon.vue+++ b/frontend/src/components/InstanceEngineIcon.vue@@ -1,7 +1,7 @@<template><NTooltip><template #trigger>- <div class="relative" v-bind="$attrs">+ <div class="relative w-4" v-bind="$attrs"><img class="h-4 w-auto" :src="SelectedEngineIconPath" /><divv-if="showStatus"diff --git a/frontend/src/components/ProvideSQLEditorContext.vue b/frontend/src/components/ProvideSQLEditorContext.vueindex c4caff3c14..c2dad9d98d 100644--- a/frontend/src/components/ProvideSQLEditorContext.vue+++ b/frontend/src/components/ProvideSQLEditorContext.vue@@ -134,6 +134,7 @@ const prepareSheet = async () => {instanceId: sheet.database?.instanceId || UNKNOWN_ID,databaseId: sheet.databaseId || UNKNOWN_ID,},+ mode: sheet.payload.tabMode,});}diff --git a/frontend/src/composables/useExecuteSQL.ts b/frontend/src/composables/useExecuteSQL.tsindex 4b8d8af1eb..0c07a089d9 100644--- a/frontend/src/composables/useExecuteSQL.ts+++ b/frontend/src/composables/useExecuteSQL.ts@@ -4,7 +4,6 @@ import { useI18n } from "vue-i18n";import {parseSQL,- transformSQL,isSelectStatement,isMultipleStatements,isDDLStatement,@@ -12,7 +11,7 @@ import {} from "../components/MonacoEditor/sqlParser";import { pushNotification, useTabStore, useSQLEditorStore } from "@/store";import { BBNotificationStyle } from "@/bbkit/types";-import { ExecuteConfig, ExecuteOption } from "@/types";+import { ExecuteConfig, ExecuteOption, TabMode } from "@/types";const useExecuteSQL = () => {const { t } = useI18n();@@ -32,29 +31,12 @@ const useExecuteSQL = () => {});};- const execute = async (+ const executeReadonly = async (query: string,config: ExecuteConfig,option?: Partial<ExecuteOption>) => {const tab = tabStore.currentTab;-- if (tab.isExecutingSQL) {- notify("INFO", t("common.tips"), t("sql-editor.can-not-execute-query"));- return;- }-- const isDisconnected = tabStore.isDisconnected;- if (isDisconnected) {- notify("CRITICAL", t("sql-editor.select-connection"));- return;- }-- if (isEmpty(query)) {- notify("CRITICAL", t("sql-editor.notify-empty-statement"));- return;- }-const { data } = parseSQL(query);if (data === undefined) {@@ -88,14 +70,12 @@ const useExecuteSQL = () => {);}- let selectStatement =- data !== null ? transformSQL(data, config.databaseType) : query;+ let selectStatement = query;if (option?.explain) {selectStatement = `EXPLAIN ${selectStatement}`;}try {- tab.isExecutingSQL = true;const sqlResultSet = await sqlEditorStore.executeQuery({statement: selectStatement,});@@ -152,11 +132,92 @@ const useExecuteSQL = () => {},});notify("CRITICAL", error as string);- } finally {- tab.isExecutingSQL = false;}};+ const executeAdmin = async (+ query: string,+ config: ExecuteConfig,+ option?: Partial<ExecuteOption>+ ) => {+ const tab = tabStore.currentTab;++ let statement = query;+ if (option?.explain) {+ statement = `EXPLAIN ${statement}`;+ }++ try {+ const sqlResultSet = await sqlEditorStore.executeAdminQuery({+ statement,+ });++ // use `markRaw` to prevent vue from monitoring the object change deeply+ const queryResult = sqlResultSet.data+ ? markRaw(sqlResultSet.data)+ : undefined;+ Object.assign(tab, {+ queryResult,+ adviceList: sqlResultSet.adviceList,+ executeParams: {+ query,+ config,+ option,+ },+ });+ if (queryResult) {+ // Refresh the query history list when the query executed successfully+ // (with or without warnings).+ sqlEditorStore.fetchQueryHistoryList();+ }+ } catch (error) {+ Object.assign(tab, {+ queryResult: undefined,+ adviceList: undefined,+ executeParams: {+ query,+ config,+ option,+ },+ });+ notify("CRITICAL", error as string);+ }+ };++ const execute = async (+ query: string,+ config: ExecuteConfig,+ option?: Partial<ExecuteOption>+ ) => {+ const tab = tabStore.currentTab;++ if (tab.isExecutingSQL) {+ notify("INFO", t("common.tips"), t("sql-editor.can-not-execute-query"));+ return;+ }++ const isDisconnected = tabStore.isDisconnected;+ if (isDisconnected) {+ notify("CRITICAL", t("sql-editor.select-connection"));+ return;+ }++ if (isEmpty(query)) {+ notify("CRITICAL", t("sql-editor.notify-empty-statement"));+ return;+ }++ tab.isExecutingSQL = true;++ if (tab.mode === TabMode.ReadOnly) {+ await executeReadonly(query, config, option);+ } else if (tab.mode === TabMode.Admin) {+ await executeAdmin(query, config, option);+ }++ tab.isExecutingSQL = false;+ };+return {execute,};diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex f683369f50..df35e69776 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -1324,7 +1324,11 @@"open-connection": "Open connection","visualize-explain": "Visualize Explain","sql-execute-in-protected-environment": "The SQL statement below will be executed in a protected environment.",- "rows-upper-limit": "reached the limit of query results"+ "rows-upper-limit": "reached the limit of query results",+ "tab-mode": {+ "readonly": "Readonly",+ "admin": "Admin"+ }},"label": {"empty-label-value": "<Empty Value>",diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 7a8a06890e..ddc6cfe24d 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -1325,7 +1325,11 @@"open-connection": "打开连接","visualize-explain": "可视化 Explain","sql-execute-in-protected-environment": "下面的 SQL 语句将会在受保护的环境中执行。",- "rows-upper-limit": "到达查询结果条数上限"+ "rows-upper-limit": "到达查询结果条数上限",+ "tab-mode": {+ "readonly": "只读",+ "admin": "管理员"+ }},"label": {"empty-label-value": "<空值>",diff --git a/frontend/src/store/modules/sheet.ts b/frontend/src/store/modules/sheet.tsindex 04b439aca8..55af2f8c8d 100644--- a/frontend/src/store/modules/sheet.ts+++ b/frontend/src/store/modules/sheet.ts@@ -17,13 +17,31 @@ import {SheetOrganizerUpsert,ProjectId,SheetUpsert,+ SheetPayload,} from "@/types";import { getPrincipalFromIncludedList } from "./principal";import { useAuthStore } from "./auth";import { useDatabaseStore } from "./database";import { useProjectStore } from "./project";import { useTabStore } from "./tab";-import { isSheetWritable } from "@/utils";+import { getDefaultSheetPayload, isSheetWritable } from "@/utils";++function convertSheetPayload(+ resourceObj: ResourceObject,+ includedList: ResourceObject[]+): SheetPayload {+ const payload = getDefaultSheetPayload();+ try {+ const payloadJSON = resourceObj.attributes.payload;+ if (typeof payloadJSON === "string") {+ Object.assign(payload, JSON.parse(payloadJSON));+ }+ } catch {+ // nothing+ }++ return payload;+}function convertSheet(sheet: ResourceObject,@@ -46,6 +64,8 @@ function convertSheet(}}+ const payload = convertSheetPayload(sheet, includedList);+return {...(sheet.attributes as Omit<Sheet, "id" | "creator" | "updater">),id: parseInt(sheet.id),@@ -59,6 +79,7 @@ function convertSheet() as Principal,project,database,+ payload,};}@@ -135,10 +156,12 @@ export const useSheetStore = defineStore("sheet", {id: sheetUpsert.id,name: sheetUpsert.name,statement: sheetUpsert.statement,+ payload: sheetUpsert.payload,});}return this.createSheet({+ payload: getDefaultSheetPayload(),...sheetUpsert,visibility: "PRIVATE",});@@ -148,11 +171,16 @@ export const useSheetStore = defineStore("sheet", {sheetCreate.databaseId = undefined;}+ const attributes: Record<string, any> = { ...sheetCreate };+ if (typeof attributes.payload === "object") {+ attributes.payload = JSON.stringify(attributes.payload);+ }+const resData = (await axios.post(`/api/sheet`, {data: {type: "createSheet",- attributes: sheetCreate,+ attributes,},})).data;@@ -260,11 +288,16 @@ export const useSheetStore = defineStore("sheet", {return this.fetchSheetById(sheetId);},async patchSheetById(sheetPatch: SheetPatch): Promise<Sheet> {+ const attributes: Record<string, any> = { ...sheetPatch };+ if (typeof attributes.payload === "object") {+ attributes.payload = JSON.stringify(attributes.payload);+ }+const resData = (await axios.patch(`/api/sheet/${sheetPatch.id}`, {data: {type: "sheetPatch",- attributes: sheetPatch,+ attributes,},})).data;diff --git a/frontend/src/store/modules/sql.ts b/frontend/src/store/modules/sql.tsindex 68c7e38011..9a27a736e3 100644--- a/frontend/src/store/modules/sql.ts+++ b/frontend/src/store/modules/sql.ts@@ -116,6 +116,32 @@ export const useSQLStore = defineStore("sql", {throw new Error(resultSet.error);}+ return resultSet;+ },+ async adminQuery(queryInfo: QueryInfo): Promise<SQLResultSet> {+ const res = (+ await axios.post(+ `/api/sql/execute/admin`,+ {+ data: {+ type: "sqlExecute",+ attributes: {+ ...queryInfo,+ readonly: true,+ },+ },+ },+ {+ timeout: INSTANCE_OPERATION_TIMEOUT,+ }+ )+ ).data;++ const resultSet = convert(res.data);+ if (resultSet.error) {+ throw new Error(resultSet.error);+ }+return resultSet;},},diff --git a/frontend/src/store/modules/sqlEditor.ts b/frontend/src/store/modules/sqlEditor.tsindex b162e0a3fa..283a7998ce 100644--- a/frontend/src/store/modules/sqlEditor.ts+++ b/frontend/src/store/modules/sqlEditor.ts@@ -63,6 +63,19 @@ export const useSQLEditorStore = defineStore("sqlEditor", {return queryResult;},+ async executeAdminQuery({ statement }: Pick<QueryInfo, "statement">) {+ const { instanceId, databaseId } = useTabStore().currentTab.connection;+ const database = useDatabaseStore().getDatabaseById(databaseId);+ const databaseName = database.id === UNKNOWN_ID ? "" : database.name;+ const queryResult = await useSQLStore().adminQuery({+ instanceId,+ databaseName,+ statement: statement,+ limit: RESULT_ROWS_LIMIT,+ });++ return queryResult;+ },async fetchConnectionByInstanceIdAndDatabaseId(instanceId: InstanceId,databaseId: DatabaseIddiff --git a/frontend/src/store/modules/tab.ts b/frontend/src/store/modules/tab.tsindex 832ec6e53b..498b53d502 100644--- a/frontend/src/store/modules/tab.ts+++ b/frontend/src/store/modules/tab.ts@@ -30,6 +30,7 @@ const PERSISTENT_TASK_FIELDS = ["savedAt","statement","sheetId",+ "mode",] as const;type PersistentTaskInfo = Pick<TabInfo, typeof PERSISTENT_TASK_FIELDS[number]>;diff --git a/frontend/src/types/sheet.ts b/frontend/src/types/sheet.tsindex c68ad07ce0..7a111a7363 100644--- a/frontend/src/types/sheet.ts+++ b/frontend/src/types/sheet.ts@@ -7,6 +7,7 @@ import {ProjectId,RowStatus,PrincipalId,+ TabMode,} from ".";export type SheetVisibility = "PRIVATE" | "PROJECT" | "PUBLIC";@@ -15,6 +16,10 @@ export type SheetSource = "BYTEBASE" | "GITLAB_SELF_HOST" | "GITHUB_COM";export type SheetType = "SQL";+export type SheetPayload = {+ tabMode: TabMode;+};+export interface Sheet {id: SheetId;@@ -40,6 +45,7 @@ export interface Sheet {type: SheetType;starred: boolean;pinned: boolean;+ payload: SheetPayload;}export interface SheetUpsert {@@ -49,6 +55,7 @@ export interface SheetUpsert {name: string;statement: string;visibility?: SheetVisibility;+ payload?: SheetPayload;}export interface SheetCreate {@@ -57,6 +64,7 @@ export interface SheetCreate {name: string;statement: string;visibility: SheetVisibility;+ payload: SheetPayload;}export interface SheetPatch {@@ -65,6 +73,7 @@ export interface SheetPatch {statement?: string;visibility?: SheetVisibility;rowStatus?: RowStatus;+ payload?: SheetPayload;}export interface SheetFind {diff --git a/frontend/src/types/tab.ts b/frontend/src/types/tab.tsindex 332f766078..3d4666e9d8 100644--- a/frontend/src/types/tab.ts+++ b/frontend/src/types/tab.ts@@ -13,6 +13,11 @@ export type Connection = {databaseId: DatabaseId;};+export enum TabMode {+ ReadOnly = 1,+ Admin = 2,+}+export interface TabInfo {id: string;name: string;@@ -21,6 +26,7 @@ export interface TabInfo {savedAt: string;statement: string;selectedStatement: string;+ mode: TabMode;executeParams?: {query: string;config: ExecuteConfig;diff --git a/frontend/src/utils/sheet.ts b/frontend/src/utils/sheet.tsindex 8bf65624a6..f6c4834fd4 100644--- a/frontend/src/utils/sheet.ts+++ b/frontend/src/utils/sheet.ts@@ -1,4 +1,4 @@-import { Principal, Sheet } from "@/types";+import { Principal, Sheet, SheetPayload, TabMode } from "@/types";export const isSheetReadable = (sheet: Sheet, currentUser: Principal) => {// readable to@@ -54,3 +54,9 @@ export const isSheetWritable = (sheet: Sheet, currentUser: Principal) => {// visibility === "PUBLIC"return false;};++export const getDefaultSheetPayload = (): SheetPayload => {+ return {+ tabMode: TabMode.ReadOnly,+ };+};diff --git a/frontend/src/utils/tab.ts b/frontend/src/utils/tab.tsindex a5520fb7f3..af9156c51e 100644--- a/frontend/src/utils/tab.ts+++ b/frontend/src/utils/tab.ts@@ -3,7 +3,7 @@ import { computed } from "vue";import { v1 as uuidv1 } from "uuid";import { t } from "../plugins/i18n";import type { Connection, TabInfo } from "@/types";-import { UNKNOWN_ID } from "@/types";+import { UNKNOWN_ID, TabMode } from "@/types";export const defaultTabName = computed(() => t("sql-editor.untitled-sheet"));@@ -23,6 +23,7 @@ export const getDefaultTab = (): TabInfo => {savedAt: dayjs().format("YYYY-MM-DD HH:mm:ss"),statement: "",selectedStatement: "",+ mode: TabMode.ReadOnly,isExecutingSQL: false,};};diff --git a/frontend/src/views/sql-editor/EditorPanel/EditorAction.vue b/frontend/src/views/sql-editor/EditorPanel/EditorAction.vueindex 9239b31a9a..f51c625e1e 100644--- a/frontend/src/views/sql-editor/EditorPanel/EditorAction.vue+++ b/frontend/src/views/sql-editor/EditorPanel/EditorAction.vue@@ -105,6 +105,9 @@</div></section></NPopover>++ <TabModeSelect />+<NButtonsecondarystrong@@ -149,6 +152,7 @@ import { UNKNOWN_ID } from "@/types";import { instanceSlug } from "@/utils/slug";import SharePopover from "./SharePopover.vue";import ProtectedEnvironmentIcon from "@/components/Environment/ProtectedEnvironmentIcon.vue";+import TabModeSelect from "./TabModeSelect.vue";const emit = defineEmits<{(e: "save-sheet", content?: string): void;diff --git a/frontend/src/views/sql-editor/EditorPanel/EditorPanel.vue b/frontend/src/views/sql-editor/EditorPanel/EditorPanel.vueindex f0fba733d0..9c77b61afc 100644--- a/frontend/src/views/sql-editor/EditorPanel/EditorPanel.vue+++ b/frontend/src/views/sql-editor/EditorPanel/EditorPanel.vue@@ -49,6 +49,7 @@ import SQLEditor from "./SQLEditor.vue";import ExecuteHint from "./ExecuteHint.vue";import ConnectionHolder from "./ConnectionHolder.vue";import SaveSheetModal from "./SaveSheetModal.vue";+import type { SheetUpsert } from "@/types";import { UNKNOWN_ID } from "@/types";const tabStore = useTabStore();@@ -98,17 +99,20 @@ const handleSaveSheet = async (sheetName?: string) => {}isShowSaveSheetModal.value = false;- const { name, statement, sheetId } = tabStore.currentTab;+ const { name, statement, sheetId, mode } = tabStore.currentTab;sheetName = sheetName ? sheetName : name;const conn = tabStore.currentTab.connection;const database = await databaseStore.getOrFetchDatabaseById(conn.databaseId);- const sheetUpsert = {+ const sheetUpsert: SheetUpsert = {id: sheetId,projectId: database.project.id,databaseId: conn.databaseId,name: sheetName,statement: statement,+ payload: {+ tabMode: mode,+ },};const sheet = await sheetStore.upsertSheet(sheetUpsert);diff --git a/frontend/src/views/sql-editor/EditorPanel/TabModeSelect.vue b/frontend/src/views/sql-editor/EditorPanel/TabModeSelect.vuenew file mode 100644index 0000000000..3b80c5c5a3--- /dev/null+++ b/frontend/src/views/sql-editor/EditorPanel/TabModeSelect.vue@@ -0,0 +1,44 @@+<template>+ <NSelect+ v-model:value="tabStore.currentTab.mode"+ :options="tabModeOptions"+ :consistent-menu-width="false"+ @update:value="onUpdate"+ />+</template>++<script lang="ts" setup>+import { computed } from "vue";+import { SelectOption } from "naive-ui";+import { useI18n } from "vue-i18n";++import { TabMode } from "@/types";+import { useCurrentUser, useTabStore } from "@/store";+import { isDBAOrOwner } from "@/utils";++const { t } = useI18n();++const currentUser = useCurrentUser();++const allowAdmin = computed(() => isDBAOrOwner(currentUser.value.role));++const tabStore = useTabStore();++const tabModeOptions = computed((): SelectOption[] => {+ return [+ {+ value: TabMode.ReadOnly,+ label: t("sql-editor.tab-mode.readonly"),+ },+ {+ value: TabMode.Admin,+ label: t("sql-editor.tab-mode.admin"),+ disabled: !allowAdmin.value,+ },+ ];+});++const onUpdate = () => {+ tabStore.currentTab.isSaved = false;+};+</script>diff --git a/frontend/src/views/sql-editor/TabList/TabItem/TabItem.vue b/frontend/src/views/sql-editor/TabList/TabItem/TabItem.vueindex 803c56c11c..8d624811fe 100644--- a/frontend/src/views/sql-editor/TabList/TabItem/TabItem.vue+++ b/frontend/src/views/sql-editor/TabList/TabItem/TabItem.vue@@ -5,6 +5,7 @@current: isCurrentTab,temp: isTempTab(tab),hovering: state.hovering,+ admin: tab.mode === TabMode.Admin,}"@mousedown="$emit('select', tab, index)"@mouseenter="state.hovering = true"@@ -23,6 +24,7 @@ import { computed, PropType, reactive } from "vue";import { storeToRefs } from "pinia";import type { TabInfo } from "@/types";+import { TabMode } from "@/types";import { isTempTab } from "@/utils";import { useTabStore } from "@/store";import Prefix from "./Prefix.vue";