Skip to content

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

feat(sql-editor): SQL editor sharing feature part Ⅱ (#585)

Yunwei Xiao542d1f9a5352
diff --git a/api/sheet.go b/api/sheet.go
index ef39f7b837..1f52919916 100644
--- a/api/sheet.go
+++ b/api/sheet.go
@@ -43,7 +43,9 @@ type Sheet struct {
// Related fields
InstanceID int `jsonapi:"attr,instanceId"`
+ Instance *Instance `jsonapi:"relation,instance"`
DatabaseID *int `jsonapi:"attr,databaseId"`
+ Database *Database `jsonapi:"relation,database"`
// Domain specific fields
Name string `jsonapi:"attr,name"`
diff --git a/frontend/src/components/MonacoEditor/MonacoEditor.vue b/frontend/src/components/MonacoEditor/MonacoEditor.vue
index 1c372a329b..31f0bd0f87 100644
--- a/frontend/src/components/MonacoEditor/MonacoEditor.vue
+++ b/frontend/src/components/MonacoEditor/MonacoEditor.vue
@@ -56,10 +56,7 @@ const language = toRef(props, "language");
const { shouldSetContent } = useNamespacedState<SqlEditorState>("sqlEditor", [
"shouldSetContent",
]);
-const { currentTab } = useNamespacedGetters<TabGetters>(
- "tab",
- ["currentTab"]
-);
+const { currentTab } = useNamespacedGetters<TabGetters>("tab", ["currentTab"]);
const { setShouldSetContent } = useNamespacedActions<SqlEditorActions>(
"sqlEditor",
["setShouldSetContent"]
@@ -165,7 +162,7 @@ watch(
() => {
if (shouldSetContent.value) {
setShouldSetContent(false);
- setContent(editorInstance, currentTab.value.queryStatement);
+ setContent(editorInstance, currentTab.value.statement);
}
}
);
diff --git a/frontend/src/components/ProvideSqlEditorContext.vue b/frontend/src/components/ProvideSqlEditorContext.vue
index a4f0aed8cd..ec8d10045e 100644
--- a/frontend/src/components/ProvideSqlEditorContext.vue
+++ b/frontend/src/components/ProvideSqlEditorContext.vue
@@ -55,9 +55,7 @@ const prepareAccessibleConnectionByProject = async () => {
};
const prepareSqlEdtiorContext = async () => {
- store.dispatch("sqlEditor/setConnectionContext", {
- isLoadingTree: true,
- });
+ store.dispatch("sqlEditor/setConnectionContext", { isLoadingTree: true });
let connectionTree = [];
const mapConnectionAtom =
@@ -112,11 +110,11 @@ const prepareSqlEdtiorContext = async () => {
}
store.dispatch("sqlEditor/setConnectionTree", connectionTree);
- store.dispatch("sqlEditor/setConnectionContext", {
- isLoadingTree: false,
- });
+ store.dispatch("sqlEditor/setConnectionContext", { isLoadingTree: false });
store.dispatch("sqlEditor/fetchQueryHistoryList");
- store.dispatch("sqlEditor/fetchSavedQueryList");
+ store.dispatch("sqlEditor/setSqlEditorState", { isFetchingSheet: true });
+ store.dispatch("sheet/fetchSheetList");
+ store.dispatch("sqlEditor/setSqlEditorState", { isFetchingSheet: false });
};
onMounted(async () => {
diff --git a/frontend/src/composables/useExecuteSQL.ts b/frontend/src/composables/useExecuteSQL.ts
index c8a890b757..a0d6484c68 100644
--- a/frontend/src/composables/useExecuteSQL.ts
+++ b/frontend/src/composables/useExecuteSQL.ts
@@ -32,13 +32,12 @@ const useExecuteSQL = () => {
}
const currentTab = store.getters["tab/currentTab"];
- const queryStatement = currentTab.queryStatement;
+ const isDisconnected = store.getters["sqlEditor/isDisconnected"];
+ const statement = currentTab.statement;
const selectedStatement = currentTab.selectedStatement;
- const sqlStatement = selectedStatement || queryStatement;
+ const sqlStatement = selectedStatement || statement;
- const ctx = store.state.sqlEditor.connectionContext;
-
- if (ctx.instanceId === 0 || ctx.databaseId === 0) {
+ if (isDisconnected) {
notify("CRITICAL", t("sql-editor.select-connection"));
return;
}
diff --git a/frontend/src/composables/useSQLEditorConnection.ts b/frontend/src/composables/useSQLEditorConnection.ts
new file mode 100644
index 0000000000..18b8a03da0
--- /dev/null
+++ b/frontend/src/composables/useSQLEditorConnection.ts
@@ -0,0 +1,58 @@
+import { useRouter } from "vue-router";
+import { useStore } from "vuex";
+
+import { SheetState } from "../types";
+import { connectionSlug } from "../utils";
+import { getDefaultConnectionContext } from "../store/modules/sqlEditor";
+
+const useSQLEditorConnection = () => {
+ const router = useRouter();
+ const store = useStore();
+
+ /**
+ * Set the connection by tab info
+ * @param param
+ * @param payload
+ */
+ const setConnectionContextFromCurrentTab = () => {
+ const currentTab = store.getters["tab/currentTab"];
+ const sheetById = store.state.sheet.sheetById as SheetState["sheetById"];
+
+ if (currentTab.sheetId && sheetById.has(currentTab.sheetId)) {
+ const sheet = sheetById.get(currentTab.sheetId);
+
+ const database = store.getters["database/databaseById"](
+ sheet?.databaseId,
+ sheet?.instanceId
+ );
+
+ store.dispatch("sqlEditor/setConnectionContext", {
+ hasSlug: true,
+ databaseId: sheet?.databaseId,
+ instanceId: sheet?.instanceId,
+ });
+
+ router.replace({
+ name: "sql-editor.detail",
+ params: {
+ connectionSlug: connectionSlug(database),
+ },
+ });
+ } else {
+ store.dispatch(
+ "sqlEditor/setConnectionContext",
+ getDefaultConnectionContext()
+ );
+
+ router.push({
+ path: "/sql-editor",
+ });
+ }
+ };
+
+ return {
+ setConnectionContextFromCurrentTab,
+ };
+};
+
+export { useSQLEditorConnection };
diff --git a/frontend/src/locales/en.yml b/frontend/src/locales/en.yml
index 22dbb855cc..358d986f17 100644
--- a/frontend/src/locales/en.yml
+++ b/frontend/src/locales/en.yml
@@ -1095,18 +1095,20 @@ sql-editor:
can-not-execute-query: Can not execute query when loading data.
rows: row | rows
no-history-found: No history found
- no-saved-query-found: No saved query found
+ no-sheet-found: No sheet found
search-history: Search History
- search-saved-queries: Search Saved Queries
- queries: Queries
+ search-sheets: Search Sheets
hint-tips:
confirm-to-delete-this-history: Confirm to delete this history?
- confirm-to-delete-this-saved-query: Confirm to delete this saved query?
+ confirm-to-delete-this-sheet: Confirm to delete this sheet?
please-input-the-tab-label: Please input the tab label!
copy-code: Copy code
notify:
copy-code-succeed: Copy code succeed
view-all-tabs: View all Tabs
+ sheet: Sheet
+ sheets: Sheets
+ connection-holder: Select a connection or select a sheet from left panel to get started
label:
empty-label-value: <Empty Value>
no-label: No labels
diff --git a/frontend/src/locales/zh-CN.yml b/frontend/src/locales/zh-CN.yml
index a0fdebbfb8..334e4381f8 100644
--- a/frontend/src/locales/zh-CN.yml
+++ b/frontend/src/locales/zh-CN.yml
@@ -952,7 +952,7 @@ sql-editor:
close-pane: 关闭面板
loading-data: 加载数据中...
table-empty-placehoder: 点击 ”运行“ 执行查询
- no-rows-found: 无数据
+ no-rows-found: 暂无数据
download-as-csv: 下载为 CSV 格式
download-as-json: 下载为 JSON 格式
only-select-allowed: 只允许执行 {select} 语句
@@ -965,19 +965,21 @@ sql-editor:
goto-alter-schema-hint: 请从编辑器顶部选择一个数据库连接
can-not-execute-query: 加载数据时无法执行查询
rows: 条记录
- no-history-found: 无历史记录
- no-saved-query-found: 无归档查询语句
+ no-history-found: 暂无历史记录
+ no-sheet-found: 暂无工作表
search-history: 搜索历史记录
- search-saved-queries: 搜索归档查询
- queries: 归档查询
+ search-sheets: 搜索工作表
hint-tips:
confirm-to-delete-this-history: 确定删除这条记录?
- confirm-to-delete-this-saved-query: 确定删除这条查询语句?
+ confirm-to-delete-this-sheet: 确定删除这条查询语句?
please-input-the-tab-label: 请输入标签页名称!
copy-code: 复制代码
notify:
copy-code-succeed: 代码复制成功
view-all-tabs: 查看所有标签页
+ sheet: 工作表
+ sheets: 工作表
+ connection-holder: 选择一个数据连接或者从左侧面板选择一个工作表以开始
label:
empty-label-value: <空值>
no-label: 没有标签
diff --git a/frontend/src/store/index.ts b/frontend/src/store/index.ts
index 51f555acde..9c1fa05407 100644
--- a/frontend/src/store/index.ts
+++ b/frontend/src/store/index.ts
@@ -1,5 +1,4 @@
import { createStore, Store } from "vuex";
-import createPersistedState from "vuex-persistedstate";
/**
* Following states are persisted in database
@@ -20,10 +19,5 @@ const isProd = import.meta.env.NODE_ENV == "production";
export const store: Store<any> = createStore({
modules,
- plugins: [
- createPersistedState({
- paths: ["tab"],
- }),
- ],
strict: !isProd,
});
diff --git a/frontend/src/store/modules/sheet.ts b/frontend/src/store/modules/sheet.ts
new file mode 100644
index 0000000000..28b5647e4a
--- /dev/null
+++ b/frontend/src/store/modules/sheet.ts
@@ -0,0 +1,233 @@
+import axios from "axios";
+import { isEmpty } from "lodash-es";
+
+import * as types from "../mutation-types";
+import { makeActions } from "../actions";
+import type {
+ Sheet,
+ SheetId,
+ SheetState,
+ SheetPatch,
+ CreateSheetState,
+ Principal,
+ ResourceObject,
+ ResourceIdentifier,
+ ConnectionContext,
+ TabInfo,
+ Instance,
+ Database,
+} from "../../types";
+import { unknown } from "../../types";
+import { getPrincipalFromIncludedList } from "./principal";
+
+function convertSheet(
+ sheet: ResourceObject,
+ includedList: ResourceObject[],
+ rootGetters: any
+): Sheet {
+ const instanceId = (sheet.relationships!.instance.data as ResourceIdentifier)
+ .id;
+
+ let instance: Instance = unknown("INSTANCE") as Instance;
+
+ const databaseId = (sheet.relationships!.database.data as ResourceIdentifier)
+ .id;
+
+ let database: Database = unknown("DATABASE") as Database;
+
+ for (const item of includedList || []) {
+ if (item.type == "instance" && item.id == instanceId) {
+ instance = rootGetters["instance/convert"](item, includedList);
+ }
+ if (item.type == "database" && item.id == databaseId) {
+ database = rootGetters["database/convert"](item, includedList);
+ }
+ }
+
+ return {
+ ...(sheet.attributes as Omit<Sheet, "id" | "creator" | "updater">),
+ creator: getPrincipalFromIncludedList(
+ sheet.relationships!.creator.data,
+ includedList
+ ) as Principal,
+ updater: getPrincipalFromIncludedList(
+ sheet.relationships!.updater.data,
+ includedList
+ ) as Principal,
+ instance,
+ database,
+ id: parseInt(sheet.id),
+ };
+}
+
+const state: () => SheetState = () => {
+ return {
+ sheetList: [],
+ sheetById: new Map(),
+ };
+};
+
+const getters = {
+ currentSheet: (
+ state: SheetState,
+ getters: any,
+ rootState: any,
+ rootGetters: any
+ ): Sheet => {
+ const currentTab = rootGetters["tab/currentTab"];
+
+ if (!currentTab || isEmpty(currentTab)) return unknown("SHEET") as Sheet;
+
+ const sheetId = currentTab.sheetId;
+
+ return state.sheetById.get(sheetId) || (unknown("SHEET") as Sheet);
+ },
+};
+
+const mutations = {
+ [types.SET_SHEET_STATE](state: SheetState, payload: Partial<SheetState>) {
+ Object.assign(state, payload);
+ },
+ [types.SET_SHEET_LIST](state: SheetState, payload: Sheet[]) {
+ state.sheetList = payload;
+ },
+ [types.SET_SHEET_BY_ID](
+ state: SheetState,
+ { sheetId, sheet }: { sheetId: SheetId; sheet: Sheet }
+ ) {
+ state.sheetById.set(sheetId, sheet);
+ },
+ [types.DELETE_SHEET](state: SheetState, sheetId: SheetId) {
+ const idx = state.sheetList.findIndex((sheet) => sheet.id === sheetId);
+ if (idx !== -1) state.sheetList.splice(idx, 1);
+
+ if (state.sheetById.has(sheetId)) {
+ state.sheetById.delete(sheetId);
+ }
+ },
+};
+
+type ActionsMap = {
+ setSheetState: typeof mutations.SET_SHEET_STATE;
+ setSheetList: typeof mutations.SET_SHEET_LIST;
+};
+
+const actions = {
+ ...makeActions<ActionsMap>({
+ setSheetState: types.SET_SHEET_STATE,
+ setSheetList: types.SET_SHEET_LIST,
+ }),
+ // create
+ async createSheet(
+ { commit, state, rootState, rootGetters }: any,
+ sheetRecord?: CreateSheetState
+ ): Promise<Sheet> {
+ const ctx = rootState.sqlEditor.connectionContext as ConnectionContext;
+ const tab = rootGetters["tab/currentTab"] as TabInfo;
+
+ const result = (
+ await axios.post(`/api/sheet`, {
+ data: {
+ type: "createSheet",
+ attributes: {
+ instanceId: ctx.instanceId,
+ databaseId: ctx.databaseId,
+ name: tab.name,
+ statement: tab.statement,
+ visibility: "PRIVATE",
+ },
+ },
+ })
+ ).data;
+ const newSheet = convertSheet(result.data, result.included, rootGetters);
+
+ commit(
+ types.SET_SHEET_LIST,
+ (state.sheetList as Sheet[])
+ .concat(newSheet)
+ .sort((a, b) => b.createdTs - a.createdTs)
+ );
+
+ commit(types.SET_SHEET_BY_ID, {
+ sheetId: newSheet.id,
+ sheet: newSheet,
+ });
+
+ return newSheet;
+ },
+ // retrieve
+ async fetchSheetList({ commit, dispatch, state, rootGetters }: any) {
+ const data = (await axios.get(`/api/sheet`)).data;
+ const sheetList: Sheet[] = data.data.map((sheet: ResourceObject) => {
+ const newSheet = convertSheet(sheet, data.included, rootGetters);
+ commit(types.SET_SHEET_BY_ID, {
+ sheetId: newSheet.id,
+ sheet: newSheet,
+ });
+ return newSheet;
+ });
+
+ commit(
+ types.SET_SHEET_LIST,
+ sheetList.sort((a, b) => b.createdTs - a.createdTs)
+ );
+ },
+ // update
+ async patchSheetById(
+ { dispatch, rootGetters }: any,
+ { id, name, statement, visibility }: SheetPatch
+ ): Promise<Sheet> {
+ const attributes: Omit<SheetPatch, "id"> = {};
+ if (name) {
+ attributes.name = name;
+ }
+ if (statement) {
+ attributes.statement = statement;
+ }
+ if (visibility) {
+ attributes.visibility = visibility;
+ }
+
+ const result = (
+ await axios.patch(`/api/sheet/${id}`, {
+ data: {
+ type: "sheetPatch",
+ attributes,
+ },
+ })
+ ).data;
+
+ const newSheet = convertSheet(result.data, result.included, rootGetters);
+
+ dispatch("fetchSheetList");
+
+ return newSheet;
+ },
+ // delete
+ async deleteSheet({ commit, state }: any, id: number) {
+ await axios.delete(`/api/sheet/${id}`);
+
+ commit(types.DELETE_SHEET, id);
+ },
+ // upsert
+ async upsertSheet(
+ { commit, dispatch, state }: any,
+ payload: Partial<Sheet>
+ ): Promise<Sheet> {
+ const hasSheet = state.sheetById.has(payload.id);
+
+ if (hasSheet) {
+ return dispatch("patchSheetById", payload);
+ } else {
+ return dispatch("createSheet");
+ }
+ },
+};
+
+export default {
+ namespaced: true,
+ state,
+ getters,
+ actions,
+ mutations,
+};
diff --git a/frontend/src/store/modules/sql.ts b/frontend/src/store/modules/sql.ts
index c2af399b93..7e7e24a700 100644
--- a/frontend/src/store/modules/sql.ts
+++ b/frontend/src/store/modules/sql.ts
@@ -88,7 +88,7 @@ const actions = {
).data.data;
const resultSet = convert(data);
- return resultSet;
+ return resultSet.data;
},
};
diff --git a/frontend/src/store/modules/sqlEditor.ts b/frontend/src/store/modules/sqlEditor.ts
index 278222d488..601477dbe6 100644
--- a/frontend/src/store/modules/sqlEditor.ts
+++ b/frontend/src/store/modules/sqlEditor.ts
@@ -1,4 +1,3 @@
-import axios from "axios";
import dayjs from "dayjs";
import { isEmpty } from "lodash-es";
@@ -11,56 +10,34 @@ import {
DatabaseId,
ProjectId,
QueryHistory,
- SavedQuery,
- ResourceObject,
+ UNKNOWN_ID,
} from "../../types";
import * as types from "../mutation-types";
import { makeActions } from "../actions";
-import { getPrincipalFromIncludedList } from "./principal";
-function convertSavedQuery(
- savedQuery: ResourceObject,
- includedList: ResourceObject[]
-): SavedQuery {
- return {
- ...(savedQuery.attributes as Omit<
- SavedQuery,
- "id" | "creator" | "updater"
- >),
- creator: getPrincipalFromIncludedList(
- savedQuery.relationships!.creator.data,
- includedList
- ),
- updater: getPrincipalFromIncludedList(
- savedQuery.relationships!.updater.data,
- includedList
- ),
- id: parseInt(savedQuery.id),
- };
-}
+export const getDefaultConnectionContext = () => ({
+ hasSlug: false,
+ instanceId: UNKNOWN_ID,
+ instanceName: "",
+ databaseId: UNKNOWN_ID,
+ databaseName: "",
+ tableId: UNKNOWN_ID,
+ tableName: "",
+ isLoadingTree: false,
+ selectedDatabaseId: UNKNOWN_ID,
+ selectedTableName: "",
+});
const state: () => SqlEditorState = () => ({
connectionTree: [],
- connectionContext: {
- hasSlug: false,
- instanceId: 0,
- instanceName: "",
- databaseId: 0,
- databaseName: "",
- tableId: 0,
- tableName: "",
- isLoadingTree: false,
- selectedDatabaseId: 0,
- selectedTableName: "",
- },
+ connectionContext: getDefaultConnectionContext(),
isExecuting: false,
isShowExecutingHint: false,
shouldSetContent: false,
// Related data and status
queryHistoryList: [],
isFetchingQueryHistory: false,
- savedQueryList: [],
- isFetchingSavedQueries: false,
+ isFetchingSheet: false,
});
const getters = {
@@ -135,6 +112,13 @@ const getters = {
const connectionContext = state.connectionContext;
return `${connectionContext.instanceId}/${connectionContext.databaseId}/${connectionContext.tableId}`;
},
+ // in case of the connection is not set, miss the instance id, we can not create the sheet
+ isDisconnected(state: SqlEditorState) {
+ return (
+ state.connectionContext.instanceId === UNKNOWN_ID ||
+ state.connectionContext.databaseId === UNKNOWN_ID
+ );
+ },
};
const mutations = {
@@ -174,15 +158,6 @@ 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;
- },
};
type SqlEditorActionsMap = {
@@ -193,8 +168,6 @@ type SqlEditorActionsMap = {
setIsExecuting: typeof mutations.SET_IS_EXECUTING;
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;
};
const actions = {
@@ -206,34 +179,26 @@ const actions = {
setIsExecuting: types.SET_IS_EXECUTING,
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,
}),
async executeQuery(
{ dispatch, state, rootGetters }: any,
payload: Partial<QueryInfo> = {}
) {
const currentTab = rootGetters["tab/currentTab"];
- const res = await dispatch(
+ const queryResult = await dispatch(
"sql/query",
{
instanceId: state.connectionContext.instanceId,
databaseName: state.connectionContext.databaseName,
- statement: currentTab.selectedStatement || currentTab.queryStatement,
+ statement: currentTab.selectedStatement || currentTab.statement,
...payload,
},
{ root: true }
);
- dispatch(
- "tab/updateCurrentTab",
- {
- queryResult: res.data,
- },
- { root: true }
- );
+ dispatch("tab/updateCurrentTab", { queryResult }, { root: true });
dispatch("fetchQueryHistoryList");
- return res;
+ return queryResult;
},
async fetchConnectionByInstanceIdAndDatabaseId(
{ commit, dispatch }: any,
@@ -303,90 +268,6 @@ const actions = {
state.queryHistoryList.filter((t: QueryHistory) => t.id !== id)
);
},
- async createSavedQuery(
- { commit, state }: any,
- { name, statement }: { name: string; statement: string }
- ): Promise<SavedQuery> {
- const data = (
- await axios.post(`/api/savedquery`, {
- data: {
- type: "createSavedQuery",
- attributes: {
- name,
- statement,
- },
- },
- })
- ).data;
- const newSavedQuery = convertSavedQuery(data.data, data.included);
-
- commit(
- types.SET_SAVED_QUERY_LIST,
- (state.savedQueryList as SavedQuery[])
- .concat(newSavedQuery)
- .sort((a, b) => b.createdTs - a.createdTs)
- );
-
- return newSavedQuery;
- },
- async fetchSavedQueryList({ commit }: 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 convertSavedQuery(savedQuery, data.included);
- }
- );
-
- 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({ commit, state }: any, id: number) {
- await axios.delete(`/api/savedquery/${id}`);
- commit(
- types.SET_SAVED_QUERY_LIST,
- state.savedQueryList.filter((t: SavedQuery) => t.id !== id)
- );
- },
- async checkSavedQueryExistById({ state }: any, id: number) {
- for (const savedQuery of state.savedQueryList) {
- if (savedQuery.id === id) {
- return true;
- }
- }
- return false;
- },
};
export default {
diff --git a/frontend/src/store/modules/tab.ts b/frontend/src/store/modules/tab.ts
index 368cb3932e..8ef75ca1d6 100644
--- a/frontend/src/store/modules/tab.ts
+++ b/frontend/src/store/modules/tab.ts
@@ -7,10 +7,10 @@ import { makeActions } from "../actions";
export const getDefaultTab = () => {
return {
id: uuidv1(),
- label: "Untitled Queries",
+ name: "Untitled Sheet",
isSaved: false,
savedAt: dayjs().format("YYYY-MM-DD HH:mm:ss"),
- queryStatement: "",
+ statement: "",
selectedStatement: "",
};
};
diff --git a/frontend/src/store/mutation-types.ts b/frontend/src/store/mutation-types.ts
index 94437c107c..82cb1e5705 100644
--- a/frontend/src/store/mutation-types.ts
+++ b/frontend/src/store/mutation-types.ts
@@ -6,8 +6,6 @@ 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_TAB_STATE = "SET_TAB_STATE";
@@ -16,3 +14,9 @@ export const REMOVE_TAB = "REMOVE_TAB";
export const UPDATE_TAB = "UPDATE_TAB";
export const UPDATE_CURRENT_TAB = "UPDATE_CURRENT_TAB";
export const SET_CURRENT_TAB_ID = "SET_CURRENT_TAB_ID";
+
+// Sheet mutation types
+export const SET_SHEET_STATE = "SET_SHEET_STATE";
+export const SET_SHEET_LIST = "SET_SHEET_LIST";
+export const SET_SHEET_BY_ID = "SET_SHEET_BY_ID";
+export const DELETE_SHEET = "DELETE_SHEET";
diff --git a/frontend/src/types/common.ts b/frontend/src/types/common.ts
index 5d2beeec6b..94129786f0 100644
--- a/frontend/src/types/common.ts
+++ b/frontend/src/types/common.ts
@@ -19,6 +19,7 @@ import { Repository } from "./repository";
import { VCS } from "./vcs";
import { DeploymentConfig } from "./deployment";
import { DefaultApporvalPolicy } from "./policy";
+import { Sheet } from "./sheet";
// System bot id
export const SYSTEM_BOT_ID = 1;
@@ -128,7 +129,8 @@ export type ResourceType =
| "VCS"
| "REPOSITORY"
| "ANOMALY"
- | "DEPLOYMENT_CONFIG";
+ | "DEPLOYMENT_CONFIG"
+ | "SHEET";
export const unknown = (
type: ResourceType
@@ -154,7 +156,8 @@ export const unknown = (
| VCS
| Repository
| Anomaly
- | DeploymentConfig => {
+ | DeploymentConfig
+ | Sheet => {
// Have to omit creator and updater to avoid recursion.
const UNKNOWN_PRINCIPAL: Principal = {
id: UNKNOWN_ID,
@@ -453,6 +456,21 @@ export const unknown = (
},
};
+ const UNKNOWN_SHEET: Sheet = {
+ id: UNKNOWN_ID,
+ creator: UNKNOWN_PRINCIPAL,
+ createdTs: 0,
+ updater: UNKNOWN_PRINCIPAL,
+ updatedTs: 0,
+ instanceId: UNKNOWN_ID,
+ instance: UNKNOWN_INSTANCE,
+ databaseId: UNKNOWN_ID,
+ database: UNKNOWN_DATABASE,
+ name: "<<Unknown sheet>>",
+ statement: "",
+ visibility: "PRIVATE",
+ };
+
switch (type) {
case "PRINCIPAL":
return UNKNOWN_PRINCIPAL;
@@ -498,6 +516,8 @@ export const unknown = (
return UNKNOWN_ANOMALY;
case "DEPLOYMENT_CONFIG":
return UNKNOWN_DEPLOYMENT_CONFIG;
+ case "SHEET":
+ return UNKNOWN_SHEET;
}
};
@@ -526,7 +546,8 @@ export const empty = (
| VCS
| Repository
| Anomaly
- | DeploymentConfig => {
+ | DeploymentConfig
+ | Sheet => {
// Have to omit creator and updater to avoid recursion.
const EMPTY_PRINCIPAL: Principal = {
id: EMPTY_ID,
@@ -823,6 +844,21 @@ export const empty = (
},
};
+ const EMPTY_SHEET: Sheet = {
+ id: EMPTY_ID,
+ creator: EMPTY_PRINCIPAL,
+ createdTs: 0,
+ updater: EMPTY_PRINCIPAL,
+ updatedTs: 0,
+ instanceId: EMPTY_ID,
+ instance: EMPTY_INSTANCE,
+ databaseId: EMPTY_ID,
+ database: EMPTY_DATABASE,
+ name: "<<Empty sheet>>",
+ statement: "",
+ visibility: "PRIVATE",
+ };
+
switch (type) {
case "PRINCIPAL":
return EMPTY_PRINCIPAL;
@@ -868,5 +904,7 @@ export const empty = (
return EMPTY_ANOMALY;
case "DEPLOYMENT_CONFIG":
return EMPTY_DEPLOYMENT_CONFIG;
+ case "SHEET":
+ return EMPTY_SHEET;
}
};
diff --git a/frontend/src/types/id.ts b/frontend/src/types/id.ts
index cf95db66f7..85fdca5971 100644
--- a/frontend/src/types/id.ts
+++ b/frontend/src/types/id.ts
@@ -68,7 +68,7 @@ export type AnomalyId = IdType;
export type CommandId = IdType;
export type CommandRegisterId = IdType;
-export type SavedQueryId = IdType;
+export type SheetId = IdType;
// This references to the object id, which can be used as a container.
// Currently, only issue can be used a container.
diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts
index cb15814713..dc19d35465 100644
--- a/frontend/src/types/index.ts
+++ b/frontend/src/types/index.ts
@@ -38,3 +38,4 @@ export * from "./deployment";
export * from "./sqlEditor";
export * from "./tab";
export * from "./subscription";
+export * from "./sheet";
diff --git a/frontend/src/types/sheet.ts b/frontend/src/types/sheet.ts
new file mode 100644
index 0000000000..859a28e9aa
--- /dev/null
+++ b/frontend/src/types/sheet.ts
@@ -0,0 +1,46 @@
+import {
+ SheetId,
+ Instance,
+ InstanceId,
+ Database,
+ DatabaseId,
+ Principal,
+} from ".";
+
+export type SheetVisibility = "PRIVATE" | "PROJECT" | "PUBLIC";
+
+export interface Sheet {
+ id: SheetId;
+
+ // Standard fields
+ creator: Principal;
+ createdTs: number;
+ updater: Principal;
+ updatedTs: number;
+
+ // Related fields
+ instanceId: InstanceId;
+ instance: Instance;
+ databaseId?: DatabaseId;
+ database?: Database;
+
+ // Domain fields
+ name: string;
+ statement: string;
+ visibility: SheetVisibility;
+}
+
+export type CreateSheetState = Omit<
+ Sheet,
+ "id" | "creator" | "createdTs" | "updater" | "updatedTs"
+>;
+
+export type SheetPatch = Partial<
+ Pick<Sheet, "id" | "name" | "statement" | "visibility">
+>;
+
+export type AccessOption = {
+ label: string;
+ description: string;
+ value: SheetVisibility;
+};
diff --git a/frontend/src/types/sqlEditor.ts b/frontend/src/types/sqlEditor.ts
index d47251de08..0f1f86470c 100644
--- a/frontend/src/types/sqlEditor.ts
+++ b/frontend/src/types/sqlEditor.ts
@@ -1,13 +1,6 @@
import * as monaco from "monaco-editor";
-import {
- InstanceId,
- DatabaseId,
- TableId,
- ViewId,
- ActivityId,
- SavedQueryId,
-} from "../types";
+import { InstanceId, DatabaseId, TableId, ViewId, ActivityId } from "../types";
import { Principal } from "./principal";
export type EditorModel = monaco.editor.ITextModel;
@@ -65,20 +58,3 @@ export interface QueryHistory {
// Customerize fields
createdAt: string;
}
-
-export interface SavedQuery {
- id: SavedQueryId;
-
- // Standard fields
- creator: Principal;
- createdTs: number;
- updater: Principal;
- 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 78f1513935..f0942bd42e 100644
--- a/frontend/src/types/store.ts
+++ b/frontend/src/types/store.ts
@@ -6,8 +6,8 @@ import {
Policy,
PolicyType,
QueryHistory,
- SavedQuery,
View,
+ Sheet,
} from ".";
import { Activity } from "./activity";
import { ServerInfo } from "./actuator";
@@ -26,6 +26,7 @@ import {
PrincipalId,
ProjectId,
VCSId,
+ SheetId,
} from "./id";
import { Inbox, InboxSummary } from "./inbox";
import { Instance, MigrationHistory } from "./instance";
@@ -48,6 +49,7 @@ import { TabInfo } from "./tab";
import instanceStore from "../store/modules/instance";
import sqlEditorStore from "../store/modules/sqlEditor";
import tabStore from "../store/modules/tab";
+import sheetStore from "../store/modules/sheet";
export interface ActuatorState {
serverInfo?: ServerInfo;
@@ -196,9 +198,8 @@ export interface SqlEditorState {
shouldSetContent: boolean;
queryHistoryList: QueryHistory[];
isFetchingQueryHistory: boolean;
- savedQueryList: SavedQuery[];
- isFetchingSavedQueries: boolean;
isExecuting: boolean;
+ isFetchingSheet: boolean;
isShowExecutingHint: boolean;
}
export type SqlEditorGetters = typeof sqlEditorStore.getters;
@@ -216,3 +217,11 @@ export type TabMutations = typeof tabStore.mutations;
export interface DeploymentState {
deploymentConfigByProjectId: Map<ProjectId, DeploymentConfig>;
}
+
+export interface SheetState {
+ sheetList: Sheet[];
+ sheetById: Map<SheetId, Sheet>;
+}
+export type SheetGetters = typeof sheetStore.getters;
+export type SheetActions = typeof sheetStore.actions;
+export type SheetMutations = typeof sheetStore.mutations;
diff --git a/frontend/src/types/tab.ts b/frontend/src/types/tab.ts
index 15a0253e9c..74eb755483 100644
--- a/frontend/src/types/tab.ts
+++ b/frontend/src/types/tab.ts
@@ -1,12 +1,14 @@
+import { SheetId } from "../types";
+
export interface TabInfo {
id: string;
- label: string;
+ name: string;
isSaved: boolean;
savedAt: string;
- queryStatement: string;
+ statement: string;
selectedStatement: string;
queryResult?: Record<string, any>[];
- currentQueryId?: number;
+ sheetId?: SheetId;
}
export type AnyTabInfo = Partial<TabInfo>;
diff --git a/frontend/src/views/SqlEditor/AsidePanel/AsidePanel.vue b/frontend/src/views/SqlEditor/AsidePanel/AsidePanel.vue
index 41cbf41c70..e88add0029 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 name="queries" :tab="$t('sql-editor.queries')">
- <SavedQueryContainer />
+ <NTabPane name="sheets" :tab="$t('sql-editor.sheets')">
+ <SheetContainer />
</NTabPane>
<NTabPane name="history" :tab="$t('common.history')">
<QueryHistoryContainer />
@@ -34,7 +34,7 @@ import { useNamespacedState } from "vuex-composition-helpers";
import type { SqlEditorState } from "../../../types";
import DatabaseTree from "./DatabaseTree.vue";
import QueryHistoryContainer from "./QueryHistoryContainer.vue";
-import SavedQueryContainer from "./SavedQueryContainer.vue";
+import SheetContainer from "./SheetContainer.vue";
import TableSchema from "./TableSchema.vue";
const FULL_HEIGHT = 100;
diff --git a/frontend/src/views/SqlEditor/AsidePanel/QueryHistoryContainer.vue b/frontend/src/views/SqlEditor/AsidePanel/QueryHistoryContainer.vue
index b51aa0b7c0..94bfacd598 100644
--- a/frontend/src/views/SqlEditor/AsidePanel/QueryHistoryContainer.vue
+++ b/frontend/src/views/SqlEditor/AsidePanel/QueryHistoryContainer.vue
@@ -209,7 +209,7 @@ const handleDeleteHistory = () => {
const handleQueryHistoryClick = async (queryHistory: QueryHistory) => {
addTab({
- queryStatement: queryHistory.statement,
+ statement: queryHistory.statement,
selectedStatement: "",
});
};
diff --git a/frontend/src/views/SqlEditor/AsidePanel/SavedQueryContainer.vue b/frontend/src/views/SqlEditor/AsidePanel/SheetContainer.vue
similarity index 58%
rename from frontend/src/views/SqlEditor/AsidePanel/SavedQueryContainer.vue
rename to frontend/src/views/SqlEditor/AsidePanel/SheetContainer.vue
index e911378d22..a37be4df84 100644
--- a/frontend/src/views/SqlEditor/AsidePanel/SavedQueryContainer.vue
+++ b/frontend/src/views/SqlEditor/AsidePanel/SheetContainer.vue
@@ -5,7 +5,7 @@
<div class="w-full">
<NInput
v-model:value="state.search"
- :placeholder="$t('sql-editor.search-saved-queries')"
+ :placeholder="$t('sql-editor.search-sheets')"
>
<template #prefix>
<heroicons-outline:search class="h-5 w-5 text-gray-300" />
@@ -16,27 +16,27 @@
<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="w-full px-1 pr-2 py-2 border-b flex flex-col justify-start items-start cursor-pointer"
:class="`${
- currentTab.currentQueryId === query.id
+ currentTab.sheetId === query.id
? 'bg-gray-100 rounded border-b-0'
: ''
}`"
- @click="handleSavedQueryClick(query)"
+ @click="handleSheetClick(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)"
+ @dblclick="handleEditSheet(query.id, query.name)"
>
<input
- v-if="state.editingSavedQueryId === query.id"
+ v-if="state.editingSheetId === query.id"
ref="queryNameInputerRef"
- v-model="state.currentSavedQueryName"
+ v-model="state.currentSheetName"
type="text"
class="rounded px-2 py-0 text-sm w-full"
- @blur="handleSavedQueryNameChanged"
- @keyup.enter="handleSavedQueryNameChanged"
+ @blur="handleSheetNameChanged"
+ @keyup.enter="handleSheetNameChanged"
@keyup.esc="handleCancelEdit"
/>
<span v-else class="text-sm" v-html="query.formatedName"></span>
@@ -72,7 +72,7 @@
</div>
<div
- v-show="isLoading && savedQueryList.length === 0"
+ v-show="isLoading && sheetList.length === 0"
class="absolute w-full h-full flex justify-center items-center"
>
<BBSpin :title="$t('common.loading')" />
@@ -85,9 +85,9 @@
@close="handleHintClose"
>
<DeleteHint
- :content="$t('sql-editor.hint-tips.confirm-to-delete-this-saved-query')"
+ :content="$t('sql-editor.hint-tips.confirm-to-delete-this-sheet')"
@close="handleHintClose"
- @confirm="handleDeleteSavedQuery"
+ @confirm="handleDeleteSheet"
/>
</BBModal>
</template>
@@ -106,61 +106,71 @@ import {
TabActions,
TabGetters,
TabState,
- SavedQuery,
+ SheetActions,
+ SheetState,
+ Sheet,
SqlEditorActions,
SqlEditorState,
} from "../../../types";
import { getHighlightHTMLByKeyWords } from "../../../utils";
import DeleteHint from "./DeleteHint.vue";
+import { useSQLEditorConnection } from "../../../composables/useSQLEditorConnection";
interface State {
search: string;
isShowDeletingHint: boolean;
- currentSavedQueryName: string;
- editingSavedQueryId: number | null;
- currentActionSavedQuery: SavedQuery | null;
+ currentSheetName: string;
+ editingSheetId: number | null;
+ currentActionSheet: Sheet | null;
}
const { t } = useI18n();
+const { setConnectionContextFromCurrentTab } = useSQLEditorConnection();
-const { savedQueryList, isFetchingSavedQueries: isLoading } =
- useNamespacedState<SqlEditorState>("sqlEditor", [
- "savedQueryList",
- "isFetchingSavedQueries",
- ]);
+const { isFetchingSheet: isLoading } = useNamespacedState<SqlEditorState>(
+ "sqlEditor",
+ ["isFetchingSheet"]
+);
+const { sheetList } = useNamespacedState<SheetState>("sheet", ["sheetList"]);
const { tabList } = useNamespacedState<TabState>("tab", ["tabList"]);
const { currentTab } = useNamespacedGetters<TabGetters>("tab", ["currentTab"]);
-const { deleteSavedQuery, setShouldSetContent, patchSavedQuery } =
- useNamespacedActions<SqlEditorActions>("sqlEditor", [
- "deleteSavedQuery",
- "setShouldSetContent",
- "patchSavedQuery",
+
+// actions
+const { setShouldSetContent } = useNamespacedActions<SqlEditorActions>(
+ "sqlEditor",
+ ["setShouldSetContent"]
+);
+const { updateCurrentTab, setCurrentTabId, addTab } =
+ useNamespacedActions<TabActions>("tab", [
+ "updateCurrentTab",
+ "setCurrentTabId",
+ "addTab",
]);
-const { updateCurrentTab, setCurrentTabId } = useNamespacedActions<TabActions>(
- "tab",
- ["updateCurrentTab", "setCurrentTabId"]
+const { deleteSheet, patchSheetById } = useNamespacedActions<SheetActions>(
+ "sheet",
+ ["deleteSheet", "patchSheetById"]
);
const state = reactive<State>({
search: "",
- currentSavedQueryName: "",
- editingSavedQueryId: null,
+ currentSheetName: "",
+ editingSheetId: null,
isShowDeletingHint: false,
- currentActionSavedQuery: null,
+ currentActionSheet: null,
});
const queryNameInputerRef = ref<HTMLInputElement>();
const data = computed(() => {
const tempData =
- savedQueryList.value && savedQueryList.value.length > 0
- ? savedQueryList.value.filter((savedQuery) => {
+ sheetList.value && sheetList.value.length > 0
+ ? sheetList.value.filter((sheet) => {
let t = false;
- if (savedQuery.name.includes(state.search)) {
+ if (sheet.name.includes(state.search)) {
t = true;
}
- if (savedQuery.statement.includes(state.search)) {
+ if (sheet.statement.includes(state.search)) {
t = true;
}
@@ -168,21 +178,18 @@ const data = computed(() => {
})
: [];
- return tempData.map((savedQuery) => {
+ return tempData.map((sheet) => {
return {
- ...savedQuery,
+ ...sheet,
formatedName: state.search
- ? getHighlightHTMLByKeyWords(
- escape(savedQuery.name),
- escape(state.search)
- )
- : escape(savedQuery.name),
+ ? getHighlightHTMLByKeyWords(escape(sheet.name), escape(state.search))
+ : escape(sheet.name),
formatedStatement: state.search
? getHighlightHTMLByKeyWords(
- escape(savedQuery.statement),
+ escape(sheet.statement),
escape(state.search)
)
- : escape(savedQuery.statement),
+ : escape(sheet.statement),
};
});
});
@@ -191,8 +198,8 @@ const notifyMessage = computed(() => {
if (isLoading.value) {
return "";
}
- if (savedQueryList.value.length === null) {
- return t("sql-editor.no-saved-query-found");
+ if (sheetList.value.length === null) {
+ return t("sql-editor.no-sheet-found");
}
return "";
@@ -205,37 +212,37 @@ const actionDropdownOptions = computed(() => [
},
]);
-const handleEditSavedQuery = (id: number, name: string) => {
- state.editingSavedQueryId = id;
- state.currentSavedQueryName = name;
+const handleEditSheet = (id: number, name: string) => {
+ state.editingSheetId = id;
+ state.currentSheetName = name;
nextTick(() => {
queryNameInputerRef.value?.focus();
});
};
const handleCancelEdit = () => {
- state.editingSavedQueryId = null;
- state.currentSavedQueryName = "";
+ state.editingSheetId = null;
+ state.currentSheetName = "";
};
-const handleSavedQueryNameChanged = () => {
- if (state.editingSavedQueryId) {
- patchSavedQuery({
- id: state.editingSavedQueryId,
- name: state.currentSavedQueryName,
+const handleSheetNameChanged = () => {
+ if (state.editingSheetId) {
+ patchSheetById({
+ id: state.editingSheetId,
+ name: state.currentSheetName,
});
- if (currentTab.value.currentQueryId === state.editingSavedQueryId) {
+ if (currentTab.value.sheetId === state.editingSheetId) {
updateCurrentTab({
- label: state.currentSavedQueryName,
+ name: state.currentSheetName,
});
}
handleCancelEdit();
}
};
-const handleActionBtnClick = (key: string, savedQuery: SavedQuery) => {
- state.currentActionSavedQuery = savedQuery;
+const handleActionBtnClick = (key: string, sheet: Sheet) => {
+ state.currentActionSheet = sheet;
if (key === "delete") {
state.isShowDeletingHint = true;
@@ -243,43 +250,47 @@ const handleActionBtnClick = (key: string, savedQuery: SavedQuery) => {
};
const handleActionBtnOutsideClick = () => {
- state.currentActionSavedQuery = null;
+ state.currentActionSheet = null;
};
const handleHintClose = () => {
- state.currentActionSavedQuery = null;
+ state.currentActionSheet = null;
state.isShowDeletingHint = false;
};
-const handleDeleteSavedQuery = () => {
- if (state.currentActionSavedQuery) {
- deleteSavedQuery(state.currentActionSavedQuery.id);
+const handleDeleteSheet = () => {
+ if (state.currentActionSheet) {
+ deleteSheet(state.currentActionSheet.id);
- if (currentTab.value.currentQueryId === state.currentActionSavedQuery.id) {
+ if (currentTab.value.sheetId === state.currentActionSheet.id) {
updateCurrentTab({
- currentQueryId: undefined,
+ sheetId: undefined,
});
}
}
state.isShowDeletingHint = false;
};
-const handleSavedQueryClick = (savedQuery: SavedQuery) => {
- if (currentTab.value.currentQueryId !== savedQuery.id) {
+const handleSheetClick = async (sheet: Sheet) => {
+ if (currentTab.value.sheetId !== sheet.id) {
+ // open opened tab first
for (const tab of tabList.value) {
- if (tab.currentQueryId === savedQuery.id) {
+ if (tab.sheetId === sheet.id) {
setCurrentTabId(tab.id);
+ setConnectionContextFromCurrentTab();
setShouldSetContent(true);
return;
}
}
- updateCurrentTab({
- label: savedQuery.name,
- queryStatement: savedQuery.statement,
+ // otherwise, add new tab
+ addTab({
+ name: sheet.name,
+ statement: sheet.statement,
selectedStatement: "",
- currentQueryId: savedQuery.id,
+ sheetId: sheet.id,
});
+ setConnectionContextFromCurrentTab();
setShouldSetContent(true);
}
};
diff --git a/frontend/src/views/SqlEditor/EditorPanel/ConnectionHolder.vue b/frontend/src/views/SqlEditor/EditorPanel/ConnectionHolder.vue
new file mode 100644
index 0000000000..8cd37f4447
--- /dev/null
+++ b/frontend/src/views/SqlEditor/EditorPanel/ConnectionHolder.vue
@@ -0,0 +1,10 @@
+<template>
+ <div class="flex items-center justify-center w-full h-full text-gray-400">
+ <heroicons-outline:lightning-bolt class="mr-1" />
+ <div>
+ <p>
+ {{ $t("sql-editor.connection-holder") }}
+ </p>
+ </div>
+ </div>
+</template>
diff --git a/frontend/src/views/SqlEditor/EditorPanel/EditorAction.vue b/frontend/src/views/SqlEditor/EditorPanel/EditorAction.vue
index 35c6dae451..a337b87846 100644
--- a/frontend/src/views/SqlEditor/EditorPanel/EditorAction.vue
+++ b/frontend/src/views/SqlEditor/EditorPanel/EditorAction.vue
@@ -26,7 +26,7 @@
strong
type="primary"
:disabled="isEmptyStatement || currentTab.isSaved"
- @click="handleSaveQueryBtnClick"
+ @click="handleUpsertSheet"
>
<carbon:save class="h-5 w-5" /> &nbsp; {{ $t("common.save") }} (⌘+S)
</NButton>
@@ -38,9 +38,9 @@
</template>
<script lang="ts" setup>
+import { computed, ref, watch, onMounted } from "vue";
import { cloneDeep } from "lodash-es";
import { CascaderOption } from "naive-ui";
-import { computed, ref, watch } from "vue";
import {
useNamespacedState,
useNamespacedActions,
@@ -49,10 +49,13 @@ import {
import {
SqlEditorState,
+ SqlEditorGetters,
SqlEditorActions,
ConnectionContext,
TabGetters,
+ SheetActions,
TabActions,
+ UNKNOWN_ID,
} from "../../../types";
import { useExecuteSQL } from "../../../composables/useExecuteSQL";
import { isDev } from "../../../utils";
@@ -62,45 +65,47 @@ const { connectionTree, connectionContext } =
"connectionTree",
"connectionContext",
]);
+const { isDisconnected } = useNamespacedGetters<SqlEditorGetters>("sqlEditor", [
+ "isDisconnected",
+]);
+
const { currentTab } = useNamespacedGetters<TabGetters>("tab", ["currentTab"]);
-const {
- createSavedQuery,
- setConnectionContext,
- patchSavedQuery,
- checkSavedQueryExistById,
-} = useNamespacedActions<SqlEditorActions>("sqlEditor", [
- "createSavedQuery",
- "setConnectionContext",
- "patchSavedQuery",
- "checkSavedQueryExistById",
+
+// actions
+const { setConnectionContext } = useNamespacedActions<SqlEditorActions>(
+ "sqlEditor",
+ ["setConnectionContext"]
+);
+
+const { upsertSheet } = useNamespacedActions<SheetActions>("sheet", [
+ "upsertSheet",
]);
+
const { updateCurrentTab } = useNamespacedActions<TabActions>("tab", [
"updateCurrentTab",
]);
+const selectedConnection = ref();
+const isSeletedDatabase = ref(false);
const isEmptyStatement = computed(
- () => !currentTab.value || currentTab.value.queryStatement === ""
+ () => !currentTab.value || currentTab.value.statement === ""
);
-const selectedConnection = ref();
-const isSeletedDatabase = ref(false);
const { execute, state: executeState } = useExecuteSQL();
const handleRunQuery = () => {
execute();
};
-watch(
- () => connectionTree.value,
- (newVal) => {
- if (newVal) {
- const ctx = connectionContext.value;
- selectedConnection.value = ctx.hasSlug
- ? ctx.tableId || ctx.databaseId || ctx.instanceId
- : null;
- }
+const setSelectedConnection = (ctx: ConnectionContext) => {
+ if (ctx) {
+ selectedConnection.value = ctx.hasSlug
+ ? (ctx.tableId !== UNKNOWN_ID && ctx.tableId) ||
+ (ctx.databaseId !== UNKNOWN_ID && ctx.databaseId) ||
+ (ctx.instanceId !== UNKNOWN_ID && ctx.instanceId)
+ : null;
}
-);
+};
const handleConnectionChange = (
value: number,
@@ -137,30 +142,44 @@ const handleConnectionChange = (
}
};
-const handleSaveQueryBtnClick = async () => {
- const { queryStatement, label, currentQueryId } = currentTab.value;
- const isQueryExist = await checkSavedQueryExistById(currentQueryId || -1);
+const handleUpsertSheet = async () => {
+ const { name, statement, sheetId } = currentTab.value;
+ return upsertSheet({
+ id: sheetId,
+ name,
+ statement,
+ });
+};
- if (isQueryExist && currentQueryId) {
- patchSavedQuery({
- id: currentQueryId,
- name: label,
- statement: queryStatement,
- });
- } else {
- const newSavedQuery = await createSavedQuery({
- name: label,
- statement: queryStatement,
- });
- updateCurrentTab({
- currentQueryId: newSavedQuery.id,
- });
+watch(
+ () => connectionTree.value,
+ (newVal) => {
+ if (newVal) {
+ setSelectedConnection(connectionContext.value);
+ }
+ },
+ { deep: true }
+);
+
+// selected a new connection
+watch(
+ () => isDisconnected.value,
+ async (newVal) => {
+ if (!newVal) {
+ const newSheet = await handleUpsertSheet();
+ updateCurrentTab({
+ sheetId: newSheet.id,
+ isSaved: true,
+ });
+ } else {
+ setSelectedConnection(connectionContext.value);
+ }
}
+);
- updateCurrentTab({
- isSaved: true,
- });
-};
+onMounted(() => {
+ setSelectedConnection(connectionContext.value);
+});
</script>
<style scoped>
diff --git a/frontend/src/views/SqlEditor/EditorPanel/EditorPanel.vue b/frontend/src/views/SqlEditor/EditorPanel/EditorPanel.vue
index 10157a2324..2c3389237d 100644
--- a/frontend/src/views/SqlEditor/EditorPanel/EditorPanel.vue
+++ b/frontend/src/views/SqlEditor/EditorPanel/EditorPanel.vue
@@ -2,7 +2,12 @@
<div class="editor-pane h-full">
<EditorAction />
- <QueryEditor />
+ <template v-if="!isDisconnected">
+ <QueryEditor />
+ </template>
+ <template v-else>
+ <ConnectionHolder />
+ </template>
<BBModal
v-if="isShowExecutingHint"
@@ -17,19 +22,29 @@
<script lang="ts" setup>
import {
useNamespacedState,
+ useNamespacedGetters,
useNamespacedActions,
} from "vuex-composition-helpers";
-import { SqlEditorState, SqlEditorActions } from "../../../types";
+import {
+ SqlEditorState,
+ SqlEditorActions,
+ SqlEditorGetters,
+} from "../../../types";
import EditorAction from "./EditorAction.vue";
import QueryEditor from "./QueryEditor.vue";
import ExecuteHint from "./ExecuteHint.vue";
+import ConnectionHolder from "./ConnectionHolder.vue";
const { isShowExecutingHint } = useNamespacedState<SqlEditorState>(
"sqlEditor",
["isShowExecutingHint"]
);
+const { isDisconnected } = useNamespacedGetters<SqlEditorGetters>("sqlEditor", [
+ "isDisconnected",
+]);
+
const { setSqlEditorState } = useNamespacedActions<SqlEditorActions>(
"sqlEditor",
["setSqlEditorState"]
diff --git a/frontend/src/views/SqlEditor/EditorPanel/ExecuteHint.vue b/frontend/src/views/SqlEditor/EditorPanel/ExecuteHint.vue
index 02e300266d..eaf5162278 100644
--- a/frontend/src/views/SqlEditor/EditorPanel/ExecuteHint.vue
+++ b/frontend/src/views/SqlEditor/EditorPanel/ExecuteHint.vue
@@ -47,6 +47,8 @@ import {
useNamespacedState,
} from "vuex-composition-helpers";
+import { UNKNOWN_ID } from "../../../types";
+
import type {
SqlEditorState,
SqlEditorGetters,
@@ -76,7 +78,7 @@ const { currentTab } = useNamespacedGetters<TabGetters>("tab", ["currentTab"]);
const parsedStatement = computed(() => {
const sqlStatement =
- currentTab.value.selectedStatement || currentTab.value.queryStatement;
+ currentTab.value.selectedStatement || currentTab.value.statement;
const { data } = parseSQL(sqlStatement);
return data !== null ? transformSQL(data) : sqlStatement;
});
@@ -91,7 +93,7 @@ const handleColse = () => {
};
const gotoAlterSchema = () => {
- if (ctx.databaseId === 0) {
+ if (ctx.databaseId === UNKNOWN_ID) {
store.dispatch("notification/pushNotification", {
module: "bytebase",
style: "CRITICAL",
diff --git a/frontend/src/views/SqlEditor/EditorPanel/QueryEditor.vue b/frontend/src/views/SqlEditor/EditorPanel/QueryEditor.vue
index 730ff5d4e2..9c4f5557f2 100644
--- a/frontend/src/views/SqlEditor/EditorPanel/QueryEditor.vue
+++ b/frontend/src/views/SqlEditor/EditorPanel/QueryEditor.vue
@@ -17,34 +17,23 @@ import {
} from "vuex-composition-helpers";
import { useExecuteSQL } from "../../../composables/useExecuteSQL";
-import {
- TabActions,
- TabGetters,
- SqlEditorActions,
-} from "../../../types";
+import { TabActions, TabGetters, SheetActions } from "../../../types";
-const { currentTab } = useNamespacedGetters<TabGetters>(
- "tab",
- ["currentTab"]
-);
-const { updateCurrentTab } = useNamespacedActions<TabActions>(
- "tab",
- ["updateCurrentTab"]
-);
-const { createSavedQuery, patchSavedQuery, checkSavedQueryExistById } =
- useNamespacedActions<SqlEditorActions>("sqlEditor", [
- "createSavedQuery",
- "patchSavedQuery",
- "checkSavedQueryExistById",
- ]);
+const { currentTab } = useNamespacedGetters<TabGetters>("tab", ["currentTab"]);
+const { updateCurrentTab } = useNamespacedActions<TabActions>("tab", [
+ "updateCurrentTab",
+]);
+const { upsertSheet } = useNamespacedActions<SheetActions>("sheet", [
+ "upsertSheet",
+]);
const { execute } = useExecuteSQL();
-const sqlCode = computed(() => currentTab.value.queryStatement);
+const sqlCode = computed(() => currentTab.value.statement);
const handleChange = debounce((value: string) => {
updateCurrentTab({
- queryStatement: value,
+ statement: value,
isSaved: false,
});
}, 300);
@@ -56,26 +45,16 @@ const handleChangeSelection = debounce((value: string) => {
}, 300);
const handleSave = async (statement: string) => {
- const { label, currentQueryId } = currentTab.value;
- const isQueryExist = await checkSavedQueryExistById(currentQueryId || -1);
+ const { name, sheetId } = currentTab.value;
- if (isQueryExist && currentQueryId) {
- patchSavedQuery({
- id: currentQueryId,
- name: label,
- statement,
- });
- } else {
- const newSavedQuery = await createSavedQuery({
- name: label,
- statement,
- });
- updateCurrentTab({
- currentQueryId: newSavedQuery.id,
- });
- }
+ const newSheet = await upsertSheet({
+ id: sheetId,
+ name,
+ statement,
+ });
updateCurrentTab({
+ sheetId: newSheet.id,
isSaved: true,
});
};
diff --git a/frontend/src/views/SqlEditor/SqlEditor.vue b/frontend/src/views/SqlEditor/SqlEditor.vue
index eb42e0bee8..0e223218b4 100644
--- a/frontend/src/views/SqlEditor/SqlEditor.vue
+++ b/frontend/src/views/SqlEditor/SqlEditor.vue
@@ -8,10 +8,10 @@
<Pane size="80">
<template v-if="hasTabs">
<Splitpanes horizontal class="default-theme">
- <Pane size="60">
+ <Pane :size="isDisconnected ? 100 : 60">
<EditorPanel :key="paneKey" />
</Pane>
- <Pane size="40">
+ <Pane :size="isDisconnected ? 0 : 40">
<TablePanel :key="paneKey" />
</Pane>
</Splitpanes>
@@ -37,6 +37,9 @@ const store = useStore();
const hasTabs = computed(() => store.getters["tab/hasTabs"]);
const paneKey = computed(() => store.getters["tab/currentTab"].id);
+const isDisconnected = computed(
+ () => store.getters["sqlEditor/isDisconnected"]
+);
</script>
<style>
diff --git a/frontend/src/views/SqlEditor/TabListContainer.vue b/frontend/src/views/SqlEditor/TabListContainer.vue
index 38925872a2..81ef09d992 100644
--- a/frontend/src/views/SqlEditor/TabListContainer.vue
+++ b/frontend/src/views/SqlEditor/TabListContainer.vue
@@ -1,19 +1,19 @@
<template>
- <div class="tag-list-container">
+ <div class="tab-list-container">
<!-- tab list-->
<div
- class="tag-list-wrapper relative overflow-hidden"
+ class="tab-list-wrapper relative overflow-hidden"
:class="{ 'is-scrolling': scrollState.isScrolling }"
>
<div
ref="tablistRef"
- class="tag-list-tablist"
+ class="tab-list-tablist"
@wheel="handleScollTabList"
>
<div
v-for="tab in tabList"
:key="tab.id"
- class="tag-list-tab"
+ class="tab-list-tab"
:class="{ active: tab.id === currentTabId }"
:style="scrollState.style"
@click="handleSelectTab(tab)"
@@ -48,7 +48,7 @@
</span>
</div>
<span v-else>
- {{ tab.label }}
+ {{ tab.name }}
</span>
</div>
<template v-if="enterTabId === tab.id && tabList.length > 1">
@@ -81,18 +81,28 @@
</div>
</div>
- <div class="tag-list-add">
- <button
- class="p-1 hover:bg-gray-200 rounded-md"
- @click="handleAddTab({})"
+ <div class="tab-list-add">
+ <NTooltip
+ trigger="hover"
+ placement="bottom-center"
+ :disabled="!isDisconnected"
>
- <heroicons-solid:plus class="h-4 w-4" />
- </button>
+ <template #trigger>
+ <button
+ class="p-1 hover:bg-gray-200 rounded-md"
+ :class="{ 'cursor-not-allowed': isDisconnected }"
+ @click="handleAddTab({})"
+ >
+ <heroicons-solid:plus class="h-4 w-4" />
+ </button>
+ </template>
+ Please select connections
+ </NTooltip>
</div>
- <div class="tag-list-more">
+ <div class="tab-list-more">
<NPopselect
v-model:value="selectedTab"
- :options="tabListOptions"
+ :options="localTabList"
trigger="click"
size="medium"
scrollable
@@ -112,7 +122,8 @@
</template>
<script lang="ts" setup>
-import { ref, watch, reactive, nextTick, computed } from "vue";
+import { ref, watch, reactive, nextTick, computed, onMounted } from "vue";
+import { debounce, cloneDeep } from "lodash-es";
import { useI18n } from "vue-i18n";
import { useStore } from "vuex";
import {
@@ -124,19 +135,31 @@ import {
import {
TabInfo,
AnyTabInfo,
+ SqlEditorGetters,
TabGetters,
TabState,
TabActions,
- SqlEditorActions,
+ SheetActions,
} from "../../types";
-import { debounce } from "lodash-es";
+import { getDefaultTab } from "../../store/modules/tab";
+import { useSQLEditorConnection } from "../../composables/useSQLEditorConnection";
-const { currentTab } = useNamespacedGetters<TabGetters>("tab", ["currentTab"]);
+// getters map
+const { currentTab, hasTabs } = useNamespacedGetters<TabGetters>("tab", [
+ "currentTab",
+ "hasTabs",
+]);
+const { isDisconnected } = useNamespacedGetters<SqlEditorGetters>("sqlEditor", [
+ "isDisconnected",
+]);
+// state map
const { currentTabId, tabList } = useNamespacedState<TabState>("tab", [
"currentTabId",
"tabList",
]);
+
+// actions map
const { addTab, removeTab, setCurrentTabId, updateCurrentTab } =
useNamespacedActions<TabActions>("tab", [
"addTab",
@@ -144,14 +167,14 @@ const { addTab, removeTab, setCurrentTabId, updateCurrentTab } =
"setCurrentTabId",
"updateCurrentTab",
]);
-const { patchSavedQuery, checkSavedQueryExistById } =
- useNamespacedActions<SqlEditorActions>("sqlEditor", [
- "patchSavedQuery",
- "checkSavedQueryExistById",
- ]);
+const { createSheet, patchSheetById } = useNamespacedActions<SheetActions>(
+ "sheet",
+ ["createSheet", "patchSheetById"]
+);
const store = useStore();
const { t } = useI18n();
+const { setConnectionContextFromCurrentTab } = useSQLEditorConnection();
const enterTabId = ref("");
const selectedTab = computed(() => currentTabId.value);
@@ -164,10 +187,10 @@ const labelState = reactive({
});
const labelInputRef = ref<HTMLInputElement>();
-const tabListOptions = computed(() => {
+const localTabList = computed(() => {
return tabList.value.map((tab: TabInfo) => {
return {
- label: tab.label,
+ label: tab.name,
value: tab.id,
};
});
@@ -185,12 +208,21 @@ const scrollingDistance = computed(() => {
return scrollState.scrollWidth - scrollState.offsetWidth;
});
-const reComputedScrollWidth = () => {
+const recalculateScrollWidth = () => {
scrollState.scrollWidth = tablistRef.value?.scrollWidth as number;
scrollState.offsetWidth = tablistRef.value?.offsetWidth as number;
scrollState.isScrolling = scrollingDistance.value > 0;
};
+const updateSheetName = () => {
+ if (currentTab.value.sheetId) {
+ patchSheetById({
+ id: currentTab.value.sheetId,
+ name: labelState.currentLabelName,
+ });
+ }
+};
+
// Edit label logic
const handleEditLabel = (tab: TabInfo) => {
labelState.isEditingLabel = true;
@@ -200,16 +232,13 @@ const handleTryChangeLabel = () => {
if (labelState.currentLabelName !== "") {
labelState.isEditingLabel = false;
updateCurrentTab({
- label: labelState.currentLabelName,
+ name: labelState.currentLabelName,
});
- if (currentTab.value.currentQueryId) {
- patchSavedQuery({
- id: currentTab.value.currentQueryId,
- name: labelState.currentLabelName,
- });
- }
+
+ updateSheetName();
+
nextTick(() => {
- reComputedScrollWidth();
+ recalculateScrollWidth();
scrollState.style = {
transform: `translateX(0px)`,
};
@@ -225,50 +254,54 @@ const handleTryChangeLabel = () => {
const handleCancelChangeLabel = () => {
labelState.currentLabelName = labelState.oldLabelName;
updateCurrentTab({
- label: labelState.currentLabelName,
+ name: labelState.currentLabelName,
});
- if (currentTab.value.currentQueryId) {
- patchSavedQuery({
- id: currentTab.value.currentQueryId,
- name: labelState.currentLabelName,
- });
- }
+
+ updateSheetName();
+
nextTick(() => {
labelState.isEditingLabel = false;
- reComputedScrollWidth();
+ recalculateScrollWidth();
});
};
const handleSelectTab = async (tab: TabInfo) => {
setCurrentTabId(tab.id);
-
- if (currentTab.value.currentQueryId) {
- const exist = await checkSavedQueryExistById(
- currentTab.value.currentQueryId
- );
- if (!exist) {
- updateCurrentTab({
- currentQueryId: undefined,
- });
- }
- }
+ setConnectionContextFromCurrentTab();
};
const handleAddTab = (tab: AnyTabInfo) => {
+ if (isDisconnected.value) return;
+
addTab(tab);
- nextTick(() => {
- const tab = currentTab.value;
+
+ nextTick(async () => {
+ const tab = cloneDeep(currentTab.value);
handleEditLabel(tab);
- reComputedScrollWidth();
+
+ // make a relation between the new sheet and the current tab
+ const newSheet = await createSheet();
+
+ updateCurrentTab({
+ sheetId: newSheet.id,
+ });
+
+ recalculateScrollWidth();
});
};
-const handleRemoveTab = (tab: TabInfo) => {
- removeTab(tab);
+const handleRemoveTab = async (tab: TabInfo) => {
+ await removeTab(tab);
+ const tabsLength = tabList.value.length;
+
+ if (tabsLength > 0) {
+ handleSelectTab(tabList.value[tabsLength - 1]);
+ }
nextTick(() => {
- reComputedScrollWidth();
+ recalculateScrollWidth();
});
};
const handleSelectTabFromPopselect = (tabId: string) => {
setCurrentTabId(tabId);
+ setConnectionContextFromCurrentTab();
};
const handleScollTabList = debounce((e: WheelEvent) => {
@@ -281,8 +314,8 @@ watch(
() => labelState.isEditingLabel,
(newVal) => {
if (newVal) {
- labelState.currentLabelName = currentTab.value.label;
- labelState.oldLabelName = currentTab.value.label;
+ labelState.currentLabelName = currentTab.value.name;
+ labelState.oldLabelName = currentTab.value.name;
nextTick(() => {
labelInputRef.value?.focus();
});
@@ -295,40 +328,56 @@ watch(
}
}
);
+
+onMounted(async () => {
+ if (!hasTabs.value) {
+ addTab(getDefaultTab());
+ if (!isDisconnected.value) {
+ // make a relation between the new sheet and the current tab
+ const newSheet = await createSheet();
+
+ updateCurrentTab({
+ sheetId: newSheet.id,
+ });
+
+ recalculateScrollWidth();
+ }
+ }
+});
</script>
<style scoped>
-.tag-list-container {
+.tab-list-container {
height: var(--tab-height);
@apply flex box-border;
@apply text-gray-500 text-sm;
@apply border-b;
}
-.tag-list-tablist {
+.tab-list-tablist {
@apply flex overflow-auto;
max-width: calc(100vw - 112px);
scrollbar-width: none; /* firefox */
-ms-overflow-style: none; /* IE 10+ */
}
-.tag-list-wrapper.is-scrolling::before {
+.tab-list-wrapper.is-scrolling::before {
@apply absolute top-0 left-0 w-4 h-full z-10;
content: "";
transition: box-shadow 0.3s cubic-bezier(0.4, 0, 0.2, 1);
box-shadow: inset 10px 0 8px -8px rgb(0 0 0 / 16%);
}
-.tag-list-wrapper.is-scrolling::after {
+.tab-list-wrapper.is-scrolling::after {
@apply absolute top-0 right-0 w-4 h-full z-10;
content: "";
transition: box-shadow 0.3s cubic-bezier(0.4, 0, 0.2, 1);
box-shadow: inset -10px 0 8px -8px rgb(0 0 0 / 16%);
}
-.tag-list-tablist::-webkit-scrollbar {
+.tab-list-tablist::-webkit-scrollbar {
display: none; /* Chrome Safari */
}
-.tag-list-tab {
+.tab-list-tab {
@apply inline-flex place-items-center;
@apply cursor-pointer box-border;
@apply px-2 border-r;
@@ -338,33 +387,33 @@ watch(
transition: transform 0.3s, -webkit-transform 0.3s;
}
-.tag-list-tab.active {
+.tab-list-tab.active {
@apply cursor-text relative;
@apply bg-white;
@apply text-accent;
}
-.tag-list-tab .label {
+.tab-list-tab .label {
@apply p-2;
}
-.tag-list-tab .suffix {
+.tab-list-tab .suffix {
@apply flex justify-center items-center h-4 w-4;
}
-.tag-list-tab .suffix.close {
+.tab-list-tab .suffix.close {
@apply cursor-pointer;
@apply text-gray-500;
}
-.tag-list-move-prev,
-.tag-list-move-next,
-.tag-list-add {
+.tab-list-move-prev,
+.tab-list-move-next,
+.tab-list-add {
@apply flex items-center;
@apply cursor-pointer;
@apply p-2;
}
-.tag-list-more {
+.tab-list-more {
@apply flex items-center justify-end flex-1;
@apply cursor-pointer;
@apply p-2;
diff --git a/server/sheet.go b/server/sheet.go
index dcf92e9955..af79b49fe0 100644
--- a/server/sheet.go
+++ b/server/sheet.go
@@ -190,5 +190,23 @@ func (s *Server) composeSheetRelationship(ctx context.Context, sheet *api.Sheet)
return err
}
+ sheet.Instance, err = s.composeInstanceByID(ctx, sheet.InstanceID)
+ if err != nil {
+ return err
+ }
+
+ if sheet.DatabaseID != nil {
+ databaseFind := &api.DatabaseFind{
+ ID: sheet.DatabaseID,
+ }
+ sheet.Database, err = s.composeDatabaseByFind(ctx, databaseFind)
+ if err != nil {
+ return err
+ }
+ if sheet.Database == nil {
+ return fmt.Errorf("database ID not found %v", sheet.DatabaseID)
+ }
+ }
+
return nil
}