Skip to content

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

refactor(sql-editor): keep connection when switching tabs (#2576)

Liu Jiba0de56deebc
diff --git a/frontend/src/components/ProvideSQLEditorContext.vue b/frontend/src/components/ProvideSQLEditorContext.vue
index fec97849c9..411795ca27 100644
--- a/frontend/src/components/ProvideSQLEditorContext.vue
+++ b/frontend/src/components/ProvideSQLEditorContext.vue
@@ -16,8 +16,14 @@ import {
useDebugStore,
useInstanceStore,
} from "@/store";
-import { Instance, Database, ConnectionAtom, UNKNOWN_ID } from "@/types";
-import { mapConnectionAtom } from "@/utils";
+import {
+ Instance,
+ Database,
+ ConnectionAtom,
+ UNKNOWN_ID,
+ DEFAULT_PROJECT_ID,
+} from "@/types";
+import { emptyConnection, mapConnectionAtom } from "@/utils";
type LocalState = {
instanceList: Instance[];
@@ -90,6 +96,12 @@ const prepareSheetFromQuery = async () => {
name: sheet.name,
statement: sheet.statement,
isSaved: true,
+ connection: {
+ ...emptyConnection(),
+ projectId: sheet.database?.projectId || DEFAULT_PROJECT_ID,
+ instanceId: sheet.database?.instanceId || UNKNOWN_ID,
+ databaseId: sheet.databaseId || UNKNOWN_ID,
+ },
});
setConnectionContextFromCurrentTab();
useSQLEditorStore().setSQLEditorState({
diff --git a/frontend/src/composables/useExecuteSQL.ts b/frontend/src/composables/useExecuteSQL.ts
index 6cecdf2555..34384d054c 100644
--- a/frontend/src/composables/useExecuteSQL.ts
+++ b/frontend/src/composables/useExecuteSQL.ts
@@ -45,7 +45,7 @@ const useExecuteSQL = () => {
notify("INFO", t("common.tips"), t("sql-editor.can-not-execute-query"));
}
- const isDisconnected = sqlEditorStore.isDisconnected;
+ const isDisconnected = tabStore.isDisconnected;
if (isDisconnected) {
notify("CRITICAL", t("sql-editor.select-connection"));
return;
diff --git a/frontend/src/composables/useSQLEditorConnection.ts b/frontend/src/composables/useSQLEditorConnection.ts
index f80a48958b..38a6343571 100644
--- a/frontend/src/composables/useSQLEditorConnection.ts
+++ b/frontend/src/composables/useSQLEditorConnection.ts
@@ -1,19 +1,12 @@
import { useRouter } from "vue-router";
-import { DEFAULT_PROJECT_ID, Sheet, UNKNOWN_ID } from "../types";
+import { Sheet } from "../types";
import { connectionSlug } from "../utils";
-import { getDefaultConnectionContext } from "@/store";
-import {
- useDatabaseStore,
- useTabStore,
- useSQLEditorStore,
- useSheetStore,
-} from "@/store";
+import { useDatabaseStore, useTabStore, useSheetStore } from "@/store";
const useSQLEditorConnection = () => {
const router = useRouter();
const tabStore = useTabStore();
- const sqlEditorStore = useSQLEditorStore();
const sheetStore = useSheetStore();
/**
@@ -26,13 +19,6 @@ const useSQLEditorConnection = () => {
if (currentTab.sheetId && sheetById.has(currentTab.sheetId)) {
const sheet = sheetById.get(currentTab.sheetId) as Sheet;
- sqlEditorStore.setConnectionContext({
- hasSlug: true,
- projectId: sheet.database?.projectId || DEFAULT_PROJECT_ID,
- instanceId: sheet.database?.instanceId || UNKNOWN_ID,
- databaseId: sheet.databaseId || UNKNOWN_ID,
- });
-
if (sheet.databaseId) {
const database = useDatabaseStore().getDatabaseById(sheet.databaseId);
@@ -47,8 +33,6 @@ const useSQLEditorConnection = () => {
});
}
} else {
- sqlEditorStore.setConnectionContext(getDefaultConnectionContext());
-
router.push({
path: "/sql-editor",
});
diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts
index ce33a21636..b0af287f04 100644
--- a/frontend/src/router/index.ts
+++ b/frontend/src/router/index.ts
@@ -1337,12 +1337,10 @@ router.beforeEach((to, from, next) => {
useSheetStore()
.fetchSheetById(Number(sheetId))
.then((sheet: Sheet) => {
- tabStore.addTab({
+ tabStore.updateCurrentTab({
name: sheet.name,
statement: sheet.statement,
isSaved: true,
- });
- tabStore.updateCurrentTab({
sheetId: sheet.id,
});
useSQLEditorStore().setSQLEditorState({
diff --git a/frontend/src/store/modules/database.ts b/frontend/src/store/modules/database.ts
index d073a9d2c2..0d41749ecf 100644
--- a/frontend/src/store/modules/database.ts
+++ b/frontend/src/store/modules/database.ts
@@ -1,5 +1,6 @@
import { defineStore } from "pinia";
import axios from "axios";
+import { computed, unref, watch } from "vue";
import {
Backup,
Database,
@@ -14,12 +15,14 @@ import {
EnvironmentId,
Instance,
InstanceId,
+ MaybeRef,
PrincipalId,
Project,
ProjectId,
ResourceIdentifier,
ResourceObject,
unknown,
+ UNKNOWN_ID,
} from "@/types";
import { getPrincipalFromIncludedList } from "./principal";
import { useBackupStore } from "./backup";
@@ -443,3 +446,20 @@ export const useDatabaseStore = defineStore("database", {
},
},
});
+
+export const useDatabaseById = (databaseId: MaybeRef<DatabaseId>) => {
+ const store = useDatabaseStore();
+ watch(
+ () => unref(databaseId),
+ (id) => {
+ if (id !== UNKNOWN_ID) {
+ if (store.getDatabaseById(id).id === UNKNOWN_ID) {
+ store.fetchDatabaseById(id);
+ }
+ }
+ },
+ { immediate: true }
+ );
+
+ return computed(() => store.getDatabaseById(unref(databaseId)));
+};
diff --git a/frontend/src/store/modules/instance.ts b/frontend/src/store/modules/instance.ts
index bfd364f976..0546c4a295 100644
--- a/frontend/src/store/modules/instance.ts
+++ b/frontend/src/store/modules/instance.ts
@@ -1,6 +1,6 @@
import { defineStore } from "pinia";
import axios from "axios";
-import { computed, onBeforeMount } from "vue";
+import { computed, onBeforeMount, unref, watch } from "vue";
import {
DataSource,
empty,
@@ -15,6 +15,7 @@ import {
InstanceState,
InstanceUserId,
INSTANCE_OPERATION_TIMEOUT,
+ MaybeRef,
MigrationHistory,
MigrationHistoryId,
ResourceIdentifier,
@@ -22,6 +23,7 @@ import {
RowStatus,
SQLResultSet,
unknown,
+ UNKNOWN_ID,
} from "@/types";
import { InstanceUser } from "@/types/InstanceUser";
import { getPrincipalFromIncludedList } from "./principal";
@@ -496,3 +498,20 @@ export const useInstanceList = (rowStatusList?: RowStatus[]) => {
onBeforeMount(() => store.fetchInstanceList(rowStatusList));
return computed(() => store.getInstanceList(rowStatusList));
};
+
+export const useInstanceById = (instanceId: MaybeRef<InstanceId>) => {
+ const store = useInstanceStore();
+ watch(
+ () => unref(instanceId),
+ (id) => {
+ if (id !== UNKNOWN_ID) {
+ if (store.getInstanceById(id).id === UNKNOWN_ID) {
+ store.fetchInstanceById(id);
+ }
+ }
+ },
+ { immediate: true }
+ );
+
+ return computed(() => store.getInstanceById(unref(instanceId)));
+};
diff --git a/frontend/src/store/modules/sqlEditor.ts b/frontend/src/store/modules/sqlEditor.ts
index c27a75ad07..43a20b75b5 100644
--- a/frontend/src/store/modules/sqlEditor.ts
+++ b/frontend/src/store/modules/sqlEditor.ts
@@ -1,6 +1,5 @@
import { defineStore } from "pinia";
import dayjs from "dayjs";
-import { isEmpty } from "lodash-es";
import {
SQLEditorState,
ConnectionAtom,
@@ -12,8 +11,8 @@ import {
QueryHistory,
UNKNOWN_ID,
Sheet,
- DEFAULT_PROJECT_ID,
unknown,
+ InstanceId,
} from "@/types";
import { useActivityStore } from "./activity";
import { useDatabaseStore } from "./database";
@@ -21,20 +20,12 @@ import { useInstanceStore } from "./instance";
import { useTableStore } from "./table";
import { useSQLStore } from "./sql";
import { useProjectStore } from "./project";
+import { useTabStore } from "./tab";
+import { emptyConnection } from "@/utils";
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: {},
+ option: {} as any,
});
export const useSQLEditorStore = defineStore("sqlEditor", {
@@ -53,14 +44,7 @@ export const useSQLEditorStore = defineStore("sqlEditor", {
}),
getters: {
- connectionTreeByInstanceId(state): Partial<ConnectionAtom> {
- const idx = state.connectionTree.findIndex((item) => {
- return item.id === state.connectionContext.instanceId;
- });
-
- return idx !== -1 ? state.connectionTree[idx] : {};
- },
-
+ // TODO: remove this after a refactor to <TableSchema>
connectionInfo() {
const projectStore = useProjectStore();
const instanceStore = useInstanceStore();
@@ -75,30 +59,6 @@ export const useSQLEditorStore = defineStore("sqlEditor", {
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 => {
@@ -116,27 +76,6 @@ export const useSQLEditorStore = defineStore("sqlEditor", {
}
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: {
@@ -165,9 +104,12 @@ export const useSQLEditorStore = defineStore("sqlEditor", {
this.isFetchingQueryHistory = payload;
},
async executeQuery({ statement }: Pick<QueryInfo, "statement">) {
+ const { instanceId, databaseId } = useTabStore().currentTab.connection;
+ const database = useDatabaseStore().getDatabaseById(databaseId);
+ const databaseName = database.id === UNKNOWN_ID ? "" : database.name;
const queryResult = await useSQLStore().query({
- instanceId: this.connectionContext.instanceId,
- databaseName: this.connectionContext.databaseName,
+ instanceId,
+ databaseName,
statement: statement,
// set the limit to 10000 temporarily to avoid the query timeout and page crash
limit: 10000,
@@ -178,18 +120,23 @@ export const useSQLEditorStore = defineStore("sqlEditor", {
async fetchConnectionByInstanceIdAndDatabaseId({
instanceId,
databaseId,
- }: Pick<SQLEditorState["connectionContext"], "instanceId" | "databaseId">) {
- const instance = await useInstanceStore().fetchInstanceById(instanceId);
- const database = await useDatabaseStore().fetchDatabaseById(databaseId);
- await useTableStore().fetchTableListByDatabaseId(database.id);
+ }: {
+ instanceId: InstanceId;
+ databaseId: DatabaseId;
+ }) {
+ const [database] = await Promise.all([
+ useDatabaseStore().fetchDatabaseById(databaseId),
+ useInstanceStore().fetchInstanceById(instanceId),
+ useTableStore().fetchTableListByDatabaseId(databaseId),
+ ]);
- this.setConnectionContext({
- hasSlug: true,
- instanceId,
- instanceName: instance.name,
- databaseId: database.syncStatus === "OK" ? database.id : undefined,
- databaseName: database.syncStatus === "OK" ? database.name : undefined,
- databaseType: instance.engine,
+ useTabStore().updateCurrentTab({
+ connection: {
+ ...emptyConnection(),
+ projectId: database.project.id,
+ instanceId,
+ databaseId,
+ },
});
},
async fetchQueryHistoryList() {
diff --git a/frontend/src/store/modules/tab.ts b/frontend/src/store/modules/tab.ts
index 1c9861c37d..d1f421bd2c 100644
--- a/frontend/src/store/modules/tab.ts
+++ b/frontend/src/store/modules/tab.ts
@@ -1,23 +1,34 @@
import { defineStore } from "pinia";
-import { TabInfo, AnyTabInfo, TabState } from "@/types";
-import { getDefaultTab } from "@/utils/tab";
+import { TabInfo, AnyTabInfo, TabState, UNKNOWN_ID } from "@/types";
+import { getDefaultTab, INITIAL_TAB } from "@/utils";
+import { useInstanceStore } from "./instance";
export const useTabStore = defineStore("tab", {
state: (): TabState => ({
- tabList: [],
- currentTabId: "",
+ tabList: [INITIAL_TAB],
+ currentTabId: INITIAL_TAB.id,
}),
getters: {
currentTab(state): TabInfo {
- const idx = state.tabList.findIndex(
- (tab: TabInfo) => tab.id === state.currentTabId
- );
- return (idx === -1 ? {} : state.tabList[idx]) as TabInfo;
+ const tab = state.tabList.find((tab) => tab.id === state.currentTabId);
+ return tab ?? getDefaultTab();
},
hasTabs(state: TabState): boolean {
return state.tabList.length > 0;
},
+ isDisconnected(): boolean {
+ const { instanceId, databaseId } = this.currentTab.connection;
+ if (instanceId === UNKNOWN_ID) {
+ return true;
+ }
+ const instance = useInstanceStore().getInstanceById(instanceId);
+ if (instance.engine === "MYSQL" || instance.engine === "TIDB") {
+ // Connecting to instance directly.
+ return false;
+ }
+ return databaseId === UNKNOWN_ID;
+ },
},
actions: {
@@ -41,13 +52,7 @@ export const useTabStore = defineStore("tab", {
this.tabList.splice(this.tabList.indexOf(payload), 1);
},
updateCurrentTab(payload: AnyTabInfo) {
- const idx = this.tabList.findIndex(
- (tab: TabInfo) => tab.id === this.currentTabId
- );
- Object.assign(this.tabList[idx], {
- ...this.tabList[idx],
- ...payload,
- });
+ Object.assign(this.currentTab, payload);
},
setCurrentTabId(payload: string) {
this.currentTabId = payload;
diff --git a/frontend/src/store/modules/table.ts b/frontend/src/store/modules/table.ts
index 7067ed581c..459eb2bbb8 100644
--- a/frontend/src/store/modules/table.ts
+++ b/frontend/src/store/modules/table.ts
@@ -7,6 +7,7 @@ import {
ResourceIdentifier,
ResourceObject,
Table,
+ TableId,
TableIndex,
TableState,
unknown,
@@ -71,6 +72,15 @@ export const useTableStore = defineStore("table", {
return this.tableListByDatabaseId.get(databaseId) || [];
},
+ getTableByDatabaseIdAndTableId(
+ databaseId: DatabaseId,
+ tableId: TableId
+ ): Table {
+ const list = this.getTableListByDatabaseId(databaseId);
+ const table = list.find((t) => t.id === tableId);
+ return table || unknown("TABLE");
+ },
+
setTableByDatabaseIdAndTableName({
databaseId,
tableName,
diff --git a/frontend/src/types/common.ts b/frontend/src/types/common.ts
index fd167bc3fd..c25a0f94b7 100644
--- a/frontend/src/types/common.ts
+++ b/frontend/src/types/common.ts
@@ -1,4 +1,3 @@
-import { Policy } from ".";
import { Activity } from "./activity";
import { Anomaly } from "./anomaly";
import { BackupSetting } from "./backup";
@@ -22,9 +21,10 @@ import { ProjectWebhook } from "./projectWebhook";
import { Repository } from "./repository";
import { VCS } from "./vcs";
import { DeploymentConfig } from "./deployment";
-import { DefaultApprovalPolicy } from "./policy";
+import { Policy, DefaultApprovalPolicy } from "./policy";
import { Sheet } from "./sheet";
import { SQLReviewPolicy } from "./sqlReview";
+import { Table } from "./table";
// System bot id
export const SYSTEM_BOT_ID = 1;
@@ -135,7 +135,8 @@ export type ResourceType =
| "ANOMALY"
| "DEPLOYMENT_CONFIG"
| "SHEET"
- | "SQL_REVIEW";
+ | "SQL_REVIEW"
+ | "TABLE";
interface ResourceMaker {
(type: "PRINCIPAL"): Principal;
@@ -163,6 +164,7 @@ interface ResourceMaker {
(type: "DEPLOYMENT_CONFIG"): DeploymentConfig;
(type: "SHEET"): Sheet;
(type: "SQL_REVIEW"): SQLReviewPolicy;
+ (type: "TABLE"): Table;
}
const makeUnknown = (type: ResourceType) => {
@@ -514,6 +516,27 @@ const makeUnknown = (type: ResourceType) => {
ruleList: [],
};
+ const UNKNOWN_TABLE: Table = {
+ id: UNKNOWN_ID,
+ database: UNKNOWN_DATABASE,
+ creator: UNKNOWN_PRINCIPAL,
+ updater: UNKNOWN_PRINCIPAL,
+ createdTs: 0,
+ updatedTs: 0,
+ name: "<<Unknown table>>",
+ type: "BASE TABLE",
+ engine: "InnoDB",
+ collation: "",
+ rowCount: 0,
+ dataSize: 0,
+ indexList: [],
+ indexSize: 0,
+ dataFree: 0,
+ createOptions: "",
+ comment: "",
+ columnList: [],
+ };
+
switch (type) {
case "PRINCIPAL":
return UNKNOWN_PRINCIPAL;
@@ -565,6 +588,8 @@ const makeUnknown = (type: ResourceType) => {
return UNKNOWN_SHEET;
case "SQL_REVIEW":
return UNKNOWN_SQL_REVIEW_POLICY;
+ case "TABLE":
+ return UNKNOWN_TABLE;
}
};
export const unknown = makeUnknown as ResourceMaker;
@@ -916,6 +941,27 @@ const makeEmpty = (type: ResourceType) => {
ruleList: [],
};
+ const EMPTY_TABLE: Table = {
+ id: EMPTY_ID,
+ database: EMPTY_DATABASE,
+ creator: EMPTY_PRINCIPAL,
+ updater: EMPTY_PRINCIPAL,
+ createdTs: 0,
+ updatedTs: 0,
+ name: "",
+ type: "BASE TABLE",
+ engine: "InnoDB",
+ collation: "",
+ rowCount: 0,
+ dataSize: 0,
+ indexList: [],
+ indexSize: 0,
+ dataFree: 0,
+ createOptions: "",
+ comment: "",
+ columnList: [],
+ };
+
switch (type) {
case "PRINCIPAL":
return EMPTY_PRINCIPAL;
@@ -967,6 +1013,8 @@ const makeEmpty = (type: ResourceType) => {
return EMPTY_SHEET;
case "SQL_REVIEW":
return EMPTY_SQL_REVIEW_POLICY;
+ case "TABLE":
+ return EMPTY_TABLE;
}
};
export const empty = makeEmpty as ResourceMaker;
diff --git a/frontend/src/types/sqlEditor.ts b/frontend/src/types/sqlEditor.ts
index 94026a2be5..c29f694fe3 100644
--- a/frontend/src/types/sqlEditor.ts
+++ b/frontend/src/types/sqlEditor.ts
@@ -1,14 +1,5 @@
import type * as monaco from "monaco-editor";
-import { DropdownOption } from "naive-ui";
-
-import {
- ProjectId,
- InstanceId,
- DatabaseId,
- TableId,
- ViewId,
- ActivityId,
-} from "../types";
+import { InstanceId, DatabaseId, TableId, ViewId, ActivityId } from "../types";
import { Principal } from "./principal";
export type EditorModel = monaco.editor.ITextModel;
@@ -35,21 +26,11 @@ export enum SortText {
KEYWORD = "3",
}
-// TODO(Steven): ConnectionContext should be refactored later,
-// because it has some extra not required fields: instanceName, databaseName...
+// TODO(Jim): Move `isLoadingTree` to the root of sql editor state.
+// refactor <TableSchema> to get rid of this structure totally.
export type ConnectionContext = {
- hasSlug: boolean;
- projectId: ProjectId;
- projectName: string;
- instanceId: InstanceId;
- instanceName: string;
- databaseId: DatabaseId;
- databaseName: string;
- databaseType: string;
- tableId?: TableId;
- tableName?: string;
isLoadingTree: boolean;
- option: DropdownOption;
+ option: ConnectionAtom;
};
export interface QueryHistory {
diff --git a/frontend/src/types/tab.ts b/frontend/src/types/tab.ts
index 6dbf0069ab..07a1d405cd 100644
--- a/frontend/src/types/tab.ts
+++ b/frontend/src/types/tab.ts
@@ -1,4 +1,11 @@
-import { Advice, SheetId } from "../types";
+import {
+ Advice,
+ DatabaseId,
+ InstanceId,
+ ProjectId,
+ SheetId,
+ TableId,
+} from "../types";
export type ExecuteConfig = {
databaseType: string;
@@ -8,9 +15,17 @@ export type ExecuteOption = {
explain: boolean;
};
+export type Connection = {
+ projectId: ProjectId;
+ instanceId: InstanceId;
+ databaseId: DatabaseId;
+ tableId: TableId;
+};
+
export interface TabInfo {
id: string;
name: string;
+ connection: Connection;
isSaved: boolean;
savedAt: string;
statement: string;
diff --git a/frontend/src/utils/index.ts b/frontend/src/utils/index.ts
index 358abda31e..96454b43b4 100644
--- a/frontend/src/utils/index.ts
+++ b/frontend/src/utils/index.ts
@@ -13,6 +13,7 @@ export * from "./types";
export * from "./util";
export * from "./label";
export * from "./deployment";
+export * from "./tab";
export * from "./task";
export * from "./principal";
export * from "./sql-editor";
diff --git a/frontend/src/utils/tab.ts b/frontend/src/utils/tab.ts
index 13d15bb520..fbdd719994 100644
--- a/frontend/src/utils/tab.ts
+++ b/frontend/src/utils/tab.ts
@@ -2,16 +2,29 @@ import dayjs from "dayjs";
import { computed } from "vue";
import { v1 as uuidv1 } from "uuid";
import { t } from "../plugins/i18n";
+import { Connection, DEFAULT_PROJECT_ID, TabInfo, UNKNOWN_ID } from "@/types";
export const defaultTabName = computed(() => t("sql-editor.untitled-sheet"));
-export const getDefaultTab = () => {
+export const emptyConnection = (): Connection => {
+ return {
+ projectId: DEFAULT_PROJECT_ID,
+ instanceId: UNKNOWN_ID,
+ databaseId: UNKNOWN_ID,
+ tableId: UNKNOWN_ID,
+ };
+};
+
+export const getDefaultTab = (): TabInfo => {
return {
id: uuidv1(),
name: defaultTabName.value,
+ connection: emptyConnection(),
isSaved: true,
savedAt: dayjs().format("YYYY-MM-DD HH:mm:ss"),
statement: "",
selectedStatement: "",
};
};
+
+export const INITIAL_TAB = getDefaultTab();
diff --git a/frontend/src/views/sql-editor/AsidePanel/AsidePanel.vue b/frontend/src/views/sql-editor/AsidePanel/AsidePanel.vue
index f2a4333ca8..e42bbc97a5 100644
--- a/frontend/src/views/sql-editor/AsidePanel/AsidePanel.vue
+++ b/frontend/src/views/sql-editor/AsidePanel/AsidePanel.vue
@@ -53,6 +53,8 @@ watch(
(option) => {
if (option && option.type === "table") {
databasePaneSize.value = DATABASE_PANE_SIZE;
+ } else {
+ databasePaneSize.value = FULL_HEIGHT;
}
}
);
diff --git a/frontend/src/views/sql-editor/AsidePanel/DatabaseTree.vue b/frontend/src/views/sql-editor/AsidePanel/DatabaseTree.vue
index 276305af26..af76574c2d 100644
--- a/frontend/src/views/sql-editor/AsidePanel/DatabaseTree.vue
+++ b/frontend/src/views/sql-editor/AsidePanel/DatabaseTree.vue
@@ -16,6 +16,7 @@
<div class="databases-tree--tree overflow-y-scroll">
<n-tree
block-line
+ expand-on-click
:data="treeData"
:pattern="searchPattern"
:default-expanded-keys="defaultExpandedKeys"
@@ -43,26 +44,23 @@
</template>
<script lang="ts" setup>
-import { cloneDeep, omit, escape } from "lodash-es";
-import { TreeOption, DropdownOption } from "naive-ui";
+import { escape } from "lodash-es";
+import { DropdownOption } from "naive-ui";
import { ref, computed, h, nextTick, onMounted, watch } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
-import {
- ConnectionAtom,
- ConnectionContext,
- Database,
- UNKNOWN_ID,
-} from "@/types";
+import { ConnectionAtom, UNKNOWN_ID } from "@/types";
import {
useDatabaseStore,
useInstanceStore,
useSQLEditorStore,
useTableStore,
+ useTabStore,
} from "@/store";
import {
connectionSlug,
+ emptyConnection,
getHighlightHTMLByKeyWords,
mapConnectionAtom,
} from "@/utils";
@@ -74,11 +72,17 @@ type Position = {
y: number;
};
+type DropdownOptionWithConnectionAtom = DropdownOption & {
+ item: ConnectionAtom;
+};
+
const { t } = useI18n();
const router = useRouter();
const instanceStore = useInstanceStore();
+const databaseStore = useDatabaseStore();
const sqlEditorStore = useSQLEditorStore();
+const tabStore = useTabStore();
const defaultExpandedKeys = ref<string[]>([]);
const searchPattern = ref();
@@ -88,27 +92,29 @@ const dropdownPosition = ref<Position>({
y: 0,
});
const selectedKeys = ref<string[] | number[]>([]);
-const sheetContext = ref<DropdownOption>();
+const dropdownContext = ref<ConnectionAtom>();
onMounted(() => {
- const ctx = sqlEditorStore.connectionContext;
- if (ctx.hasSlug) {
- defaultExpandedKeys.value = [
- `instance-${ctx.instanceId}`,
- `database-${ctx.databaseId}`,
- ];
+ const { instanceId, databaseId } = tabStore.currentTab.connection;
+ const keys: string[] = [];
+ if (instanceId !== UNKNOWN_ID) {
+ keys.push(`instance-${instanceId}`);
+ }
+ if (databaseId !== UNKNOWN_ID) {
+ keys.push(`database-${databaseId}`);
}
+ defaultExpandedKeys.value = keys;
});
-const dropdownOptions = computed(() => {
- if (!sheetContext.value) {
+const dropdownOptions = computed((): DropdownOptionWithConnectionAtom[] => {
+ if (!dropdownContext.value) {
return [];
- } else if (sheetContext.value.type === "table") {
+ } else if (dropdownContext.value.type === "table") {
return [
{
key: "alter-table",
label: t("sql-editor.alter-table"),
- item: sheetContext.value,
+ item: dropdownContext.value,
},
];
} else {
@@ -116,7 +122,7 @@ const dropdownOptions = computed(() => {
{
key: "open-connection",
label: t("sql-editor.open-connection"),
- item: sheetContext.value,
+ item: dropdownContext.value,
},
];
}
@@ -138,96 +144,36 @@ watch(
{ immediate: true }
);
-const getFlattenConnectionTree = () => {
- const tree = sqlEditorStore.connectionTree;
- if (!tree) {
- return {};
- }
-
- const instanceList = tree
- .filter((node) => node.type === "instance")
- .map((item) => omit(item, "children"));
-
- const allDatabaseList = tree.flatMap((node) => {
- if (node.children && node.children.length > 0) {
- return node.children.filter((node) => node.type === "database");
- }
- }) as ConnectionAtom[];
-
- const databaseList = allDatabaseList.map((item) => omit(item, "children"));
-
- const tableList = allDatabaseList
- .filter((item) => item.children && item.children.length > 0)
- .flatMap((db: ConnectionAtom) => {
- if (db.children) {
- return db.children.filter((node) => node.type === "table");
- }
- });
-
- return {
- instanceList,
- databaseList,
- tableList,
- };
-};
-
-const setSheetContext = (option: any) => {
+const setConnection = (option: ConnectionAtom) => {
if (option) {
- const ctx = cloneDeep(
- sqlEditorStore.connectionContext
- ) as ConnectionContext;
- const { instanceList, databaseList } = getFlattenConnectionTree();
-
- const getInstanceNameByInstanceId = (id: number) => {
- const instance = instanceList?.find((item) => item.id === id);
- return instance ? instance.label : "";
- };
- const getInstanceEngineByInstanceId = (id: number) => {
- const selectedInstance = instanceStore.getInstanceById(id);
- return selectedInstance ? selectedInstance.engine : "MYSQL";
- };
+ const conn = emptyConnection();
// If selected item is instance node
if (option.type === "instance") {
- ctx.instanceId = option.id;
- ctx.instanceName = option.label;
- ctx.databaseId = UNKNOWN_ID;
- ctx.databaseName = "";
- ctx.databaseType = getInstanceEngineByInstanceId(option.id);
- ctx.tableId = UNKNOWN_ID;
- ctx.tableName = "";
+ conn.instanceId = option.id;
} else if (option.type === "database") {
// If selected item is database node
const instanceId = option.parentId;
- ctx.instanceId = instanceId;
- ctx.instanceName = getInstanceNameByInstanceId(instanceId);
- ctx.databaseId = option.id;
- ctx.databaseName = option.label;
- ctx.databaseType = getInstanceEngineByInstanceId(instanceId);
- ctx.tableId = UNKNOWN_ID;
- ctx.tableName = "";
+ conn.instanceId = instanceId;
+ conn.databaseId = option.id;
} else if (option.type === "table") {
// If selected item is table node
const databaseId = option.parentId;
- const databaseInfo = databaseList?.find((item) => item.id === databaseId);
- const databaseName = databaseInfo?.label || "";
- const instanceId = databaseInfo?.parentId || UNKNOWN_ID;
- ctx.instanceId = instanceId;
- ctx.instanceName = getInstanceNameByInstanceId(instanceId);
- ctx.databaseId = databaseId;
- ctx.databaseName = databaseName;
- ctx.databaseType = getInstanceEngineByInstanceId(instanceId);
- ctx.tableId = option.id;
- ctx.tableName = option.label;
+ const databaseInfo = databaseStore.getDatabaseById(databaseId);
+ const instanceId = databaseInfo.instance.id;
+ conn.instanceId = instanceId;
+ conn.databaseId = databaseId;
+ conn.tableId = option.id;
}
- ctx.hasSlug = true;
- sqlEditorStore.setConnectionContext(ctx);
+ tabStore.updateCurrentTab({
+ connection: conn,
+ });
- if (ctx.instanceId !== UNKNOWN_ID && ctx.databaseId !== UNKNOWN_ID) {
+ if (conn.instanceId !== UNKNOWN_ID && conn.databaseId !== UNKNOWN_ID) {
const database = useDatabaseStore().getDatabaseById(
- ctx.databaseId,
- ctx.instanceId
+ conn.databaseId,
+ conn.instanceId
);
router.replace({
name: "sql-editor.detail",
@@ -236,11 +182,17 @@ const setSheetContext = (option: any) => {
},
});
}
+
+ // TODO(Jim): This part is for <TableSchema> only
+ // and should be removed after upcoming refactor.
+ sqlEditorStore.setConnectionContext({
+ option,
+ });
}
};
// dynamic render the highlight keywords
-const renderLabel = ({ option }: { option: TreeOption }) => {
+const renderLabel = ({ option }: { option: ConnectionAtom }) => {
const renderLabelHTML = searchPattern.value
? h("span", {
innerHTML: getHighlightHTMLByKeyWords(
@@ -255,12 +207,12 @@ const renderLabel = ({ option }: { option: TreeOption }) => {
};
// render the suffix icon
-const renderSuffix = ({ option }: { option: TreeOption }) => {
+const renderSuffix = ({ option }: { option: ConnectionAtom }) => {
const renderSuffixHTML = h(OpenConnectionIcon, {
id: "tree-node-suffix",
class: "n-tree-node-content__suffix-icon",
onClick: function () {
- setSheetContext(option);
+ setConnection(option);
},
});
@@ -277,19 +229,13 @@ const loadSubTree = async (item: ConnectionAtom) => {
}
};
-const gotoAlterSchema = (option: any) => {
+const gotoAlterSchema = (option: ConnectionAtom) => {
const databaseId = option.parentId;
- const projectId = sqlEditorStore.findProjectIdByDatabaseId(databaseId);
- const databaseList =
- sqlEditorStore.connectionInfo.databaseListByProjectId.get(projectId);
- const database = databaseList?.find(
- (database: Database) => database.id === databaseId
- );
- if (!database) {
+ const database = databaseStore.getDatabaseById(databaseId);
+ if (database.id === UNKNOWN_ID) {
return;
}
- const databaseName = database.name;
router.push({
name: "workspace.issue.detail",
params: {
@@ -297,8 +243,8 @@ const gotoAlterSchema = (option: any) => {
},
query: {
template: "bb.issue.database.schema.update",
- name: `[${databaseName}] Alter schema`,
- project: projectId,
+ name: `[${database.name}] Alter schema`,
+ project: database.project.id,
databaseList: databaseId,
sql: `ALTER TABLE ${option.label}`,
},
@@ -306,14 +252,15 @@ const gotoAlterSchema = (option: any) => {
};
const handleSelect = (key: string) => {
- const option = dropdownOptions.value.find(
- (item) => item.key === key
- ) as DropdownOption;
+ const option = dropdownOptions.value.find((item) => item.key === key);
+ if (!option) {
+ return;
+ }
if (key === "alter-table") {
gotoAlterSchema(option.item);
} else if (key === "open-connection") {
- setSheetContext(option.item);
+ setConnection(option.item);
}
showDropdown.value = false;
@@ -323,25 +270,25 @@ const handleClickoutside = () => {
showDropdown.value = false;
};
-const nodeProps = (info: { option: TreeOption }) => {
+const nodeProps = (info: { option: ConnectionAtom }) => {
const { option } = info;
return {
onClick(e: MouseEvent) {
+ // TODO(Jim): This part is for <TableSchema> only
+ // and should be removed after upcoming refactor.
const targetEl = e.target as HTMLElement;
if (option && targetEl.className === "n-tree-node-content__text") {
- const ctx = cloneDeep(
- sqlEditorStore.connectionContext
- ) as ConnectionContext;
- ctx.option = option;
- sqlEditorStore.setConnectionContext(ctx);
+ sqlEditorStore.setConnectionContext({
+ option,
+ });
}
},
onContextmenu(e: MouseEvent) {
e.preventDefault();
showDropdown.value = false;
if (option && option.key) {
- sheetContext.value = option;
+ dropdownContext.value = option;
selectedKeys.value = [option.key as string];
}
diff --git a/frontend/src/views/sql-editor/AsidePanel/TableSchema.vue b/frontend/src/views/sql-editor/AsidePanel/TableSchema.vue
index b44219e153..48ad2dbd8f 100644
--- a/frontend/src/views/sql-editor/AsidePanel/TableSchema.vue
+++ b/frontend/src/views/sql-editor/AsidePanel/TableSchema.vue
@@ -67,7 +67,7 @@
import { ref, watch } from "vue";
import { useRouter } from "vue-router";
-import { Database, DatabaseId, UNKNOWN_ID } from "@/types";
+import { Database } from "@/types";
import { useSQLEditorStore, useTableStore } from "@/store";
const emit = defineEmits<{
@@ -78,15 +78,17 @@ const tableStore = useTableStore();
const sqlEditorStore = useSQLEditorStore();
const tableInfo = ref();
-const ctx = sqlEditorStore.connectionContext;
const router = useRouter();
const gotoAlterSchema = () => {
- let databaseId = ctx.databaseId as DatabaseId;
- if (databaseId === UNKNOWN_ID) {
- const option = ctx.option;
- databaseId = option.parentId as number;
+ // TODO(Jim): Remove the dependency of `sqlEditorStore.connectionContext.option`
+ // after refactoring <DatabaseTree>
+ const { option } = sqlEditorStore.connectionContext;
+ if (option.type !== "table") {
+ return;
}
+ const tableName = option.label;
+ const databaseId = option.parentId;
const projectId = sqlEditorStore.findProjectIdByDatabaseId(databaseId);
const databaseList =
@@ -104,7 +106,7 @@ const gotoAlterSchema = () => {
name: `[${databaseName}] Alter schema`,
project: projectId,
databaseList: databaseId,
- sql: `ALTER TABLE ${ctx.tableName}`,
+ sql: `ALTER TABLE ${tableName}`,
},
});
};
diff --git a/frontend/src/views/sql-editor/EditorPanel/EditorAction.vue b/frontend/src/views/sql-editor/EditorPanel/EditorAction.vue
index 0b0bf8d6c0..0528f9caaa 100644
--- a/frontend/src/views/sql-editor/EditorPanel/EditorAction.vue
+++ b/frontend/src/views/sql-editor/EditorPanel/EditorAction.vue
@@ -23,9 +23,7 @@
</div>
<div class="action-right space-x-2 flex justify-end items-center">
<NPopover
- v-if="
- connectionContext.instanceId !== UNKNOWN_ID && !hasReadonlyDataSource
- "
+ v-if="selectedInstance.id !== UNKNOWN_ID && !hasReadonlyDataSource"
trigger="hover"
>
<template #trigger>
@@ -44,45 +42,54 @@
</NButton>
</p>
</NPopover>
+
<NPopover trigger="hover" placement="bottom-center" :show-arrow="false">
<template #trigger>
<label class="flex items-center text-sm space-x-1">
- <div class="flex items-center">
- <InstanceEngineIcon
- v-if="connectionContext.instanceId !== UNKNOWN_ID"
- :instance="selectedInstance"
- show-status
- />
- <span class="ml-2">{{ connectionContext.instanceName }}</span>
+ <div
+ v-if="selectedInstance.id !== UNKNOWN_ID"
+ class="flex items-center"
+ >
+ <InstanceEngineIcon :instance="selectedInstance" show-status />
+ <span class="ml-2">{{ selectedInstance.name }}</span>
</div>
<div
- v-if="connectionContext.databaseName"
+ v-if="selectedDatabase.id !== UNKNOWN_ID"
class="flex items-center"
>
&nbsp; / &nbsp;
<heroicons-outline:database />
- <span class="ml-2">{{ connectionContext.databaseName }}</span>
+ <span class="ml-2">{{ selectedDatabase.name }}</span>
</div>
- <div v-if="connectionContext.tableName" class="flex items-center">
+ <div
+ v-if="selectedTable.id !== UNKNOWN_ID"
+ class="flex items-center"
+ >
&nbsp; / &nbsp;
<heroicons-outline:table />
- <span class="ml-2">{{ connectionContext.tableName }}</span>
+ <span class="ml-2">{{ selectedTable.name }}</span>
</div>
</label>
</template>
<section>
<div class="space-y-2">
- <div v-if="connectionContext.instanceName" class="flex flex-col">
+ <div
+ v-if="selectedInstance.id !== UNKNOWN_ID"
+ class="flex flex-col"
+ >
<h1 class="text-gray-400">{{ $t("common.instance") }}:</h1>
- <span>{{ connectionContext.instanceName }}</span>
+ <span>{{ selectedInstance.name }}</span>
</div>
- <div v-if="connectionContext.databaseName" class="flex flex-col">
+ <div
+ v-if="selectedDatabase.id !== UNKNOWN_ID"
+ class="flex flex-col"
+ >
<h1 class="text-gray-400">{{ $t("common.database") }}:</h1>
- <span>{{ connectionContext.databaseName }}</span>
+ <span>{{ selectedDatabase.name }}</span>
</div>
- <div v-if="connectionContext.tableName" class="flex flex-col">
+ <div v-if="selectedTable.id !== UNKNOWN_ID" class="flex flex-col">
<h1 class="text-gray-400">{{ $t("common.table") }}:</h1>
- <span>{{ connectionContext.tableName }}</span>
+ <span>{{ selectedTable.name }}</span>
</div>
</div>
</section>
@@ -101,7 +108,7 @@
<NButton
:disabled="
isEmptyStatement ||
- sqlEditorStore.isDisconnected ||
+ tabStore.isDisconnected ||
!tabStore.currentTab.isSaved
"
>
@@ -120,8 +127,15 @@
import { computed, defineEmits } from "vue";
import { useRouter } from "vue-router";
import { useExecuteSQL } from "@/composables/useExecuteSQL";
-import { useInstanceStore, useTabStore, useSQLEditorStore } from "@/store";
-import { UNKNOWN_ID, Instance } from "@/types";
+import {
+ useInstanceStore,
+ useTabStore,
+ useSQLEditorStore,
+ useInstanceById,
+ useDatabaseById,
+ useTableStore,
+} from "@/store";
+import { UNKNOWN_ID } from "@/types";
import { instanceSlug } from "@/utils/slug";
import SharePopover from "./SharePopover.vue";
@@ -133,19 +147,26 @@ const router = useRouter();
const instanceStore = useInstanceStore();
const tabStore = useTabStore();
const sqlEditorStore = useSQLEditorStore();
+const tableStore = useTableStore();
-const connectionContext = computed(() => sqlEditorStore.connectionContext);
+const connection = computed(() => tabStore.currentTab.connection);
const isEmptyStatement = computed(
() => !tabStore.currentTab || tabStore.currentTab.statement === ""
);
-const selectedInstance = computed<Instance>(() => {
- const ctx = sqlEditorStore.connectionContext;
- return instanceStore.getInstanceById(ctx.instanceId);
-});
+const selectedInstance = useInstanceById(
+ computed(() => connection.value.instanceId)
+);
const selectedInstanceEngine = computed(() => {
return instanceStore.formatEngine(selectedInstance.value);
});
+const selectedDatabase = useDatabaseById(
+ computed(() => connection.value.databaseId)
+);
+const selectedTable = computed(() => {
+ const { databaseId, tableId } = connection.value;
+ return tableStore.getTableByDatabaseIdAndTableId(databaseId, tableId);
+});
const hasReadonlyDataSource = computed(() => {
for (const ds of selectedInstance.value.dataSourceList) {
diff --git a/frontend/src/views/sql-editor/EditorPanel/EditorPanel.vue b/frontend/src/views/sql-editor/EditorPanel/EditorPanel.vue
index 3136164db1..a1220cd0d2 100644
--- a/frontend/src/views/sql-editor/EditorPanel/EditorPanel.vue
+++ b/frontend/src/views/sql-editor/EditorPanel/EditorPanel.vue
@@ -9,7 +9,7 @@
{{ $t("sql-editor.sql-execute-in-protected-environment") }}
</div>
- <template v-if="!sqlEditorStore.isDisconnected">
+ <template v-if="!tabStore.isDisconnected">
<SQLEditor @save-sheet="handleSaveSheet" />
</template>
<template v-else>
@@ -57,7 +57,7 @@ const instanceStore = useInstanceStore();
const isShowSaveSheetModal = ref(false);
const isProtectedEnvironment = computed(() => {
- const { instanceId } = sqlEditorStore.connectionContext;
+ const { instanceId } = tabStore.currentTab.connection;
const instance = instanceStore.getInstanceById(instanceId);
return instance.environment.tier === "PROTECTED";
});
@@ -78,11 +78,11 @@ const handleSaveSheet = async (sheetName?: string) => {
const { name, statement, sheetId } = tabStore.currentTab;
sheetName = sheetName ? sheetName : name;
- const ctx = sqlEditorStore.connectionContext;
+ const conn = tabStore.currentTab.connection;
const sheetUpsert = {
id: sheetId,
- projectId: ctx.projectId,
- databaseId: ctx.databaseId,
+ projectId: conn.projectId,
+ databaseId: conn.databaseId,
name: sheetName,
statement: statement,
};
diff --git a/frontend/src/views/sql-editor/EditorPanel/ExecuteHint.vue b/frontend/src/views/sql-editor/EditorPanel/ExecuteHint.vue
index 119768c569..48d6f96dc9 100644
--- a/frontend/src/views/sql-editor/EditorPanel/ExecuteHint.vue
+++ b/frontend/src/views/sql-editor/EditorPanel/ExecuteHint.vue
@@ -51,24 +51,24 @@
import { computed } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
-
-import { pushNotification, useTabStore, useSQLEditorStore } from "@/store";
-import { UNKNOWN_ID } from "@/types";
-
+import { pushNotification, useTabStore, useDatabaseStore } from "@/store";
import {
parseSQL,
transformSQL,
isDDLStatement,
} from "@/components/MonacoEditor/sqlParser";
+import { UNKNOWN_ID } from "@/types";
const emit = defineEmits<{
(e: "close"): void;
}>();
+const DDLIssueTemplate = "bb.issue.database.schema.update";
+const DMLIssueTemplate = "bb.issue.database.data.update";
+
const router = useRouter();
const { t } = useI18n();
const tabStore = useTabStore();
-const sqlEditorStore = useSQLEditorStore();
const sqlStatement = computed(
() => tabStore.currentTab.selectedStatement || tabStore.currentTab.statement
@@ -86,8 +86,6 @@ const isDDLSQLStatement = computed(() => {
return data !== null ? isDDLStatement(data) : false;
});
-const ctx = computed(() => sqlEditorStore.connectionContext);
-
const docLink =
"https://bytebase.com/docs/concepts/schema-change-workflow#ui-workflow?source=console";
@@ -96,7 +94,8 @@ const handleColse = () => {
};
const gotoAlterSchema = () => {
- if (ctx.value.databaseId === UNKNOWN_ID) {
+ const { databaseId } = tabStore.currentTab.connection;
+ if (databaseId === UNKNOWN_ID) {
pushNotification({
module: "bytebase",
style: "CRITICAL",
@@ -107,11 +106,7 @@ const gotoAlterSchema = () => {
emit("close");
- const projectId = sqlEditorStore.findProjectIdByDatabaseId(
- ctx.value.databaseId as number
- );
- const DDLIssueTemplate = "bb.issue.database.schema.update";
- const DMLIssueTemplate = "bb.issue.database.data.update";
+ const database = useDatabaseStore().getDatabaseById(databaseId);
router.push({
name: "workspace.issue.detail",
@@ -120,11 +115,11 @@ const gotoAlterSchema = () => {
},
query: {
template: isDDLSQLStatement.value ? DDLIssueTemplate : DMLIssueTemplate,
- name: `[${ctx.value.databaseName}] ${
+ name: `[${database.name}] ${
isDDLSQLStatement.value ? "Alter schema" : "Change Data"
}`,
- project: projectId,
- databaseList: ctx.value.databaseId,
+ project: database.project.id,
+ databaseList: databaseId,
sql: getParsedStatement(),
},
});
diff --git a/frontend/src/views/sql-editor/EditorPanel/SQLEditor.vue b/frontend/src/views/sql-editor/EditorPanel/SQLEditor.vue
index 0cd73268e8..d85de74078 100644
--- a/frontend/src/views/sql-editor/EditorPanel/SQLEditor.vue
+++ b/frontend/src/views/sql-editor/EditorPanel/SQLEditor.vue
@@ -27,6 +27,7 @@ import {
useDatabaseStore,
useTableStore,
useSheetStore,
+ useInstanceById,
} from "@/store";
import { useExecuteSQL } from "@/composables/useExecuteSQL";
import MonacoEditor from "@/components/MonacoEditor/MonacoEditor.vue";
@@ -48,10 +49,9 @@ const editorRef = ref<InstanceType<typeof MonacoEditor>>();
const { execute } = useExecuteSQL();
const sqlCode = computed(() => tabStore.currentTab.statement);
-const selectedInstance = computed(() => {
- const ctx = sqlEditorStore.connectionContext;
- return instanceStore.getInstanceById(ctx.instanceId);
-});
+const selectedInstance = useInstanceById(
+ computed(() => tabStore.currentTab.connection.instanceId)
+);
const selectedInstanceEngine = computed(() => {
return instanceStore.formatEngine(selectedInstance.value);
});
diff --git a/frontend/src/views/sql-editor/EditorPanel/SharePopover.vue b/frontend/src/views/sql-editor/EditorPanel/SharePopover.vue
index 305f68d873..dedec69ef3 100644
--- a/frontend/src/views/sql-editor/EditorPanel/SharePopover.vue
+++ b/frontend/src/views/sql-editor/EditorPanel/SharePopover.vue
@@ -91,14 +91,16 @@ import slug from "slug";
import {
pushNotification,
useTabStore,
- useSQLEditorStore,
useSheetStore,
+ useInstanceStore,
+ useDatabaseStore,
} from "@/store";
import { AccessOption } from "@/types";
const { t } = useI18n();
const tabStore = useTabStore();
-const sqlEditorStore = useSQLEditorStore();
+const instanceStore = useInstanceStore();
+const databaseStore = useDatabaseStore();
const sheetStore = useSheetStore();
const accessOptions = computed<AccessOption[]>(() => {
@@ -121,16 +123,20 @@ const accessOptions = computed<AccessOption[]>(() => {
];
});
-const ctx = computed(() => sqlEditorStore.connectionContext);
const sheet = computed(() => sheetStore.currentSheet);
const creator = computed(() => sheetStore.isCreator);
-const connectionSlug = [
- slug(ctx.value.instanceName as string),
- ctx.value.instanceId,
- slug(ctx.value.databaseName as string),
- ctx.value.databaseId,
-].join("_");
+const connectionSlug = computed((): string => {
+ const { instanceId, databaseId } = tabStore.currentTab.connection;
+ const instance = instanceStore.getInstanceById(instanceId);
+ const database = databaseStore.getDatabaseById(databaseId);
+ return [
+ slug(instance.name),
+ instanceId,
+ slug(database.name),
+ databaseId,
+ ].join("_");
+});
const currentAccess = ref<AccessOption>(accessOptions.value[0]);
const isShowAccessPopover = ref(false);
@@ -166,7 +172,7 @@ const sheetSlug = `${slug(tabStore.currentTab.name)}_${
tabStore.currentTab.sheetId
}`;
const sharedTabLink = ref(
- `${window.location.origin}/sql-editor/${connectionSlug}/${sheetSlug}`
+ `${window.location.origin}/sql-editor/${connectionSlug.value}/${sheetSlug}`
);
const { copy, copied } = useClipboard({
diff --git a/frontend/src/views/sql-editor/SQLEditor.vue b/frontend/src/views/sql-editor/SQLEditor.vue
index a36be2045d..7c90bb33f4 100644
--- a/frontend/src/views/sql-editor/SQLEditor.vue
+++ b/frontend/src/views/sql-editor/SQLEditor.vue
@@ -26,7 +26,7 @@
<script lang="ts" setup>
import { computed } from "vue";
-import { useTabStore, useSQLEditorStore } from "@/store";
+import { useTabStore } from "@/store";
import AsidePanel from "./AsidePanel/AsidePanel.vue";
import EditorPanel from "./EditorPanel/EditorPanel.vue";
import TabListContainer from "./TabListContainer.vue";
@@ -36,11 +36,10 @@ import { Splitpanes, Pane } from "splitpanes";
import "splitpanes/dist/splitpanes.css";
const tabStore = useTabStore();
-const sqlEditorStore = useSQLEditorStore();
const hasTabs = computed(() => tabStore.hasTabs);
const paneKey = computed(() => tabStore.currentTab.id);
-const isDisconnected = computed(() => sqlEditorStore.isDisconnected);
+const isDisconnected = computed(() => tabStore.isDisconnected);
</script>
<style>
diff --git a/frontend/src/views/sql-editor/TablePanel/TableView.vue b/frontend/src/views/sql-editor/TablePanel/TableView.vue
index df8e53bf69..29f621fc2b 100644
--- a/frontend/src/views/sql-editor/TablePanel/TableView.vue
+++ b/frontend/src/views/sql-editor/TablePanel/TableView.vue
@@ -68,7 +68,7 @@ import { debouncedRef } from "@vueuse/core";
import { unparse } from "papaparse";
import { isEmpty } from "lodash-es";
import dayjs from "dayjs";
-import { useTabStore, useSQLEditorStore } from "@/store";
+import { useTabStore, useSQLEditorStore, useInstanceStore } from "@/store";
import { createExplainToken } from "@/utils";
import DataTable from "./DataTable.vue";
@@ -78,6 +78,7 @@ interface State {
const { t } = useI18n();
const tabStore = useTabStore();
+const instanceStore = useInstanceStore();
const sqlEditorStore = useSQLEditorStore();
const queryResult = computed(() => tabStore.currentTab.queryResult || null);
@@ -174,7 +175,10 @@ const handleExportBtnClick = (format: "csv" | "json") => {
};
const showVisualizeButton = computed((): boolean => {
- const { databaseType } = sqlEditorStore.connectionContext;
+ const instance = instanceStore.getInstanceById(
+ tabStore.currentTab.connection.instanceId
+ );
+ const databaseType = instance.engine;
const { executeParams } = tabStore.currentTab;
return databaseType === "POSTGRES" && !!executeParams?.option?.explain;
});