Skip to content

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

refactor: migrate sqlEditor store to pinia (#1098)

Yunwei Xiao55771488d425
diff --git a/frontend/src/components/MonacoEditor/MonacoEditor.vue b/frontend/src/components/MonacoEditor/MonacoEditor.vue
index a02b750dc5..1d9e5dd308 100644
--- a/frontend/src/components/MonacoEditor/MonacoEditor.vue
+++ b/frontend/src/components/MonacoEditor/MonacoEditor.vue
@@ -23,13 +23,8 @@ import {
useNamespacedState,
} from "vuex-composition-helpers";
-import { pushNotification, useTabStore } from "@/store";
-import {
- SqlEditorActions,
- SqlEditorState,
- SheetGetters,
- SqlDialect,
-} from "../../types";
+import { pushNotification, useTabStore, useSQLEditorStore } from "@/store";
+import { SheetGetters, SqlDialect } from "../../types";
import { useLineDecorations } from "./lineDecorations";
const props = defineProps({
@@ -62,20 +57,12 @@ const sqlCode = toRef(props, "value");
const language = toRef(props, "language");
const tabStore = useTabStore();
+const sqlEditorStore = useSQLEditorStore();
const { t } = useI18n();
-const { shouldSetContent, shouldFormatContent } =
- useNamespacedState<SqlEditorState>("sqlEditor", [
- "shouldSetContent",
- "shouldFormatContent",
- ]);
+
const { isReadOnly } = useNamespacedGetters<SheetGetters>("sheet", [
"isReadOnly",
]);
-const { setShouldSetContent, setShouldFormatContent } =
- useNamespacedActions<SqlEditorActions>("sqlEditor", [
- "setShouldSetContent",
- "setShouldFormatContent",
- ]);
const readonly = computed(() => isReadOnly.value(tabStore.currentTab));
@@ -232,10 +219,10 @@ onUnmounted(() => {
});
watch(
- () => shouldSetContent.value,
+ () => sqlEditorStore.shouldSetContent,
() => {
- if (shouldSetContent.value) {
- setShouldSetContent(false);
+ if (sqlEditorStore.shouldSetContent) {
+ sqlEditorStore.setShouldSetContent(false);
setContent(editorInstance, tabStore.currentTab.statement);
}
}
@@ -243,15 +230,15 @@ watch(
// trigger format code from outside
watch(
- () => shouldFormatContent.value,
+ () => sqlEditorStore.shouldFormatContent,
() => {
- if (shouldFormatContent.value) {
+ if (sqlEditorStore.shouldFormatContent) {
formatContent(editorInstance, language.value as SqlDialect);
nextTick(() => {
setPositionAtEndOfLine(editorInstance);
editorInstance.focus();
});
- setShouldFormatContent(false);
+ sqlEditorStore.setShouldFormatContent(false);
}
}
);
diff --git a/frontend/src/components/MonacoEditor/useMonaco.ts b/frontend/src/components/MonacoEditor/useMonaco.ts
index f0ff22fdd2..4a5d487001 100644
--- a/frontend/src/components/MonacoEditor/useMonaco.ts
+++ b/frontend/src/components/MonacoEditor/useMonaco.ts
@@ -1,5 +1,4 @@
import { computed } from "vue";
-import { useStore } from "vuex";
import { useNamespacedGetters } from "vuex-composition-helpers";
import * as monaco from "monaco-editor";
import type { editor as Editor } from "monaco-editor";
@@ -13,20 +12,19 @@ import {
SqlDialect,
} from "../../types";
import sqlFormatter from "./sqlFormatter";
-import { useDatabaseStore, useTableStore } from "@/store";
+import { useDatabaseStore, useTableStore, useSQLEditorStore } from "@/store";
const useMonaco = async (lang: string) => {
- const store = useStore();
const dataSourceStore = useDatabaseStore();
const tableStore = useTableStore();
+ const sqlEditorStore = useSQLEditorStore();
const { instanceList } = useNamespacedGetters<InstanceGetters>("instance", [
"instanceList",
]);
const databaseList = computed(() => {
- const currentInstanceId =
- store.state.sqlEditor.connectionContext.instanceId;
+ const currentInstanceId = sqlEditorStore.connectionContext.instanceId;
return dataSourceStore.getDatabaseListByInstanceId(currentInstanceId);
});
diff --git a/frontend/src/components/ProvideSqlEditorContext.vue b/frontend/src/components/ProvideSqlEditorContext.vue
index 5240990914..2f43c7af7c 100644
--- a/frontend/src/components/ProvideSqlEditorContext.vue
+++ b/frontend/src/components/ProvideSqlEditorContext.vue
@@ -9,6 +9,7 @@ import {
useInstanceStore,
useProjectStore,
useTableStore,
+ useSQLEditorStore,
} from "@/store";
import { reactive, onMounted } from "vue";
import { useStore } from "vuex";
@@ -39,6 +40,7 @@ const state = reactive<{
const currentUser = useCurrentUser();
const projectStore = useProjectStore();
const tableStore = useTableStore();
+const sqlEditorStore = useSQLEditorStore();
const prepareAccessibleConnectionByProject = async () => {
// It will also be called when user logout
@@ -64,7 +66,7 @@ const prepareAccessibleConnectionByProject = async () => {
};
const prepareSqlEditorContext = async () => {
- store.dispatch("sqlEditor/setConnectionContext", { isLoadingTree: true });
+ sqlEditorStore.setConnectionContext({ isLoadingTree: true });
let connectionTree = [];
const mapConnectionAtom =
@@ -114,9 +116,9 @@ const prepareSqlEditorContext = async () => {
}
}
- store.dispatch("sqlEditor/setConnectionTree", connectionTree);
- store.dispatch("sqlEditor/setConnectionContext", { isLoadingTree: false });
- store.dispatch("sqlEditor/fetchQueryHistoryList");
+ sqlEditorStore.setConnectionTree(connectionTree);
+ sqlEditorStore.setConnectionContext({ isLoadingTree: false });
+ sqlEditorStore.fetchQueryHistoryList();
store.dispatch("sheet/fetchSheetList");
};
diff --git a/frontend/src/composables/useExecuteSQL.ts b/frontend/src/composables/useExecuteSQL.ts
index adaf6b098a..707c4bc8ef 100644
--- a/frontend/src/composables/useExecuteSQL.ts
+++ b/frontend/src/composables/useExecuteSQL.ts
@@ -1,6 +1,5 @@
import { reactive } from "vue";
import { isEmpty } from "lodash-es";
-import { useStore } from "vuex";
import { useI18n } from "vue-i18n";
import {
@@ -11,7 +10,8 @@ import {
isDDLStatement,
isDMLStatement,
} from "../components/MonacoEditor/sqlParser";
-import { pushNotification, useTabStore } from "@/store";
+import { pushNotification, useTabStore, useSQLEditorStore } from "@/store";
+import { TabInfo } from "@/types";
type ExecuteConfig = {
databaseType: string;
@@ -22,9 +22,10 @@ type ExecuteOption = {
};
const useExecuteSQL = () => {
- const store = useStore();
const { t } = useI18n();
const tabStore = useTabStore();
+ const sqlEditorStore = useSQLEditorStore();
+
const state = reactive({
isLoadingData: false,
});
@@ -47,7 +48,7 @@ const useExecuteSQL = () => {
}
const currentTab = tabStore.currentTab;
- const isDisconnected = store.getters["sqlEditor/isDisconnected"];
+ const isDisconnected = sqlEditorStore.isDisconnected;
const statement = currentTab.statement;
const selectedStatement = currentTab.selectedStatement;
const sqlStatement = selectedStatement || statement;
@@ -80,7 +81,7 @@ const useExecuteSQL = () => {
}
// only DDL and DML statements are allowed
if (isDDLStatement(data) || isDMLStatement(data)) {
- store.dispatch("sqlEditor/setSqlEditorState", {
+ sqlEditorStore.setSqlEditorState({
isShowExecutingHint: true,
});
return;
@@ -98,22 +99,22 @@ const useExecuteSQL = () => {
try {
const isExplain = option?.explain || false;
state.isLoadingData = true;
- store.dispatch("sqlEditor/setIsExecuting", true);
+ sqlEditorStore.setIsExecuting(true);
// remove the comment from the sql statement in front-end
const selectStatement =
data !== null ? transformSQL(data, config.databaseType) : sqlStatement;
const explainStatement = `EXPLAIN ${selectStatement}`;
- const queryResult = await store.dispatch("sqlEditor/executeQuery", {
+ const queryResult = (await sqlEditorStore.executeQuery({
statement: isExplain ? explainStatement : selectStatement,
- });
+ })) as any;
tabStore.updateCurrentTab({ queryResult });
- store.dispatch("sqlEditor/fetchQueryHistoryList");
+ sqlEditorStore.fetchQueryHistoryList();
} catch (error) {
tabStore.updateCurrentTab({ queryResult: undefined });
notify("CRITICAL", error as string);
} finally {
state.isLoadingData = false;
- store.dispatch("sqlEditor/setIsExecuting", false);
+ sqlEditorStore.setIsExecuting(false);
}
};
diff --git a/frontend/src/composables/useSQLEditorConnection.ts b/frontend/src/composables/useSQLEditorConnection.ts
index 5daaf9b16a..a8f9cc9ccf 100644
--- a/frontend/src/composables/useSQLEditorConnection.ts
+++ b/frontend/src/composables/useSQLEditorConnection.ts
@@ -3,13 +3,14 @@ import { useStore } from "vuex";
import { DEFAULT_PROJECT_ID, SheetState, UNKNOWN_ID } from "../types";
import { connectionSlug } from "../utils";
-import { getDefaultConnectionContext } from "../store/modules/sqlEditor";
-import { useDatabaseStore, useTabStore } from "@/store";
+import { getDefaultConnectionContext } from "@/store/pinia-modules/sqlEditor";
+import { useDatabaseStore, useTabStore, useSQLEditorStore } from "@/store";
const useSQLEditorConnection = () => {
const router = useRouter();
const store = useStore();
const tabStore = useTabStore();
+ const sqlEditorStore = useSQLEditorStore();
/**
* Set the connection by tab info
@@ -23,7 +24,7 @@ const useSQLEditorConnection = () => {
if (currentTab.sheetId && sheetById.has(currentTab.sheetId)) {
const sheet = sheetById.get(currentTab.sheetId);
- store.dispatch("sqlEditor/setConnectionContext", {
+ sqlEditorStore.setConnectionContext({
hasSlug: true,
projectId: sheet?.database?.projectId || DEFAULT_PROJECT_ID,
instanceId: sheet?.database?.instanceId || UNKNOWN_ID,
@@ -42,10 +43,7 @@ const useSQLEditorConnection = () => {
});
}
} else {
- store.dispatch(
- "sqlEditor/setConnectionContext",
- getDefaultConnectionContext()
- );
+ sqlEditorStore.setConnectionContext(getDefaultConnectionContext());
router.push({
path: "/sql-editor",
diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts
index d0d3ff7b6d..6ca6b69bcf 100644
--- a/frontend/src/router/index.ts
+++ b/frontend/src/router/index.ts
@@ -36,6 +36,7 @@ import {
useDataSourceStore,
useProjectStore,
useTableStore,
+ useSQLEditorStore,
} from "@/store";
const HOME_MODULE = "workspace.home";
@@ -1162,8 +1163,8 @@ router.beforeEach((to, from, next) => {
if (connectionSlug) {
const [, instanceId, , databaseId] = connectionSlug.split("_");
- store
- .dispatch("sqlEditor/fetchConnectionByInstanceIdAndDatabaseId", {
+ useSQLEditorStore()
+ .fetchConnectionByInstanceIdAndDatabaseId({
instanceId: Number(instanceId),
databaseId: Number(databaseId),
})
@@ -1182,7 +1183,7 @@ router.beforeEach((to, from, next) => {
tabStore.updateCurrentTab({
sheetId: sheet.id,
});
- store.dispatch("sqlEditor/setSqlEditorState", {
+ useSQLEditorStore().setSqlEditorState({
sharedSheet: sheet,
});
diff --git a/frontend/src/store/modules/sheet.ts b/frontend/src/store/modules/sheet.ts
index ffef269c2e..1a66da73b0 100644
--- a/frontend/src/store/modules/sheet.ts
+++ b/frontend/src/store/modules/sheet.ts
@@ -22,6 +22,7 @@ import {
useAuthStore,
useDatabaseStore,
useProjectStore,
+ useSQLEditorStore,
} from "../pinia-modules";
function convertSheet(
@@ -101,7 +102,8 @@ const getters = {
(state: SheetState, getters: any, rootState: any, rootGetters: any) =>
(currentTab: TabInfo): boolean => {
const { currentUser } = useAuthStore();
- const sharedSheet = rootState.sqlEditor.sharedSheet;
+ const sqlEditorStore = useSQLEditorStore();
+ const sharedSheet = sqlEditorStore.sharedSheet;
const currentSheet = getters.currentSheet(currentTab);
const isSharedByOthers = sharedSheet.id !== UNKNOWN_ID;
@@ -181,7 +183,8 @@ const actions = {
{ commit, state, rootState, rootGetters }: any,
currentTab: TabInfo
): Promise<Sheet> {
- const ctx = rootState.sqlEditor.connectionContext as ConnectionContext;
+ const sqlEditorStore = useSQLEditorStore();
+ const ctx = sqlEditorStore.connectionContext as ConnectionContext;
const result = (
await axios.post(`/api/sheet`, {
@@ -215,11 +218,7 @@ const actions = {
},
// retrieve
async fetchSheetList({ commit, dispatch, state, rootGetters }: any) {
- dispatch(
- "sqlEditor/setSqlEditorState",
- { isFetchingSheet: true },
- { root: true }
- );
+ useSQLEditorStore().setSqlEditorState({ isFetchingSheet: true });
const data = (await axios.get(`/api/sheet`)).data;
const sheetList: Sheet[] = data.data.map((rawData: ResourceObject) => {
const sheet = convertSheet(rawData, data.included, rootGetters);
@@ -234,11 +233,7 @@ const actions = {
types.SET_SHEET_LIST,
sheetList.sort((a, b) => b.createdTs - a.createdTs)
);
- dispatch(
- "sqlEditor/setSqlEditorState",
- { isFetchingSheet: false },
- { root: true }
- );
+ useSQLEditorStore().setSqlEditorState({ isFetchingSheet: false });
},
async fetchSheetById(
{ commit, dispatch, state, rootGetters }: any,
diff --git a/frontend/src/store/modules/sqlEditor.ts b/frontend/src/store/modules/sqlEditor.ts
deleted file mode 100644
index 6a0e654d3f..0000000000
--- a/frontend/src/store/modules/sqlEditor.ts
+++ /dev/null
@@ -1,289 +0,0 @@
-import dayjs from "dayjs";
-import { isEmpty } from "lodash-es";
-
-import {
- SqlEditorState,
- ConnectionAtom,
- QueryInfo,
- ConnectionContext,
- Database,
- DatabaseId,
- ProjectId,
- QueryHistory,
- UNKNOWN_ID,
- Sheet,
- DEFAULT_PROJECT_ID,
-} from "@/types";
-import * as types from "../mutation-types";
-import { makeActions } from "../actions";
-import { unknown } from "@/types";
-import {
- useActivityStore,
- useDatabaseStore,
- useInstanceStore,
- useTableStore,
- useSQLStore,
-} from "../pinia-modules";
-
-export const getDefaultConnectionContext = () => ({
- hasSlug: false,
- projectId: DEFAULT_PROJECT_ID,
- projectName: "",
- instanceId: UNKNOWN_ID,
- instanceName: "",
- databaseId: UNKNOWN_ID,
- databaseName: "",
- databaseType: "",
- tableId: UNKNOWN_ID,
- tableName: "",
- isLoadingTree: false,
- option: {},
-});
-
-const state: () => SqlEditorState = () => ({
- connectionTree: [],
- connectionContext: getDefaultConnectionContext(),
- isExecuting: false,
- isShowExecutingHint: false,
- shouldSetContent: false,
- shouldFormatContent: false,
- // Related data and status
- queryHistoryList: [],
- isFetchingQueryHistory: false,
- isFetchingSheet: false,
- sharedSheet: unknown("SHEET") as Sheet,
-});
-
-const getters = {
- connectionTreeByInstanceId(state: SqlEditorState): Partial<ConnectionAtom> {
- const idx = state.connectionTree.findIndex((item) => {
- return item.id === state.connectionContext.instanceId;
- });
-
- return idx !== -1 ? state.connectionTree[idx] : {};
- },
- connectionInfo(
- state: SqlEditorState,
- getter: any,
- rootState: any,
- rootGetters: any
- ) {
- return {
- projectListById: rootState.project.projectById,
- instanceListById: rootState.instance.instanceById,
- databaseListByInstanceId: rootState.database.databaseListByInstanceId,
- databaseListByProjectId: rootState.database.databaseListByProjectId,
- tableListByDatabaseId: rootState.table.tableListByDatabaseId,
- };
- },
- connectionInfoByInstanceId(
- state: SqlEditorState,
- getter: any,
- rootState: any,
- rootGetters: any
- ) {
- let instance = {} as any;
- let databaseList: Database[] = [];
- let tableList = [];
-
- if (!isEmpty(getter.connectionTreeByInstanceId)) {
- instance = getter.connectionTreeByInstanceId;
- databaseList = useDatabaseStore().getDatabaseListByInstanceId(
- instance.id
- );
-
- tableList = instance.children
- .map((item: ConnectionAtom) =>
- useTableStore().getTableListByDatabaseId(item.id)
- )
- .flat();
- }
-
- return {
- instance,
- databaseList,
- tableList,
- };
- },
- findProjectIdByDatabaseId:
- (state: SqlEditorState, getter: any, rootState: any) =>
- (databaseId: DatabaseId): ProjectId => {
- let projectId = UNKNOWN_ID;
- const databaseListByProjectId =
- rootState.database.databaseListByProjectId;
- for (const [id, databaseList] of databaseListByProjectId) {
- const idx = databaseList.findIndex(
- (database: Database) => database.id === databaseId
- );
- if (idx !== -1) {
- projectId = id;
- break;
- }
- }
- return projectId;
- },
- currentSlug(state: SqlEditorState) {
- const connectionContext = state.connectionContext;
- return `${connectionContext.instanceId}/${connectionContext.databaseId}/${connectionContext.tableId}`;
- },
- /**
- * check the connection whether disconnected
- * 1、If the context is not set the instanceId, return true
- * 2、If the context is set the instanceId, but not set the databaseId and databaseType is not MYSQL or TIDB, return true
- * @param state
- * @returns boolean
- */
- isDisconnected(state: SqlEditorState) {
- const ctx = state.connectionContext;
- return (
- ctx.instanceId === UNKNOWN_ID ||
- (ctx.databaseId === UNKNOWN_ID &&
- ctx.databaseType !== "MYSQL" &&
- ctx.databaseType !== "TIDB")
- );
- },
-};
-
-const mutations = {
- [types.SET_SQL_EDITOR_STATE](
- state: SqlEditorState,
- payload: Partial<SqlEditorState>
- ) {
- Object.assign(state, payload);
- },
- [types.SET_CONNECTION_TREE](
- state: SqlEditorState,
- payload: ConnectionAtom[]
- ) {
- state.connectionTree = payload;
- },
- [types.SET_CONNECTION_CONTEXT](
- state: SqlEditorState,
- payload: Partial<ConnectionContext>
- ) {
- Object.assign(state.connectionContext, payload);
- },
- [types.SET_SHOULD_SET_CONTENT](state: SqlEditorState, payload: boolean) {
- state.shouldSetContent = payload;
- },
- [types.SET_SHOULD_FORMAT_CONTENT](state: SqlEditorState, payload: boolean) {
- state.shouldFormatContent = payload;
- },
- [types.SET_IS_EXECUTING](state: SqlEditorState, payload: boolean) {
- state.isExecuting = payload;
- },
- [types.SET_QUERY_HISTORY_LIST](
- state: SqlEditorState,
- payload: QueryHistory[]
- ) {
- state.queryHistoryList = payload;
- },
- [types.SET_IS_FETCHING_QUERY_HISTORY](
- state: SqlEditorState,
- payload: boolean
- ) {
- state.isFetchingQueryHistory = payload;
- },
-};
-
-type SqlEditorActionsMap = {
- setSqlEditorState: typeof mutations.SET_SQL_EDITOR_STATE;
- setConnectionTree: typeof mutations.SET_CONNECTION_TREE;
- setConnectionContext: typeof mutations.SET_CONNECTION_CONTEXT;
- setShouldSetContent: typeof mutations.SET_SHOULD_SET_CONTENT;
- setShouldFormatContent: typeof mutations.SET_SHOULD_FORMAT_CONTENT;
- setIsExecuting: typeof mutations.SET_IS_EXECUTING;
- setQueryHistoryList: typeof mutations.SET_QUERY_HISTORY_LIST;
- setIsFetchingQueryHistory: typeof mutations.SET_IS_FETCHING_QUERY_HISTORY;
-};
-
-const actions = {
- ...makeActions<SqlEditorActionsMap>({
- setSqlEditorState: types.SET_SQL_EDITOR_STATE,
- setConnectionTree: types.SET_CONNECTION_TREE,
- setConnectionContext: types.SET_CONNECTION_CONTEXT,
- setShouldSetContent: types.SET_SHOULD_SET_CONTENT,
- setShouldFormatContent: types.SET_SHOULD_FORMAT_CONTENT,
- setIsExecuting: types.SET_IS_EXECUTING,
- setQueryHistoryList: types.SET_QUERY_HISTORY_LIST,
- setIsFetchingQueryHistory: types.SET_IS_FETCHING_QUERY_HISTORY,
- }),
- async executeQuery(
- { dispatch, state }: any,
- { statement }: Pick<QueryInfo, "statement">
- ) {
- const queryResult = await useSQLStore().query({
- instanceId: state.connectionContext.instanceId,
- databaseName: state.connectionContext.databaseName,
- statement,
- });
-
- return queryResult;
- },
- async fetchConnectionByInstanceIdAndDatabaseId(
- { commit, dispatch }: any,
- {
- instanceId,
- databaseId,
- }: Pick<SqlEditorState["connectionContext"], "instanceId" | "databaseId">
- ) {
- const instance = await useInstanceStore().fetchInstanceById(instanceId);
- const database = await useDatabaseStore().fetchDatabaseById(databaseId);
-
- commit(types.SET_CONNECTION_CONTEXT, {
- hasSlug: true,
- instanceId,
- instanceName: instance.name,
- databaseId,
- databaseName: database.name,
- databaseType: instance.engine,
- });
- },
- async fetchQueryHistoryList({ commit, dispatch }: any) {
- commit(types.SET_IS_FETCHING_QUERY_HISTORY, true);
- const activityList =
- await useActivityStore().fetchActivityListForQueryHistory({
- limit: 50,
- });
- const queryHistoryList: QueryHistory[] = activityList.map(
- (history: any) => {
- return {
- id: history.id,
- creator: history.creator,
- createdTs: history.createdTs,
- updatedTs: history.updatedTs,
- statement: history.payload.statement,
- durationNs: history.payload.durationNs,
- instanceName: history.payload.instanceName,
- databaseName: history.payload.databaseName,
- error: history.payload.error,
- createdAt: dayjs(history.createdTs * 1000).format(
- "YYYY-MM-DD HH:mm:ss"
- ),
- };
- }
- );
-
- commit(
- types.SET_QUERY_HISTORY_LIST,
- queryHistoryList.sort((a, b) => b.createdTs - a.createdTs)
- );
- commit(types.SET_IS_FETCHING_QUERY_HISTORY, false);
- },
- async deleteQueryHistory({ commit, dispatch, state }: any, id: number) {
- await useActivityStore().deleteActivityById(id);
-
- commit(
- types.SET_QUERY_HISTORY_LIST,
- state.queryHistoryList.filter((t: QueryHistory) => t.id !== id)
- );
- },
-};
-
-export default {
- namespaced: true,
- state,
- getters,
- actions,
- mutations,
-};
diff --git a/frontend/src/store/pinia-modules/index.ts b/frontend/src/store/pinia-modules/index.ts
index 35eb44acce..a67d590c1a 100644
--- a/frontend/src/store/pinia-modules/index.ts
+++ b/frontend/src/store/pinia-modules/index.ts
@@ -25,6 +25,7 @@ export * from "./projectWebhook";
export * from "./router";
export * from "./setting";
export * from "./sql";
+export * from "./sqlEditor";
export * from "./subscription";
export * from "./tab";
export * from "./table";
diff --git a/frontend/src/store/pinia-modules/sqlEditor.ts b/frontend/src/store/pinia-modules/sqlEditor.ts
new file mode 100644
index 0000000000..149f2b3009
--- /dev/null
+++ b/frontend/src/store/pinia-modules/sqlEditor.ts
@@ -0,0 +1,233 @@
+import dayjs from "dayjs";
+import { isEmpty } from "lodash-es";
+import { defineStore } from "pinia";
+
+import {
+ SqlEditorState,
+ ConnectionAtom,
+ QueryInfo,
+ ConnectionContext,
+ Database,
+ DatabaseId,
+ ProjectId,
+ QueryHistory,
+ UNKNOWN_ID,
+ Sheet,
+ DEFAULT_PROJECT_ID,
+} from "@/types";
+import { unknown } from "@/types";
+import {
+ useActivityStore,
+ useDatabaseStore,
+ useInstanceStore,
+ useTableStore,
+ useSQLStore,
+ useProjectStore,
+} from "../pinia-modules";
+
+export const getDefaultConnectionContext = () => ({
+ hasSlug: false,
+ projectId: DEFAULT_PROJECT_ID,
+ projectName: "",
+ instanceId: UNKNOWN_ID,
+ instanceName: "",
+ databaseId: UNKNOWN_ID,
+ databaseName: "",
+ databaseType: "",
+ tableId: UNKNOWN_ID,
+ tableName: "",
+ isLoadingTree: false,
+ option: {},
+});
+
+export const useSQLEditorStore = defineStore("sqlEditor", {
+ state: (): SqlEditorState => ({
+ connectionTree: [],
+ connectionContext: getDefaultConnectionContext(),
+ isExecuting: false,
+ isShowExecutingHint: false,
+ shouldSetContent: false,
+ shouldFormatContent: false,
+ // Related data and status
+ queryHistoryList: [],
+ isFetchingQueryHistory: false,
+ isFetchingSheet: false,
+ sharedSheet: unknown("SHEET") as Sheet,
+ }),
+
+ getters: {
+ connectionTreeByInstanceId(state): Partial<ConnectionAtom> {
+ const idx = state.connectionTree.findIndex((item) => {
+ return item.id === state.connectionContext.instanceId;
+ });
+
+ return idx !== -1 ? state.connectionTree[idx] : {};
+ },
+
+ connectionInfo() {
+ const projectStore = useProjectStore();
+ const instanceStore = useInstanceStore();
+ const databaseStore = useDatabaseStore();
+ const tableStore = useTableStore();
+
+ return {
+ projectListById: projectStore.projectById,
+ instanceListById: instanceStore.instanceById,
+ databaseListByInstanceId: databaseStore.databaseListByInstanceId,
+ databaseListByProjectId: databaseStore.databaseListByProjectId,
+ tableListByDatabaseId: tableStore.tableListByDatabaseId,
+ };
+ },
+ connectionInfoByInstanceId() {
+ let instance = {} as any;
+ let databaseList: Database[] = [];
+ let tableList = [];
+
+ if (!isEmpty(this.connectionTreeByInstanceId)) {
+ instance = this.connectionTreeByInstanceId;
+ databaseList = useDatabaseStore().getDatabaseListByInstanceId(
+ instance.id
+ );
+
+ tableList = instance.children
+ .map((item: ConnectionAtom) =>
+ useTableStore().getTableListByDatabaseId(item.id)
+ )
+ .flat();
+ }
+
+ return {
+ instance,
+ databaseList,
+ tableList,
+ };
+ },
+ findProjectIdByDatabaseId:
+ (state) =>
+ (databaseId: DatabaseId): ProjectId => {
+ const databaseStore = useDatabaseStore();
+ let projectId = UNKNOWN_ID;
+ const databaseListByProjectId = databaseStore.databaseListByProjectId;
+ for (const [id, databaseList] of databaseListByProjectId) {
+ const idx = databaseList.findIndex(
+ (database: Database) => database.id === databaseId
+ );
+ if (idx !== -1) {
+ projectId = id;
+ break;
+ }
+ }
+ return projectId;
+ },
+
+ currentSlug(state) {
+ const connectionContext = state.connectionContext;
+ return `${connectionContext.instanceId}/${connectionContext.databaseId}/${connectionContext.tableId}`;
+ },
+ /**
+ * check the connection whether disconnected
+ * 1、If the context is not set the instanceId, return true
+ * 2、If the context is set the instanceId, but not set the databaseId and databaseType is not MYSQL or TIDB, return true
+ * @param state
+ * @returns boolean
+ */
+ isDisconnected(state) {
+ const ctx = state.connectionContext;
+ return (
+ ctx.instanceId === UNKNOWN_ID ||
+ (ctx.databaseId === UNKNOWN_ID &&
+ ctx.databaseType !== "MYSQL" &&
+ ctx.databaseType !== "TIDB")
+ );
+ },
+ },
+
+ actions: {
+ setSqlEditorState(payload: Partial<SqlEditorState>) {
+ Object.assign(this, payload);
+ },
+ setConnectionTree(payload: ConnectionAtom[]) {
+ this.connectionTree = payload;
+ },
+ setConnectionContext(payload: Partial<ConnectionContext>) {
+ Object.assign(this.connectionContext, payload);
+ },
+ setShouldSetContent(payload: boolean) {
+ this.shouldSetContent = payload;
+ },
+ setShouldFormatContent(payload: boolean) {
+ this.shouldFormatContent = payload;
+ },
+ setIsExecuting(payload: boolean) {
+ this.isExecuting = payload;
+ },
+ setQueryHistoryList(payload: QueryHistory[]) {
+ this.queryHistoryList = payload;
+ },
+ setIsFetchingQueryHistory(payload: boolean) {
+ this.isFetchingQueryHistory = payload;
+ },
+ async executeQuery({ statement }: Pick<QueryInfo, "statement">) {
+ const queryResult = await useSQLStore().query({
+ instanceId: this.connectionContext.instanceId,
+ databaseName: this.connectionContext.databaseName,
+ statement,
+ });
+
+ return queryResult;
+ },
+ async fetchConnectionByInstanceIdAndDatabaseId({
+ instanceId,
+ databaseId,
+ }: Pick<SqlEditorState["connectionContext"], "instanceId" | "databaseId">) {
+ const instance = await useInstanceStore().fetchInstanceById(instanceId);
+ const database = await useDatabaseStore().fetchDatabaseById(databaseId);
+
+ this.setConnectionContext({
+ hasSlug: true,
+ instanceId,
+ instanceName: instance.name,
+ databaseId,
+ databaseName: database.name,
+ databaseType: instance.engine,
+ });
+ },
+ async fetchQueryHistoryList() {
+ this.setIsFetchingQueryHistory(true);
+ const activityList =
+ await useActivityStore().fetchActivityListForQueryHistory({
+ limit: 50,
+ });
+ const queryHistoryList: QueryHistory[] = activityList.map(
+ (history: any) => {
+ return {
+ id: history.id,
+ creator: history.creator,
+ createdTs: history.createdTs,
+ updatedTs: history.updatedTs,
+ statement: history.payload.statement,
+ durationNs: history.payload.durationNs,
+ instanceName: history.payload.instanceName,
+ databaseName: history.payload.databaseName,
+ error: history.payload.error,
+ createdAt: dayjs(history.createdTs * 1000).format(
+ "YYYY-MM-DD HH:mm:ss"
+ ),
+ };
+ }
+ );
+
+ this.setQueryHistoryList(
+ queryHistoryList.sort((a, b) => b.createdTs - a.createdTs)
+ );
+ this.setIsFetchingQueryHistory(false);
+ },
+ async deleteQueryHistory(id: number) {
+ await useActivityStore().deleteActivityById(id);
+
+ this.setQueryHistoryList(
+ this.queryHistoryList.filter((t: QueryHistory) => t.id !== id)
+ );
+ },
+ },
+});
diff --git a/frontend/src/types/store.ts b/frontend/src/types/store.ts
index cc33b19eb5..81c0bd7732 100644
--- a/frontend/src/types/store.ts
+++ b/frontend/src/types/store.ts
@@ -203,9 +203,6 @@ export interface SqlEditorState {
isShowExecutingHint: boolean;
sharedSheet: Sheet;
}
-export type SqlEditorGetters = typeof sqlEditorStore.getters;
-export type SqlEditorActions = typeof sqlEditorStore.actions;
-export type SqlEditorMutations = typeof sqlEditorStore.mutations;
export interface TabState {
tabList: TabInfo[];
diff --git a/frontend/src/views/SqlEditor/AsidePanel/AsidePanel.vue b/frontend/src/views/SqlEditor/AsidePanel/AsidePanel.vue
index 05360022c2..49623d39f0 100644
--- a/frontend/src/views/SqlEditor/AsidePanel/AsidePanel.vue
+++ b/frontend/src/views/SqlEditor/AsidePanel/AsidePanel.vue
@@ -29,22 +29,18 @@
<script lang="ts" setup>
import { ref, watch } from "vue";
-import { useNamespacedState } from "vuex-composition-helpers";
-import type { SqlEditorState } from "@/types";
import DatabaseTree from "./DatabaseTree.vue";
import QueryHistoryContainer from "./QueryHistoryContainer.vue";
import SheetContainer from "./SheetContainer.vue";
import TableSchema from "./TableSchema.vue";
+import { useSQLEditorStore } from "@/store";
const FULL_HEIGHT = 100;
const DATABASE_PANE_SIZE = 60;
const TABLE_SCHEMA_PANE_SIZE = FULL_HEIGHT - DATABASE_PANE_SIZE;
-const { connectionContext } = useNamespacedState<SqlEditorState>("sqlEditor", [
- "connectionContext",
-]);
-
+const sqlEditorStore = useSQLEditorStore();
const databasePaneSzie = ref(FULL_HEIGHT);
const handleResized = (data: any) => {
@@ -57,7 +53,7 @@ const handleCloseTableSchemaPane = () => {
};
watch(
- () => connectionContext.value.option,
+ () => sqlEditorStore.connectionContext.option,
(option) => {
if (option && option.type === "table") {
databasePaneSzie.value = DATABASE_PANE_SIZE;
diff --git a/frontend/src/views/SqlEditor/AsidePanel/DatabaseTree.vue b/frontend/src/views/SqlEditor/AsidePanel/DatabaseTree.vue
index e3fd1cdad3..fcf3a79c1c 100644
--- a/frontend/src/views/SqlEditor/AsidePanel/DatabaseTree.vue
+++ b/frontend/src/views/SqlEditor/AsidePanel/DatabaseTree.vue
@@ -1,6 +1,6 @@
<template>
<div
- v-if="!connectionContext.isLoadingTree"
+ v-if="!sqlEditorStore.connectionContext.isLoadingTree"
class="databases-tree p-2 space-y-2 h-full"
>
<div class="databases-tree--input">
@@ -44,20 +44,12 @@
<script lang="ts" setup>
import { ref, computed, h } from "vue";
-import {
- useNamespacedState,
- useNamespacedGetters,
- useNamespacedActions,
-} from "vuex-composition-helpers";
import { cloneDeep, omit, escape } from "lodash-es";
import { useRouter } from "vue-router";
import { TreeOption, DropdownOption } from "naive-ui";
import {
ConnectionAtom,
- SqlEditorState,
- SqlEditorGetters,
- SqlEditorActions,
ConnectionContext,
Database,
UNKNOWN_ID,
@@ -67,26 +59,17 @@ import InstanceEngineIconVue from "@/components/InstanceEngineIcon.vue";
import HeroiconsOutlineDatabase from "~icons/heroicons-outline/database.vue";
import HeroiconsOutlineTable from "~icons/heroicons-outline/table.vue";
import HeroiconsSolidDotsHorizontal from "~icons/heroicons-solid/dots-horizontal.vue";
-import { useDatabaseStore, useInstanceStore, useTabStore } from "@/store";
+import {
+ useDatabaseStore,
+ useInstanceStore,
+ useTabStore,
+ useSQLEditorStore,
+} from "@/store";
const router = useRouter();
const instanceStore = useInstanceStore();
const tabStore = useTabStore();
-
-const { findProjectIdByDatabaseId, connectionInfo } =
- useNamespacedGetters<SqlEditorGetters>("sqlEditor", [
- "findProjectIdByDatabaseId",
- "connectionInfo",
- ]);
-const { connectionTree, connectionContext } =
- useNamespacedState<SqlEditorState>("sqlEditor", [
- "connectionTree",
- "connectionContext",
- ]);
-const { setConnectionContext } = useNamespacedActions<SqlEditorActions>(
- "sqlEditor",
- ["setConnectionContext"]
-);
+const sqlEditorStore = useSQLEditorStore();
const searchPattern = ref();
const showDropdown = ref(false);
@@ -128,7 +111,7 @@ const dropdownOptions = computed(() => {
});
const treeData = computed(() => {
- const tree = cloneDeep(connectionTree.value);
+ const tree = cloneDeep(sqlEditorStore.connectionTree);
// mapping the prefix icons
return tree.map((instanceItem) => {
@@ -157,7 +140,7 @@ const treeData = computed(() => {
});
const defaultExpanedKeys = computed(() => {
- const ctx = connectionContext.value;
+ const ctx = sqlEditorStore.connectionContext;
if (ctx.hasSlug) {
return [`instance-${ctx.instanceId}`, `database-${ctx.databaseId}`];
} else {
@@ -166,7 +149,7 @@ const defaultExpanedKeys = computed(() => {
});
const defaultSelectedKeys = computed(() => {
- const ctx = connectionContext.value;
+ const ctx = sqlEditorStore.connectionContext;
if (ctx.hasSlug) {
return [`database-${ctx.databaseId}`];
} else {
@@ -175,7 +158,7 @@ const defaultSelectedKeys = computed(() => {
});
const getFlattenConnectionTree = () => {
- const tree = connectionTree.value;
+ const tree = sqlEditorStore.connectionTree;
if (!tree) {
return {};
}
@@ -209,7 +192,7 @@ const getFlattenConnectionTree = () => {
const setSheetContext = (option: any) => {
if (option) {
- let ctx: ConnectionContext = cloneDeep(connectionContext.value);
+ let ctx: ConnectionContext = cloneDeep(sqlEditorStore.connectionContext);
const { instanceList, databaseList } = getFlattenConnectionTree();
const getInstanceNameByInstanceId = (id: number) => {
@@ -260,7 +243,7 @@ const setSheetContext = (option: any) => {
}
ctx.hasSlug = true;
- setConnectionContext(ctx);
+ sqlEditorStore.setConnectionContext(ctx);
if (ctx.instanceId !== UNKNOWN_ID && ctx.databaseId !== UNKNOWN_ID) {
const database = useDatabaseStore().getDatabaseById(
@@ -313,9 +296,9 @@ const renderSuffix = ({ option }: { option: TreeOption }) => {
const gotoAlterSchema = (option: any) => {
console.log(option);
const databaseId = option.parentId;
- const projectId = findProjectIdByDatabaseId.value(databaseId);
+ const projectId = sqlEditorStore.findProjectIdByDatabaseId(databaseId);
const databaseList =
- connectionInfo.value.databaseListByProjectId.get(projectId);
+ sqlEditorStore.connectionInfo.databaseListByProjectId.get(projectId);
const databaseName = databaseList.find(
(database: Database) => database.id === databaseId
).name;
@@ -363,9 +346,11 @@ const nodeProps = ({ option }: { option: TreeOption }) => {
onClick: (e: any) => {
if (e?.target?.id === "tree-node-suffix") return;
if (option) {
- let ctx: ConnectionContext = cloneDeep(connectionContext.value);
+ let ctx: ConnectionContext = cloneDeep(
+ sqlEditorStore.connectionContext
+ );
ctx.option = option;
- setConnectionContext(ctx);
+ sqlEditorStore.setConnectionContext(ctx);
}
},
onContextmenu(e: MouseEvent) {
diff --git a/frontend/src/views/SqlEditor/AsidePanel/QueryHistoryContainer.vue b/frontend/src/views/SqlEditor/AsidePanel/QueryHistoryContainer.vue
index d11095a7e2..c18f38a8fe 100644
--- a/frontend/src/views/SqlEditor/AsidePanel/QueryHistoryContainer.vue
+++ b/frontend/src/views/SqlEditor/AsidePanel/QueryHistoryContainer.vue
@@ -51,7 +51,7 @@
</div>
<div
- v-show="isLoading && queryHistoryList.length === 0"
+ v-show="isLoading && sqlEditorStore.queryHistoryList.length === 0"
class="absolute w-full h-full flex justify-center items-center"
>
<BBSpin :title="$t('common.loading')" />
@@ -64,14 +64,11 @@ import { escape } from "lodash-es";
import { computed, reactive } from "vue";
import { useI18n } from "vue-i18n";
import { useClipboard } from "@vueuse/core";
-import {
- useNamespacedActions,
- useNamespacedState,
-} from "vuex-composition-helpers";
+
import { useDialog } from "naive-ui";
-import { pushNotification, useTabStore } from "@/store";
-import { QueryHistory, SqlEditorActions, SqlEditorState } from "@/types";
+import { pushNotification, useTabStore, useSQLEditorStore } from "@/store";
+import { QueryHistory } from "@/types";
import { getHighlightHTMLByKeyWords } from "@/utils";
interface State {
@@ -82,16 +79,7 @@ interface State {
const { t } = useI18n();
const dialog = useDialog();
const tabStore = useTabStore();
-
-const { queryHistoryList, isFetchingQueryHistory: isLoading } =
- useNamespacedState<SqlEditorState>("sqlEditor", [
- "queryHistoryList",
- "isFetchingQueryHistory",
- ]);
-const { deleteQueryHistory } = useNamespacedActions<SqlEditorActions>(
- "sqlEditor",
- ["deleteQueryHistory"]
-);
+const sqlEditorStore = useSQLEditorStore();
const state = reactive<State>({
search: "",
@@ -101,10 +89,15 @@ const state = reactive<State>({
const { copy: copyTextToClipboard, isSupported: isCopySupported } =
useClipboard();
+const isLoading = computed(() => {
+ return sqlEditorStore.isFetchingQueryHistory;
+});
+
const data = computed(() => {
const tempData =
- queryHistoryList.value && queryHistoryList.value.length > 0
- ? queryHistoryList.value.filter((history) => {
+ sqlEditorStore.queryHistoryList &&
+ sqlEditorStore.queryHistoryList.length > 0
+ ? sqlEditorStore.queryHistoryList.filter((history) => {
let t = false;
if (history.statement.includes(state.search)) {
@@ -132,7 +125,7 @@ const notifyMessage = computed(() => {
if (isLoading.value) {
return "";
}
- if (queryHistoryList.value.length === null) {
+ if (sqlEditorStore.queryHistoryList.length === null) {
return t("sql-editor.no-history-found");
}
@@ -159,7 +152,7 @@ const actionDropdownOptions = computed(() => {
const handleDeleteHistory = () => {
if (state.currentActionHistory) {
- deleteQueryHistory(state.currentActionHistory.id);
+ sqlEditorStore.deleteQueryHistory(state.currentActionHistory.id);
}
};
diff --git a/frontend/src/views/SqlEditor/AsidePanel/SheetContainer.vue b/frontend/src/views/SqlEditor/AsidePanel/SheetContainer.vue
index abe48615aa..77917a9d55 100644
--- a/frontend/src/views/SqlEditor/AsidePanel/SheetContainer.vue
+++ b/frontend/src/views/SqlEditor/AsidePanel/SheetContainer.vue
@@ -90,15 +90,8 @@ import {
} from "vuex-composition-helpers";
import { useDialog } from "naive-ui";
-import { useTabStore } from "@/store";
-import {
- SheetActions,
- SheetState,
- Sheet,
- SqlEditorActions,
- SqlEditorState,
- UNKNOWN_ID,
-} from "@/types";
+import { useTabStore, useSQLEditorStore } from "@/store";
+import { SheetActions, SheetState, Sheet, UNKNOWN_ID } from "@/types";
import { getHighlightHTMLByKeyWords } from "@/utils";
import { useSQLEditorConnection } from "@/composables/useSQLEditorConnection";
@@ -113,19 +106,11 @@ const { t } = useI18n();
const { setConnectionContextFromCurrentTab } = useSQLEditorConnection();
const dialog = useDialog();
const tabStore = useTabStore();
+const sqlEditorStore = useSQLEditorStore();
-const { sharedSheet, isFetchingSheet: isLoading } =
- useNamespacedState<SqlEditorState>("sqlEditor", [
- "sharedSheet",
- "isFetchingSheet",
- ]);
-const { sheetList } = useNamespacedState<SheetState>("sheet", ["sheetList"]);
+const isLoading = computed(() => sqlEditorStore.isFetchingSheet);
-// actions
-const { setShouldSetContent } = useNamespacedActions<SqlEditorActions>(
- "sqlEditor",
- ["setShouldSetContent"]
-);
+const { sheetList } = useNamespacedState<SheetState>("sheet", ["sheetList"]);
const { deleteSheet, patchSheetById } = useNamespacedActions<SheetActions>(
"sheet",
@@ -143,8 +128,8 @@ const queryNameInputerRef = ref<HTMLInputElement>();
const data = computed(() => {
const filterSheetList =
- sharedSheet.value.id !== UNKNOWN_ID
- ? [...sheetList.value, sharedSheet.value]
+ sqlEditorStore.sharedSheet.id !== UNKNOWN_ID
+ ? [...sheetList.value, sqlEditorStore.sharedSheet]
: sheetList.value;
const tempData =
filterSheetList && filterSheetList.length > 0
@@ -270,7 +255,7 @@ const handleSheetClick = async (sheet: Sheet) => {
if (tab.sheetId === sheet.id) {
tabStore.setCurrentTabId(tab.id);
setConnectionContextFromCurrentTab();
- setShouldSetContent(true);
+ sqlEditorStore.setShouldSetContent(true);
return;
}
}
@@ -283,7 +268,7 @@ const handleSheetClick = async (sheet: Sheet) => {
sheetId: sheet.id,
});
setConnectionContextFromCurrentTab();
- setShouldSetContent(true);
+ sqlEditorStore.setShouldSetContent(true);
}
};
</script>
diff --git a/frontend/src/views/SqlEditor/AsidePanel/TableSchema.vue b/frontend/src/views/SqlEditor/AsidePanel/TableSchema.vue
index 68fed6159b..1cc885d437 100644
--- a/frontend/src/views/SqlEditor/AsidePanel/TableSchema.vue
+++ b/frontend/src/views/SqlEditor/AsidePanel/TableSchema.vue
@@ -66,44 +66,26 @@
<script lang="ts" setup>
import { ref, watch } from "vue";
import { useRouter } from "vue-router";
-import {
- useNamespacedGetters,
- useNamespacedState,
- useNamespacedActions,
-} from "vuex-composition-helpers";
-import type {
- SqlEditorState,
- SqlEditorGetters,
- Database,
- DatabaseId,
-} from "@/types";
+import type { Database, DatabaseId } from "@/types";
+import { useSQLEditorStore, useTableStore } from "@/store";
const emit = defineEmits<{
(e: "close-pane"): void;
}>();
-const { findProjectIdByDatabaseId, connectionInfo } =
- useNamespacedGetters<SqlEditorGetters>("sqlEditor", [
- "findProjectIdByDatabaseId",
- "connectionInfo",
- ]);
-const { connectionContext } = useNamespacedState<SqlEditorState>("sqlEditor", [
- "connectionContext",
-]);
-const { fetchTableByDatabaseIdAndTableName } = useNamespacedActions("table", [
- "fetchTableByDatabaseIdAndTableName",
-]);
+const tableStore = useTableStore();
+const sqlEditorStore = useSQLEditorStore();
const tableInfo = ref();
-const ctx = connectionContext.value;
+const ctx = sqlEditorStore.connectionContext;
const router = useRouter();
const gotoAlterSchema = () => {
const databaseId = ctx.databaseId as DatabaseId;
- const projectId = findProjectIdByDatabaseId.value(databaseId);
+ const projectId = sqlEditorStore.findProjectIdByDatabaseId(databaseId);
const databaseList =
- connectionInfo.value.databaseListByProjectId.get(projectId);
+ sqlEditorStore.connectionInfo.databaseListByProjectId.get(projectId) as any;
const databaseName = databaseList.find(
(database: Database) => database.id === databaseId
).name;
@@ -127,12 +109,12 @@ const handleClosePane = () => {
};
watch(
- () => connectionContext.value.option,
+ () => sqlEditorStore.connectionContext.option,
async (option) => {
if (option && option.type === "table") {
- const res = await fetchTableByDatabaseIdAndTableName({
- databaseId: option.parentId,
- tableName: option.label,
+ const res = await tableStore.fetchTableByDatabaseIdAndTableName({
+ databaseId: option.parentId as number,
+ tableName: option.label as string,
});
tableInfo.value = res;
diff --git a/frontend/src/views/SqlEditor/EditorPanel/EditorAction.vue b/frontend/src/views/SqlEditor/EditorPanel/EditorAction.vue
index 80aa38d1b5..84a56fc05e 100644
--- a/frontend/src/views/SqlEditor/EditorPanel/EditorAction.vue
+++ b/frontend/src/views/SqlEditor/EditorPanel/EditorAction.vue
@@ -106,7 +106,9 @@
<template #trigger>
<NButton
:disabled="
- isEmptyStatement || isDisconnected || !tabStore.currentTab.isSaved
+ isEmptyStatement ||
+ sqlEditorStore.isDisconnected ||
+ !tabStore.currentTab.isSaved
"
@click.stop.prevent="toggleSharePopover"
>
@@ -121,20 +123,9 @@
<script lang="ts" setup>
import { computed, ref, defineEmits } from "vue";
-import {
- useNamespacedState,
- useNamespacedGetters,
- useNamespacedActions,
-} from "vuex-composition-helpers";
-
-import { useInstanceStore, useTabStore } from "@/store";
-import {
- SqlEditorState,
- SqlEditorGetters,
- SqlEditorActions,
- UNKNOWN_ID,
- Instance,
-} from "@/types";
+
+import { useInstanceStore, useTabStore, useSQLEditorStore } from "@/store";
+import { UNKNOWN_ID, Instance } from "@/types";
import { useExecuteSQL } from "@/composables/useExecuteSQL";
import SharePopover from "./SharePopover.vue";
import { useRouter } from "vue-router";
@@ -147,18 +138,9 @@ const emit = defineEmits<{
const router = useRouter();
const instanceStore = useInstanceStore();
const tabStore = useTabStore();
+const sqlEditorStore = useSQLEditorStore();
-const { connectionContext } = useNamespacedState<SqlEditorState>("sqlEditor", [
- "connectionContext",
-]);
-const { isDisconnected } = useNamespacedGetters<SqlEditorGetters>("sqlEditor", [
- "isDisconnected",
-]);
-
-const { setShouldFormatContent } = useNamespacedActions<SqlEditorActions>(
- "sqlEditor",
- ["setShouldFormatContent"]
-);
+const connectionContext = computed(() => sqlEditorStore.connectionContext);
const isShowSharePopover = ref(false);
@@ -166,7 +148,7 @@ const isEmptyStatement = computed(
() => !tabStore.currentTab || tabStore.currentTab.statement === ""
);
const selectedInstance = computed<Instance>(() => {
- const ctx = connectionContext.value;
+ const ctx = sqlEditorStore.connectionContext;
return instanceStore.getInstanceById(ctx.instanceId);
});
const selectedInstanceEngine = computed(() => {
@@ -210,7 +192,7 @@ const toggleSharePopover = () => {
};
const handleFormatSQL = () => {
- setShouldFormatContent(true);
+ sqlEditorStore.setShouldFormatContent(true);
};
</script>
diff --git a/frontend/src/views/SqlEditor/EditorPanel/EditorPanel.vue b/frontend/src/views/SqlEditor/EditorPanel/EditorPanel.vue
index 986f3f1dfc..c264be7de1 100644
--- a/frontend/src/views/SqlEditor/EditorPanel/EditorPanel.vue
+++ b/frontend/src/views/SqlEditor/EditorPanel/EditorPanel.vue
@@ -2,7 +2,7 @@
<div class="editor-pane h-full">
<EditorAction @save-sheet="handleSaveSheet" />
- <template v-if="!isDisconnected">
+ <template v-if="!sqlEditorStore.isDisconnected">
<QueryEditor @save-sheet="handleSaveSheet" />
</template>
<template v-else>
@@ -10,7 +10,7 @@
</template>
<BBModal
- v-if="isShowExecutingHint"
+ v-if="sqlEditorStore.isShowExecutingHint"
:title="$t('common.tips')"
@close="handleClose"
>
@@ -28,19 +28,10 @@
<script lang="ts" setup>
import { ref } from "vue";
-import {
- useNamespacedState,
- useNamespacedGetters,
- useNamespacedActions,
-} from "vuex-composition-helpers";
+import { useNamespacedActions } from "vuex-composition-helpers";
-import { useTabStore } from "@/store";
-import {
- SqlEditorState,
- SqlEditorActions,
- SqlEditorGetters,
- SheetActions,
-} from "@/types";
+import { useTabStore, useSQLEditorStore } from "@/store";
+import { SheetActions } from "@/types";
import EditorAction from "./EditorAction.vue";
import QueryEditor from "./QueryEditor.vue";
import ExecuteHint from "./ExecuteHint.vue";
@@ -49,20 +40,7 @@ import SaveSheetModal from "./SaveSheetModal.vue";
import { defaultTabName } from "../../../utils/tab";
const tabStore = useTabStore();
-
-const { isShowExecutingHint } = useNamespacedState<SqlEditorState>(
- "sqlEditor",
- ["isShowExecutingHint"]
-);
-
-const { isDisconnected } = useNamespacedGetters<SqlEditorGetters>("sqlEditor", [
- "isDisconnected",
-]);
-
-const { setSqlEditorState } = useNamespacedActions<SqlEditorActions>(
- "sqlEditor",
- ["setSqlEditorState"]
-);
+const sqlEditorStore = useSQLEditorStore();
// actions
const { upsertSheet } = useNamespacedActions<SheetActions>("sheet", [
@@ -72,7 +50,7 @@ const { upsertSheet } = useNamespacedActions<SheetActions>("sheet", [
const isShowSaveSheetModal = ref(false);
const handleClose = () => {
- setSqlEditorState({
+ sqlEditorStore.setSqlEditorState({
isShowExecutingHint: false,
});
};
diff --git a/frontend/src/views/SqlEditor/EditorPanel/ExecuteHint.vue b/frontend/src/views/SqlEditor/EditorPanel/ExecuteHint.vue
index 7116e99219..ccb0755b35 100644
--- a/frontend/src/views/SqlEditor/EditorPanel/ExecuteHint.vue
+++ b/frontend/src/views/SqlEditor/EditorPanel/ExecuteHint.vue
@@ -51,15 +51,10 @@
import { computed } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
-import {
- useNamespacedGetters,
- useNamespacedState,
-} from "vuex-composition-helpers";
-import { pushNotification, useTabStore } from "@/store";
+import { pushNotification, useTabStore, useSQLEditorStore } from "@/store";
import { UNKNOWN_ID } from "@/types";
-import type { SqlEditorState, SqlEditorGetters } from "@/types";
import {
parseSQL,
transformSQL,
@@ -73,14 +68,7 @@ const emit = defineEmits<{
const router = useRouter();
const { t } = useI18n();
const tabStore = useTabStore();
-
-const { findProjectIdByDatabaseId } = useNamespacedGetters<SqlEditorGetters>(
- "sqlEditor",
- ["findProjectIdByDatabaseId"]
-);
-const { connectionContext } = useNamespacedState<SqlEditorState>("sqlEditor", [
- "connectionContext",
-]);
+const sqlEditorStore = useSQLEditorStore();
const sqlStatement = computed(
() => tabStore.currentTab.selectedStatement || tabStore.currentTab.statement
@@ -98,7 +86,7 @@ const isDDLSQLStatement = computed(() => {
return data !== null ? isDDLStatement(data) : false;
});
-const ctx = connectionContext.value;
+const ctx = computed(() => sqlEditorStore.connectionContext);
const docLink =
"https://bytebase.com/docs/concepts/schema-change-workflow#ui-workflow";
@@ -108,7 +96,7 @@ const handleColse = () => {
};
const gotoAlterSchema = () => {
- if (ctx.databaseId === UNKNOWN_ID) {
+ if (ctx.value.databaseId === UNKNOWN_ID) {
pushNotification({
module: "bytebase",
style: "CRITICAL",
@@ -119,7 +107,9 @@ const gotoAlterSchema = () => {
emit("close");
- const projectId = findProjectIdByDatabaseId.value(ctx.databaseId as number);
+ const projectId = sqlEditorStore.findProjectIdByDatabaseId(
+ ctx.value.databaseId as number
+ );
const DDLIssueTemplate = "bb.issue.database.schema.update";
const DMLIssueTemplate = "bb.issue.database.data.update";
@@ -130,11 +120,11 @@ const gotoAlterSchema = () => {
},
query: {
template: isDDLSQLStatement.value ? DDLIssueTemplate : DMLIssueTemplate,
- name: `[${ctx.databaseName}] ${
+ name: `[${ctx.value.databaseName}] ${
isDDLSQLStatement.value ? "Alter schema" : "Change Data"
}`,
project: projectId,
- databaseList: ctx.databaseId,
+ databaseList: ctx.value.databaseId,
sql: getParsedStatement(),
},
});
diff --git a/frontend/src/views/SqlEditor/EditorPanel/QueryEditor.vue b/frontend/src/views/SqlEditor/EditorPanel/QueryEditor.vue
index 9f9401d824..17732d983e 100644
--- a/frontend/src/views/SqlEditor/EditorPanel/QueryEditor.vue
+++ b/frontend/src/views/SqlEditor/EditorPanel/QueryEditor.vue
@@ -12,11 +12,9 @@
<script lang="ts" setup>
import { debounce } from "lodash-es";
import { computed, defineEmits } from "vue";
-import { useNamespacedState } from "vuex-composition-helpers";
-import { useInstanceStore, useTabStore } from "@/store";
+import { useInstanceStore, useTabStore, useSQLEditorStore } from "@/store";
import { useExecuteSQL } from "@/composables/useExecuteSQL";
-import { SqlEditorState } from "@/types";
const emit = defineEmits<{
(e: "save-sheet", content?: string): void;
@@ -24,16 +22,13 @@ const emit = defineEmits<{
const instanceStore = useInstanceStore();
const tabStore = useTabStore();
-
-const { connectionContext } = useNamespacedState<SqlEditorState>("sqlEditor", [
- "connectionContext",
-]);
+const sqlEditorStore = useSQLEditorStore();
const { execute } = useExecuteSQL();
const sqlCode = computed(() => tabStore.currentTab.statement);
const selectedInstance = computed(() => {
- const ctx = connectionContext.value;
+ const ctx = sqlEditorStore.connectionContext;
return instanceStore.getInstanceById(ctx.instanceId);
});
const selectedInstanceEngine = computed(() => {
diff --git a/frontend/src/views/SqlEditor/EditorPanel/SharePopover.vue b/frontend/src/views/SqlEditor/EditorPanel/SharePopover.vue
index 5f7a7bc8a7..e9aed97983 100644
--- a/frontend/src/views/SqlEditor/EditorPanel/SharePopover.vue
+++ b/frontend/src/views/SqlEditor/EditorPanel/SharePopover.vue
@@ -81,18 +81,12 @@ import { useClipboard } from "@vueuse/core";
import { useI18n } from "vue-i18n";
import {
useNamespacedGetters,
- useNamespacedState,
useNamespacedActions,
} from "vuex-composition-helpers";
import slug from "slug";
-import { pushNotification, useTabStore } from "@/store";
-import {
- SqlEditorState,
- SheetGetters,
- SheetActions,
- AccessOption,
-} from "@/types";
+import { pushNotification, useTabStore, useSQLEditorStore } from "@/store";
+import { SheetGetters, SheetActions, AccessOption } from "@/types";
const emit = defineEmits<{
(e: "close"): void;
@@ -100,6 +94,7 @@ const emit = defineEmits<{
const { t } = useI18n();
const tabStore = useTabStore();
+const sqlEditorStore = useSQLEditorStore();
const accessOptions = computed<AccessOption[]>(() => {
return [
@@ -121,9 +116,6 @@ const accessOptions = computed<AccessOption[]>(() => {
];
});
-const { connectionContext } = useNamespacedState<SqlEditorState>("sqlEditor", [
- "connectionContext",
-]);
const { currentSheet, isCreator } = useNamespacedGetters<SheetGetters>(
"sheet",
["currentSheet", "isCreator"]
@@ -132,17 +124,17 @@ const { patchSheetById } = useNamespacedActions<SheetActions>("sheet", [
"patchSheetById",
]);
-const ctx = connectionContext.value;
+const ctx = computed(() => sqlEditorStore.connectionContext);
const sheet = computed(() => currentSheet.value(tabStore.currentTab));
const creator = computed(() => isCreator.value(tabStore.currentTab));
const host = window.location.host;
const connectionSlug = [
- slug(ctx.instanceName as string),
- ctx.instanceId,
- slug(ctx.databaseName as string),
- ctx.databaseId,
+ slug(ctx.value.instanceName as string),
+ ctx.value.instanceId,
+ slug(ctx.value.databaseName as string),
+ ctx.value.databaseId,
].join("_");
const currentAccess = ref<AccessOption>(accessOptions.value[0]);
diff --git a/frontend/src/views/SqlEditor/SqlEditor.vue b/frontend/src/views/SqlEditor/SqlEditor.vue
index 380a1fa013..9705956608 100644
--- a/frontend/src/views/SqlEditor/SqlEditor.vue
+++ b/frontend/src/views/SqlEditor/SqlEditor.vue
@@ -26,22 +26,19 @@
<script lang="ts" setup>
import { computed } from "vue";
-import { useStore } from "vuex";
import AsidePanel from "./AsidePanel/AsidePanel.vue";
import EditorPanel from "./EditorPanel/EditorPanel.vue";
import TabListContainer from "./TabListContainer.vue";
import TablePanel from "./TablePanel/TablePanel.vue";
import GettingStarted from "./GettingStarted.vue";
-import { useTabStore } from "@/store";
+import { useTabStore, useSQLEditorStore } from "@/store";
-const store = useStore();
const tabStore = useTabStore();
+const sqlEditorStore = useSQLEditorStore();
const hasTabs = computed(() => tabStore.hasTabs);
const paneKey = computed(() => tabStore.currentTab.id);
-const isDisconnected = computed(
- () => store.getters["sqlEditor/isDisconnected"]
-);
+const isDisconnected = computed(() => sqlEditorStore.isDisconnected);
</script>
<style>
diff --git a/frontend/src/views/SqlEditor/TablePanel/TableView.vue b/frontend/src/views/SqlEditor/TablePanel/TableView.vue
index eddc5dd084..c87d2c40df 100644
--- a/frontend/src/views/SqlEditor/TablePanel/TableView.vue
+++ b/frontend/src/views/SqlEditor/TablePanel/TableView.vue
@@ -66,14 +66,11 @@
import { computed, reactive, ref } from "vue";
import { useI18n } from "vue-i18n";
import { useResizeObserver } from "@vueuse/core";
-import { useNamespacedState } from "vuex-composition-helpers";
import { unparse } from "papaparse";
import { isEmpty } from "lodash-es";
import dayjs from "dayjs";
-import { useTabStore } from "@/store";
-
-import { SqlEditorState } from "@/types";
+import { useTabStore, useSQLEditorStore } from "@/store";
interface State {
search: string;
@@ -81,10 +78,7 @@ interface State {
const { t } = useI18n();
const tabStore = useTabStore();
-
-const { isExecuting } = useNamespacedState<SqlEditorState>("sqlEditor", [
- "isExecuting",
-]);
+const sqlEditorStore = useSQLEditorStore();
const queryResult = computed(() => tabStore.currentTab.queryResult || null);
@@ -138,7 +132,7 @@ const notifyMessage = computed(() => {
if (queryResult.value === null) {
return t("sql-editor.table-empty-placehoder");
}
- if (isExecuting.value) {
+ if (sqlEditorStore.isExecuting) {
return t("sql-editor.loading-data");
}
const data = queryResult.value[2];
@@ -186,7 +180,7 @@ const handleExportBtnClick = (format: "csv" | "json") => {
const encodedUri = encodeURI(`data:text/${format};charset=utf-8,${rawText}`);
const formatedDateString = dayjs(new Date()).format("YYYY-MM-DDTHH-mm-ss");
// Example filename: `mysheet-2022-03-23T09-54-21.json`
- const filename = `${currentTab.value.name}-${formatedDateString}`;
+ const filename = `${tabStore.currentTab.name}-${formatedDateString}`;
const link = document.createElement("a");
link.download = `${filename}.${format}`;