Skip to content

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

feat: saved query ui (#418)

STEVEN0ba074b9089d
diff --git a/frontend/src/components/MonacoEditor/MonacoEditor.vue b/frontend/src/components/MonacoEditor/MonacoEditor.vue
index 1f8dc9dfe2..5ea135d1d9 100644
--- a/frontend/src/components/MonacoEditor/MonacoEditor.vue
+++ b/frontend/src/components/MonacoEditor/MonacoEditor.vue
@@ -46,6 +46,7 @@ const emit = defineEmits<{
(e: "change", content: string): void;
(e: "change-selection", content: string): void;
(e: "run-query", content: string): void;
+ (e: "save", content: string): void;
}>();
const editorRef = ref();
@@ -145,6 +146,11 @@ const init = async () => {
}) as string;
emit("change-selection", selectedText);
});
+
+ editorInstance.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS, () => {
+ const value = editorInstance.getValue();
+ emit("save", value);
+ });
};
onMounted(init);
diff --git a/frontend/src/components/ProvideSqlEditorContext.vue b/frontend/src/components/ProvideSqlEditorContext.vue
index 6a19ba8c13..a4f0aed8cd 100644
--- a/frontend/src/components/ProvideSqlEditorContext.vue
+++ b/frontend/src/components/ProvideSqlEditorContext.vue
@@ -115,7 +115,8 @@ const prepareSqlEdtiorContext = async () => {
store.dispatch("sqlEditor/setConnectionContext", {
isLoadingTree: false,
});
- store.dispatch("sqlEditor/fetchQueryHistory");
+ store.dispatch("sqlEditor/fetchQueryHistoryList");
+ store.dispatch("sqlEditor/fetchSavedQueryList");
};
onMounted(async () => {
diff --git a/frontend/src/locales/en.yml b/frontend/src/locales/en.yml
index 2f71f42ee2..c0c2de3fa4 100644
--- a/frontend/src/locales/en.yml
+++ b/frontend/src/locales/en.yml
@@ -1094,6 +1094,8 @@ sql-editor:
rows: row | rows
no-history-found: No history found
search-history: Search History
+ search-saved-queries: Search Saved Queries
+ queries: Queries
hint-tips:
confirm-to-delete-this-history: Confirm to delete this history?
please-input-the-tab-label: Please input the tab label!
diff --git a/frontend/src/locales/zh-CN.yml b/frontend/src/locales/zh-CN.yml
index a9f0fd98cd..4fd052c71f 100644
--- a/frontend/src/locales/zh-CN.yml
+++ b/frontend/src/locales/zh-CN.yml
@@ -961,6 +961,8 @@ sql-editor:
rows: 条记录
no-history-found: 无历史记录
search-history: 搜索历史记录
+ search-saved-queries: 搜索归档查询
+ queries: 归档查询
hint-tips:
confirm-to-delete-this-history: 确定删除这条记录?
please-input-the-tab-label: 请输入标签页名称!
diff --git a/frontend/src/store/modules/activity.ts b/frontend/src/store/modules/activity.ts
index 01826c2866..b2c0ac0f5b 100644
--- a/frontend/src/store/modules/activity.ts
+++ b/frontend/src/store/modules/activity.ts
@@ -101,8 +101,20 @@ const actions = {
return activityList;
},
- async fetchActivityListForQueryHistory({ rootGetters }: any, userId: number) {
- const queryList = ["type=bb.sql-editor.query", `user=${userId}`];
+ async fetchActivityListForQueryHistory(
+ { rootGetters }: any,
+ {
+ limit,
+ }: {
+ limit: number;
+ }
+ ) {
+ const currentUser = rootGetters["auth/currentUser"]();
+ const queryList = [
+ "type=bb.sql-editor.query",
+ `user=${currentUser.id}`,
+ `limit=${limit}`,
+ ];
const data = (await axios.get(`/api/activity?${queryList.join("&")}`)).data;
const activityList = data.data.map((activity: ResourceObject) => {
return convert(activity, data.included, rootGetters);
diff --git a/frontend/src/store/modules/editorSelector.ts b/frontend/src/store/modules/editorSelector.ts
index d379d019ba..0ae26410f7 100644
--- a/frontend/src/store/modules/editorSelector.ts
+++ b/frontend/src/store/modules/editorSelector.ts
@@ -8,7 +8,7 @@ const getDefaultTab = () => {
return {
id: uuidv1(),
label: "Untitled Queries",
- isSaved: true,
+ isSaved: false,
savedAt: dayjs().format("YYYY-MM-DD HH:mm:ss"),
queryStatement: "",
selectedStatement: "",
@@ -81,7 +81,7 @@ const actions = {
const newTab = {
...getDefaultTab(),
label: payload.label ? payload.label : `Untitled Queries`,
- isSaved: true,
+ isSaved: false,
savedAt: dayjs().format("YYYY-MM-DD HH:mm:ss"),
queryStatement: payload.queryStatement || "",
selectedStatement: payload.selectedStatement || "",
diff --git a/frontend/src/store/modules/sqlEditor.ts b/frontend/src/store/modules/sqlEditor.ts
index 6293e4c900..8573b09868 100644
--- a/frontend/src/store/modules/sqlEditor.ts
+++ b/frontend/src/store/modules/sqlEditor.ts
@@ -1,3 +1,5 @@
+import axios from "axios";
+import dayjs from "dayjs";
import { isEmpty } from "lodash-es";
import {
@@ -9,10 +11,11 @@ import {
DatabaseId,
ProjectId,
QueryHistory,
+ SavedQuery,
+ ResourceObject,
} from "../../types";
import * as types from "../mutation-types";
import { makeActions } from "../actions";
-import dayjs from "dayjs";
const state: () => SqlEditorState = () => ({
connectionTree: [],
@@ -31,6 +34,8 @@ const state: () => SqlEditorState = () => ({
shouldSetContent: false,
queryHistoryList: [],
isFetchingQueryHistory: false,
+ savedQueryList: [],
+ isFetchingSavedQueries: false,
isExecuting: false,
isShowExecutingHint: false,
});
@@ -143,6 +148,16 @@ const mutations = {
) {
state.isFetchingQueryHistory = payload;
},
+ [types.SET_SAVED_QUERY_LIST](state: SqlEditorState, payload: SavedQuery[]) {
+ state.savedQueryList = payload;
+ },
+ [types.SET_IS_FETCHING_SAVED_QUERIES](
+ state: SqlEditorState,
+ payload: boolean
+ ) {
+ state.isFetchingSavedQueries = payload;
+ },
+
[types.SET_IS_EXECUTING](state: SqlEditorState, payload: boolean) {
state.isExecuting = payload;
},
@@ -155,6 +170,8 @@ type SqlEditorActionsMap = {
setShouldSetContent: typeof mutations.SET_SHOULD_SET_CONTENT;
setQueryHistoryList: typeof mutations.SET_QUERY_HISTORY_LIST;
setIsFetchingQueryHistory: typeof mutations.SET_IS_FETCHING_QUERY_HISTORY;
+ setSavedQueryList: typeof mutations.SET_SAVED_QUERY_LIST;
+ setIsFetchingSavedQueries: typeof mutations.SET_IS_FETCHING_SAVED_QUERIES;
setIsExecuting: typeof mutations.SET_IS_EXECUTING;
};
@@ -164,8 +181,10 @@ const actions = {
setConnectionTree: types.SET_CONNECTION_TREE,
setConnectionContext: types.SET_CONNECTION_CONTEXT,
setShouldSetContent: types.SET_SHOULD_SET_CONTENT,
- setQueryHistory: types.SET_QUERY_HISTORY_LIST,
+ setQueryHistoryList: types.SET_QUERY_HISTORY_LIST,
setIsFetchingQueryHistory: types.SET_IS_FETCHING_QUERY_HISTORY,
+ setSavedQueryList: types.SET_SAVED_QUERY_LIST,
+ setIsFetchingSavedQueries: types.SET_IS_FETCHING_SAVED_QUERIES,
setIsExecuting: types.SET_IS_EXECUTING,
}),
async executeQuery(
@@ -191,7 +210,7 @@ const actions = {
},
{ root: true }
);
- dispatch("sqlEditor/fetchQueryHistory", {}, { root: true });
+ dispatch("fetchQueryHistoryList");
return res;
},
async fetchConnectionByInstanceIdAndDatabaseId(
@@ -216,12 +235,13 @@ const actions = {
databaseName: databaseInfo.name,
});
},
- async fetchQueryHistory({ commit, dispatch, rootGetters }: any) {
+ async fetchQueryHistoryList({ commit, dispatch }: any) {
commit(types.SET_IS_FETCHING_QUERY_HISTORY, true);
- const currentUser = rootGetters["auth/currentUser"]();
const activityList = await dispatch(
"activity/fetchActivityListForQueryHistory",
- currentUser.id,
+ {
+ limit: 50,
+ },
{
root: true,
}
@@ -255,7 +275,79 @@ const actions = {
await dispatch("activity/deleteActivityById", id, {
root: true,
});
- dispatch("sqlEditor/fetchQueryHistory", {}, { root: true });
+ dispatch("fetchQueryHistoryList");
+ },
+ async createSavedQuery(
+ { dispatch }: any,
+ { name, statement }: { name: string; statement: string }
+ ): Promise<SavedQuery> {
+ const resData = (
+ await axios.post(`/api/savedquery`, {
+ data: {
+ type: "createSavedQuery",
+ attributes: {
+ name,
+ statement,
+ },
+ },
+ })
+ ).data.data;
+ dispatch("fetchSavedQueryList");
+
+ return {
+ ...(resData.attributes as Omit<SavedQuery, "id">),
+ id: parseInt(resData.id),
+ };
+ },
+ async fetchSavedQueryList({ commit, dispatch }: any) {
+ commit(types.SET_IS_FETCHING_SAVED_QUERIES, true);
+ const data = (await axios.get(`/api/savedquery`)).data;
+ const savedQueryList: SavedQuery[] = data.data.map(
+ (savedQuery: ResourceObject) => {
+ return {
+ ...(savedQuery.attributes as Omit<SavedQuery, "id">),
+ id: parseInt(savedQuery.id),
+ };
+ }
+ );
+
+ commit(
+ types.SET_SAVED_QUERY_LIST,
+ savedQueryList.sort((a, b) => b.createdTs - a.createdTs)
+ );
+ commit(types.SET_IS_FETCHING_SAVED_QUERIES, false);
+ },
+ async patchSavedQuery(
+ { dispatch }: any,
+ {
+ id,
+ name,
+ statement,
+ }: {
+ id: number;
+ name?: string;
+ statement?: string;
+ }
+ ) {
+ const attributes: any = {};
+ if (name) {
+ attributes.name = name;
+ }
+ if (statement) {
+ attributes.statement = statement;
+ }
+
+ await axios.patch(`/api/savedquery/${id}`, {
+ data: {
+ type: "patchSavedQuery",
+ attributes,
+ },
+ });
+ dispatch("fetchSavedQueryList");
+ },
+ async deleteSavedQuery({ dispatch }: any, id: number) {
+ await axios.delete(`/api/savedquery/${id}`);
+ dispatch("fetchSavedQueryList");
},
};
diff --git a/frontend/src/store/mutation-types.ts b/frontend/src/store/mutation-types.ts
index 4ef2826259..ac969ab9a3 100644
--- a/frontend/src/store/mutation-types.ts
+++ b/frontend/src/store/mutation-types.ts
@@ -6,6 +6,8 @@ export const SET_SHOULD_SET_CONTENT = "SET_SHOULD_SET_CONTENT";
export const SET_IS_EXECUTING = "SET_IS_EXECUTING";
export const SET_QUERY_HISTORY_LIST = "SET_QUERY_HISTORY_LIST";
export const SET_IS_FETCHING_QUERY_HISTORY = "SET_IS_FETCHING_QUERY_HISTORY";
+export const SET_SAVED_QUERY_LIST = "SET_SAVED_QUERY_LIST";
+export const SET_IS_FETCHING_SAVED_QUERIES = "SET_IS_FETCHING_SAVED_QUERIES";
// Editor Selector mutation types
export const SET_EDITOR_SELECTOR_STATE = "SET_EDITOR_SELECTOR_STATE";
diff --git a/frontend/src/types/editorSelector.ts b/frontend/src/types/editorSelector.ts
index 275b19af01..15a0253e9c 100644
--- a/frontend/src/types/editorSelector.ts
+++ b/frontend/src/types/editorSelector.ts
@@ -6,7 +6,7 @@ export interface TabInfo {
queryStatement: string;
selectedStatement: string;
queryResult?: Record<string, any>[];
- currentQueryId?: string;
+ currentQueryId?: number;
}
export type AnyTabInfo = Partial<TabInfo>;
diff --git a/frontend/src/types/id.ts b/frontend/src/types/id.ts
index 0ba99e7bdc..cf95db66f7 100644
--- a/frontend/src/types/id.ts
+++ b/frontend/src/types/id.ts
@@ -68,6 +68,8 @@ export type AnomalyId = IdType;
export type CommandId = IdType;
export type CommandRegisterId = IdType;
+export type SavedQueryId = IdType;
+
// This references to the object id, which can be used as a container.
// Currently, only issue can be used a container.
// The type is used by Activity and Message
diff --git a/frontend/src/types/sqlEditor.ts b/frontend/src/types/sqlEditor.ts
index 6abe89e988..f5e2221ec2 100644
--- a/frontend/src/types/sqlEditor.ts
+++ b/frontend/src/types/sqlEditor.ts
@@ -1,6 +1,13 @@
import * as monaco from "monaco-editor";
-import { InstanceId, DatabaseId, TableId, ViewId, ActivityId } from "../types";
+import {
+ InstanceId,
+ DatabaseId,
+ TableId,
+ ViewId,
+ ActivityId,
+ SavedQueryId,
+} from "../types";
import { Principal } from "./principal";
export type EditorModel = monaco.editor.ITextModel;
@@ -47,7 +54,6 @@ export interface QueryHistory {
creator: Principal;
createdTs: number;
updatedTs: number;
- instanceId: number;
// Domain fields
statement: string;
@@ -59,3 +65,19 @@ export interface QueryHistory {
// Customerize fields
createdAt: string;
}
+
+export interface SavedQuery {
+ id: SavedQueryId;
+
+ // Standard fields
+ creator: Principal;
+ createdTs: number;
+ updatedTs: number;
+
+ // Domain fields
+ name: string;
+ statement: string;
+
+ // Customerize fields
+ createdAt: string;
+}
diff --git a/frontend/src/types/store.ts b/frontend/src/types/store.ts
index 9c4ceb3916..424e159e7d 100644
--- a/frontend/src/types/store.ts
+++ b/frontend/src/types/store.ts
@@ -6,6 +6,7 @@ import {
Policy,
PolicyType,
QueryHistory,
+ SavedQuery,
View,
} from ".";
import { Activity } from "./activity";
@@ -195,6 +196,8 @@ export interface SqlEditorState {
shouldSetContent: boolean;
queryHistoryList: QueryHistory[];
isFetchingQueryHistory: boolean;
+ savedQueryList: SavedQuery[];
+ isFetchingSavedQueries: boolean;
isExecuting: boolean;
isShowExecutingHint: boolean;
}
diff --git a/frontend/src/views/SqlEditor/AsidePanel/AsidePanel.vue b/frontend/src/views/SqlEditor/AsidePanel/AsidePanel.vue
index beede37f6f..54bbf4cc90 100644
--- a/frontend/src/views/SqlEditor/AsidePanel/AsidePanel.vue
+++ b/frontend/src/views/SqlEditor/AsidePanel/AsidePanel.vue
@@ -17,8 +17,8 @@
</Pane>
</Splitpanes>
</NTabPane>
- <NTabPane v-if="isDev()" name="queries" tab="Queries">
- Queries Page
+ <NTabPane name="queries" :tab="$t('sql-editor.queries')">
+ <SavedQueryView />
</NTabPane>
<NTabPane name="history" :tab="$t('common.history')">
<QueryHistoryView />
@@ -32,10 +32,10 @@ import { ref, watch } from "vue";
import { useNamespacedState } from "vuex-composition-helpers";
import type { SqlEditorState } from "../../../types";
-import { isDev } from "../../../utils";
import DatabaseTree from "./DatabaseTree.vue";
import TableSchema from "./TableSchema.vue";
import QueryHistoryView from "./QueryHistoryView.vue";
+import SavedQueryView from "./SavedQueryView.vue";
const FULL_HEIGHT = 100;
const DATABASE_PANE_SIZE = 60;
diff --git a/frontend/src/views/SqlEditor/AsidePanel/SavedQueryView.vue b/frontend/src/views/SqlEditor/AsidePanel/SavedQueryView.vue
new file mode 100644
index 0000000000..d82306ea4d
--- /dev/null
+++ b/frontend/src/views/SqlEditor/AsidePanel/SavedQueryView.vue
@@ -0,0 +1,278 @@
+<template>
+ <div
+ class="relative p-2 space-y-2 w-full h-full flex flex-col justify-start items-start"
+ >
+ <div class="w-full">
+ <NInput
+ v-model:value="state.search"
+ :placeholder="$t('sql-editor.search-saved-queries')"
+ >
+ <template #prefix>
+ <heroicons-outline:search class="h-5 w-5 text-gray-300" />
+ </template>
+ </NInput>
+ </div>
+ <div class="w-full flex flex-col justify-start items-start overflow-y-auto">
+ <div
+ v-for="query in data"
+ :key="query.id"
+ class="w-full px-1 pr-2 py-2 border-b flex flex-col justify-start items-start"
+ :class="`${
+ currentTab.currentQueryId === query.id
+ ? 'bg-gray-100 rounded border-b-0'
+ : ''
+ }`"
+ @click="handleSavedQueryClick(query)"
+ >
+ <div class="pb-1 w-full flex flex-row justify-between items-center">
+ <div
+ class="w-full mr-2"
+ @dblclick="handleEditSavedQuery(query.id, query.name)"
+ >
+ <input
+ v-if="state.editingSavedQueryId === query.id"
+ ref="queryNameInputerRef"
+ v-model="state.currentSavedQueryName"
+ type="text"
+ class="rounded px-2 py-0 text-sm w-full"
+ @blur="handleSavedQueryNameChanged"
+ @keyup.enter="handleSavedQueryNameChanged"
+ @keyup.esc="handleCancelEdit"
+ />
+ <span v-else class="text-sm">{{ query.name }}</span>
+ </div>
+ <NDropdown
+ trigger="click"
+ :options="historyDropdownOptions"
+ @select="(key: string) => handleActionBtnClick(key, query)"
+ @clickoutside="handleActionBtnOutsideClick"
+ >
+ <NButton text @click.stop>
+ <template #icon>
+ <heroicons-outline:dots-horizontal
+ class="h-4 w-4 text-gray-500 flex-shrink-0"
+ />
+ </template>
+ </NButton>
+ </NDropdown>
+ </div>
+ <p
+ class="max-w-full text-gray-400 break-words font-mono truncate"
+ style="font-size: 10px"
+ >
+ {{ query.statement }}
+ </p>
+ </div>
+ </div>
+
+ <div
+ v-show="notifyMessage"
+ class="absolute w-full h-full flex justify-center items-center transition-all bg-transparent"
+ >
+ {{ notifyMessage }}
+ </div>
+
+ <div
+ v-show="isLoading && savedQueryList.length === 0"
+ class="absolute w-full h-full flex justify-center items-center"
+ >
+ <BBSpin :title="$t('common.loading')" />
+ </div>
+ </div>
+
+ <BBModal
+ v-if="state.isShowDeletingHint"
+ :title="$t('common.tips')"
+ @close="handleHintClose"
+ >
+ <DeleteHint
+ :content="$t('sql-editor.hint-tips.confirm-to-delete-this-history')"
+ @close="handleHintClose"
+ @confirm="handleDeleteSavedQuery"
+ />
+ </BBModal>
+</template>
+
+<script lang="ts" setup>
+import { computed, reactive, ref, nextTick } from "vue";
+import { useI18n } from "vue-i18n";
+import {
+ useNamespacedActions,
+ useNamespacedGetters,
+ useNamespacedState,
+} from "vuex-composition-helpers";
+import {
+ EditorSelectorActions,
+ EditorSelectorGetters,
+ EditorSelectorState,
+ SavedQuery,
+ SqlEditorActions,
+ SqlEditorState,
+} from "../../../types";
+import DeleteHint from "./DeleteHint.vue";
+
+interface State {
+ search: string;
+ isShowDeletingHint: boolean;
+ currentSavedQueryName: string;
+ editingSavedQueryId: number | null;
+ currentActionSavedQuery: SavedQuery | null;
+}
+
+const { t } = useI18n();
+
+const { savedQueryList, isFetchingSavedQueries: isLoading } =
+ useNamespacedState<SqlEditorState>("sqlEditor", [
+ "savedQueryList",
+ "isFetchingSavedQueries",
+ ]);
+const { queryTabList } = useNamespacedState<EditorSelectorState>(
+ "editorSelector",
+ ["queryTabList"]
+);
+const { currentTab } = useNamespacedGetters<EditorSelectorGetters>(
+ "editorSelector",
+ ["currentTab"]
+);
+const { deleteSavedQuery, setShouldSetContent, patchSavedQuery } =
+ useNamespacedActions<SqlEditorActions>("sqlEditor", [
+ "deleteSavedQuery",
+ "setShouldSetContent",
+ "patchSavedQuery",
+ ]);
+const { updateActiveTab, setActiveTabId } =
+ useNamespacedActions<EditorSelectorActions>("editorSelector", [
+ "updateActiveTab",
+ "setActiveTabId",
+ ]);
+
+const state = reactive<State>({
+ search: "",
+ currentSavedQueryName: "",
+ editingSavedQueryId: null,
+ isShowDeletingHint: false,
+ currentActionSavedQuery: null,
+});
+
+const queryNameInputerRef = ref<HTMLInputElement>();
+
+const data = computed(() => {
+ const temp =
+ savedQueryList.value && savedQueryList.value.length > 0
+ ? savedQueryList.value.filter((savedQuery) => {
+ let t = false;
+
+ if (savedQuery.statement.includes(state.search)) {
+ t = true;
+ }
+
+ return t;
+ })
+ : [];
+ return temp;
+});
+
+const notifyMessage = computed(() => {
+ if (isLoading.value) {
+ return "";
+ }
+ if (savedQueryList.value.length === null) {
+ return t("sql-editor.no-history-found");
+ }
+
+ return "";
+});
+
+const historyDropdownOptions = computed(() => [
+ {
+ label: t("common.delete"),
+ key: "delete",
+ },
+]);
+
+const handleEditSavedQuery = (id: number, name: string) => {
+ state.editingSavedQueryId = id;
+ state.currentSavedQueryName = name;
+ nextTick(() => {
+ queryNameInputerRef.value?.focus();
+ });
+};
+
+const handleCancelEdit = () => {
+ state.editingSavedQueryId = null;
+ state.currentSavedQueryName = "";
+};
+
+const handleSavedQueryNameChanged = () => {
+ if (state.editingSavedQueryId) {
+ patchSavedQuery({
+ id: state.editingSavedQueryId,
+ name: state.currentSavedQueryName,
+ });
+
+ if (currentTab.value.currentQueryId === state.editingSavedQueryId) {
+ updateActiveTab({
+ label: state.currentSavedQueryName,
+ });
+ }
+ handleCancelEdit();
+ }
+};
+
+const handleActionBtnClick = (key: string, savedQuery: SavedQuery) => {
+ state.currentActionSavedQuery = savedQuery;
+
+ if (key === "delete") {
+ state.isShowDeletingHint = true;
+ }
+};
+
+const handleActionBtnOutsideClick = () => {
+ state.currentActionSavedQuery = null;
+};
+
+const handleHintClose = () => {
+ state.currentActionSavedQuery = null;
+ state.isShowDeletingHint = false;
+};
+
+const handleDeleteSavedQuery = () => {
+ if (state.currentActionSavedQuery) {
+ deleteSavedQuery(state.currentActionSavedQuery.id);
+
+ if (currentTab.value.currentQueryId === state.currentActionSavedQuery.id) {
+ updateActiveTab({
+ currentQueryId: undefined,
+ });
+ }
+ }
+ state.isShowDeletingHint = false;
+};
+
+const handleSavedQueryClick = (savedQuery: SavedQuery) => {
+ if (currentTab.value.currentQueryId === savedQuery.id) {
+ if (state.editingSavedQueryId !== savedQuery.id) {
+ updateActiveTab({
+ label: "Untitled Queries",
+ currentQueryId: undefined,
+ });
+ }
+ } else {
+ for (const tab of queryTabList.value) {
+ if (tab.currentQueryId === savedQuery.id) {
+ setActiveTabId(tab.id);
+ setShouldSetContent(true);
+ return;
+ }
+ }
+
+ updateActiveTab({
+ label: savedQuery.name,
+ queryStatement: savedQuery.statement,
+ selectedStatement: "",
+ currentQueryId: savedQuery.id,
+ });
+ setShouldSetContent(true);
+ }
+};
+</script>
diff --git a/frontend/src/views/SqlEditor/EditorPanel/EditorAction.vue b/frontend/src/views/SqlEditor/EditorPanel/EditorAction.vue
index b5b56cdeb6..1b9344eab2 100644
--- a/frontend/src/views/SqlEditor/EditorPanel/EditorAction.vue
+++ b/frontend/src/views/SqlEditor/EditorPanel/EditorAction.vue
@@ -22,11 +22,11 @@
@update:value="handleConnectionChange"
/>
<NButton
- v-if="isDev()"
secondary
strong
type="primary"
- :disabled="isEmptyStatement"
+ :disabled="isEmptyStatement || currentTab.isSaved"
+ @click="handleSaveQueryBtnClick"
>
<carbon:save class="h-5 w-5" /> &nbsp; {{ $t("common.save") }} (⌘+S)
</NButton>
@@ -52,6 +52,7 @@ import {
SqlEditorActions,
ConnectionContext,
EditorSelectorGetters,
+ EditorSelectorActions,
} from "../../../types";
import { useExecuteSQL } from "../../../composables/useExecuteSQL";
import { isDev } from "../../../utils";
@@ -65,9 +66,15 @@ const { currentTab } = useNamespacedGetters<EditorSelectorGetters>(
"editorSelector",
["currentTab"]
);
-const { setConnectionContext } = useNamespacedActions<SqlEditorActions>(
- "sqlEditor",
- ["setConnectionContext"]
+const { createSavedQuery, setConnectionContext, patchSavedQuery } =
+ useNamespacedActions<SqlEditorActions>("sqlEditor", [
+ "createSavedQuery",
+ "setConnectionContext",
+ "patchSavedQuery",
+ ]);
+const { updateActiveTab } = useNamespacedActions<EditorSelectorActions>(
+ "editorSelector",
+ ["updateActiveTab"]
);
const isEmptyStatement = computed(
@@ -128,6 +135,28 @@ const handleConnectionChange = (
});
}
};
+
+const handleSaveQueryBtnClick = async () => {
+ const { queryStatement, label, currentQueryId } = currentTab.value;
+
+ if (currentQueryId) {
+ patchSavedQuery({
+ id: currentQueryId,
+ statement: queryStatement,
+ });
+ } else {
+ const newSavedQuery = await createSavedQuery({
+ name: label,
+ statement: queryStatement,
+ });
+ updateActiveTab({
+ currentQueryId: newSavedQuery.id,
+ });
+ }
+ updateActiveTab({
+ isSaved: true,
+ });
+};
</script>
<style scoped>
diff --git a/frontend/src/views/SqlEditor/EditorPanel/QueryEditor.vue b/frontend/src/views/SqlEditor/EditorPanel/QueryEditor.vue
index 1b69ff6979..5a26940bb0 100644
--- a/frontend/src/views/SqlEditor/EditorPanel/QueryEditor.vue
+++ b/frontend/src/views/SqlEditor/EditorPanel/QueryEditor.vue
@@ -4,6 +4,7 @@
@change="handleChange"
@change-selection="handleChangeSelection"
@run-query="handleRunQuery"
+ @save="handleSave"
/>
</template>
@@ -11,27 +12,39 @@
import { computed } from "vue";
import { debounce } from "lodash-es";
-import { EditorSelectorActions, TabInfo } from "../../../types";
+import {
+ EditorSelectorActions,
+ EditorSelectorGetters,
+ SqlEditorActions,
+} from "../../../types";
import { useExecuteSQL } from "../../../composables/useExecuteSQL";
-import { useStore } from "vuex";
-import { useNamespacedActions } from "vuex-composition-helpers";
+import {
+ useNamespacedActions,
+ useNamespacedGetters,
+} from "vuex-composition-helpers";
-const store = useStore();
-const activeTab = computed<TabInfo>(
- () => store.getters["editorSelector/currentTab"]
+const { currentTab } = useNamespacedGetters<EditorSelectorGetters>(
+ "editorSelector",
+ ["currentTab"]
);
const { updateActiveTab } = useNamespacedActions<EditorSelectorActions>(
"editorSelector",
["updateActiveTab"]
);
+const { createSavedQuery, patchSavedQuery } =
+ useNamespacedActions<SqlEditorActions>("sqlEditor", [
+ "createSavedQuery",
+ "patchSavedQuery",
+ ]);
const { execute } = useExecuteSQL();
-const sqlCode = computed(() => activeTab.value.queryStatement);
+const sqlCode = computed(() => currentTab.value.queryStatement);
const handleChange = debounce((value: string) => {
updateActiveTab({
queryStatement: value,
+ isSaved: false,
});
}, 300);
@@ -41,6 +54,28 @@ const handleChangeSelection = debounce((value: string) => {
});
}, 300);
+const handleSave = async (statement: string) => {
+ const { label, currentQueryId } = currentTab.value;
+
+ if (currentQueryId) {
+ patchSavedQuery({
+ id: currentQueryId,
+ statement,
+ });
+ } else {
+ const newSavedQuery = await createSavedQuery({
+ name: label,
+ statement,
+ });
+ updateActiveTab({
+ currentQueryId: newSavedQuery.id,
+ });
+ }
+ updateActiveTab({
+ isSaved: true,
+ });
+};
+
const handleRunQuery = () => {
execute();
};
diff --git a/frontend/src/views/SqlEditor/QuerySelector.vue b/frontend/src/views/SqlEditor/QuerySelector.vue
index d21caa56a4..3d6dab80f3 100644
--- a/frontend/src/views/SqlEditor/QuerySelector.vue
+++ b/frontend/src/views/SqlEditor/QuerySelector.vue
@@ -40,7 +40,7 @@
class="rounded px-2 py-0 text-sm w-full absolute left-0 bottom-0"
@blur="(e: Event) => handleTryChangeLabel()"
@keyup.enter="(e: Event) => handleTryChangeLabel()"
- @keyup.esc="(e: Event) => handleCancelInput()"
+ @keyup.esc="handleCancelInput"
/>
<!-- this is a trick -->
<span class="w-full h-full invisible line-camp-1">
@@ -127,6 +127,7 @@ import {
EditorSelectorGetters,
EditorSelectorState,
EditorSelectorActions,
+ SqlEditorActions,
} from "../../types";
import { debounce } from "lodash-es";
@@ -146,6 +147,10 @@ const { addTab, removeTab, setActiveTabId, updateActiveTab } =
"setActiveTabId",
"updateActiveTab",
]);
+const { patchSavedQuery } = useNamespacedActions<SqlEditorActions>(
+ "sqlEditor",
+ ["patchSavedQuery"]
+);
const store = useStore();
const { t } = useI18n();
@@ -198,6 +203,12 @@ const handleTryChangeLabel = () => {
updateActiveTab({
label: labelState.currentLabelName,
});
+ if (currentTab.value.currentQueryId) {
+ patchSavedQuery({
+ id: currentTab.value.currentQueryId,
+ name: labelState.currentLabelName,
+ });
+ }
nextTick(() => {
reComputedScrollWidth();
scrollState.style = {
@@ -217,6 +228,12 @@ const handleCancelInput = () => {
updateActiveTab({
label: labelState.currentLabelName,
});
+ if (currentTab.value.currentQueryId) {
+ patchSavedQuery({
+ id: currentTab.value.currentQueryId,
+ name: labelState.currentLabelName,
+ });
+ }
nextTick(() => {
labelState.isEditingLabel = false;
reComputedScrollWidth();
diff --git a/server/acl.go b/server/acl.go
index 9266dae595..1840efce3f 100644
--- a/server/acl.go
+++ b/server/acl.go
@@ -156,6 +156,24 @@ func isUpdatingSelf(ctx context.Context, c echo.Context, s *Server, curPrincipal
}
return inbox.ReceiverID == curPrincipalID, nil
}
+ } else if strings.HasPrefix(c.Path(), "/api/savedquery") {
+ if idStr := c.Param("id"); idStr != "" {
+ id, err := strconv.Atoi(idStr)
+ if err != nil {
+ return false, echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Saved query ID is not a number: %s", idStr))
+ }
+ savedQueryFind := &api.SavedQueryFind{
+ ID: &id,
+ }
+ savedQuery, err := s.SavedQueryService.FindSavedQuery(ctx, savedQueryFind)
+ if err != nil {
+ return false, echo.NewHTTPError(http.StatusInternalServerError, defaultErrMsg).SetInternal(err)
+ }
+ if savedQuery == nil {
+ return false, echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Saved query ID not found: %d", id))
+ }
+ return savedQuery.CreatorID == curPrincipalID, nil
+ }
}
return false, nil
}
diff --git a/server/acl_casbin_policy_dba.csv b/server/acl_casbin_policy_dba.csv
index 3f628a530a..ca016d376c 100644
--- a/server/acl_casbin_policy_dba.csv
+++ b/server/acl_casbin_policy_dba.csv
@@ -82,5 +82,5 @@ p, DBA, /label, GET
p, DBA, /label/{id}, PATCH
p, DBA, /savedquery, POST
p, DBA, /savedquery, GET
-p, DBA, /savedquery/{id}, PATCH
+p, DBA, /savedquery/{id}, PATCH_SELF
p, DBA, /savedquery/{id}, DELETE_SELF
diff --git a/server/acl_casbin_policy_developer.csv b/server/acl_casbin_policy_developer.csv
index 038dbf2995..a2348c8fdd 100644
--- a/server/acl_casbin_policy_developer.csv
+++ b/server/acl_casbin_policy_developer.csv
@@ -72,5 +72,5 @@ p, DEVELOPER, /setting, GET
p, DEVELOPER, /label, GET
p, DEVELOPER, /savedquery, POST
p, DEVELOPER, /savedquery, GET
-p, DEVELOPER, /savedquery/{id}, PATCH
+p, DEVELOPER, /savedquery/{id}, PATCH_SELF
p, DEVELOPER, /savedquery/{id}, DELETE_SELF
diff --git a/server/acl_casbin_policy_owner.csv b/server/acl_casbin_policy_owner.csv
index f98baeb9ad..8497dbdd2b 100644
--- a/server/acl_casbin_policy_owner.csv
+++ b/server/acl_casbin_policy_owner.csv
@@ -88,5 +88,5 @@ p, OWNER, /label, GET
p, OWNER, /label/{id}, PATCH
p, OWNER, /savedquery, POST
p, OWNER, /savedquery, GET
-p, OWNER, /savedquery/{id}, PATCH
+p, OWNER, /savedquery/{id}, PATCH_SELF
p, OWNER, /savedquery/{id}, DELETE_SELF