Skip to content

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

refactor: connect to the database (#18386)

ecmadao8390536374cb
diff --git a/frontend/src/store/modules/sqlEditor/tab.ts b/frontend/src/store/modules/sqlEditor/tab.ts
index 9c1d9e30c6..ac77532a2c 100644
--- a/frontend/src/store/modules/sqlEditor/tab.ts
+++ b/frontend/src/store/modules/sqlEditor/tab.ts
@@ -124,6 +124,9 @@ export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {
if (!fullTab) {
continue;
}
+ if (!fullTab.mode) {
+ fullTab.mode = "WORKSHEET";
+ }
validOpenTabMap.set(tab.id, tab);
tabsById.set(tab.id, fullTab);
@@ -394,6 +397,13 @@ export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {
currentTabId.value = id;
};
+ // TODO(ed): deprecate
+ // The similar tab should not consider the worksheet
+ // What we should do:
+ // When load the SQL Editor page in the URL like /instances/{instance}/databases/{database},
+ // get the connection, check if exist opening tab with the same connection
+ // - exist: set the current tab id
+ // - not exist: we still have to provide a draft worksheet, but the draft can only exist in the memory, not in the local storage
const selectOrAddSimilarNewTab = (
tab: CoreSQLEditorTab,
beside = false,
diff --git a/frontend/src/utils/sqlEditor.ts b/frontend/src/utils/sqlEditor.ts
index 118f015a5e..e7753bc355 100644
--- a/frontend/src/utils/sqlEditor.ts
+++ b/frontend/src/utils/sqlEditor.ts
@@ -1,11 +1,7 @@
import dayjs from "dayjs";
import { head } from "lodash-es";
import { v1 as uuidv1 } from "uuid";
-import {
- useDatabaseV1Store,
- usePolicyV1Store,
- useSQLEditorTabStore,
-} from "@/store";
+import { useDatabaseV1Store, usePolicyV1Store } from "@/store";
import type {
ComposedDatabase,
CoreSQLEditorTab,
@@ -54,6 +50,7 @@ export const defaultSQLEditorTab = (): SQLEditorTab => {
export const defaultSQLEditorTabTitle = () => {
return dayjs().format("YYYY-MM-DD HH:mm");
};
+
export const emptySQLEditorConnection = (): SQLEditorConnection => {
return {
instance: "",
@@ -61,7 +58,7 @@ export const emptySQLEditorConnection = (): SQLEditorConnection => {
};
};
-export const connectionForSQLEditorTab = (tab: SQLEditorTab) => {
+export const getConnectionForSQLEditorTab = (tab: SQLEditorTab) => {
const target: {
instance: InstanceResource | undefined;
database: ComposedDatabase | undefined;
@@ -98,11 +95,6 @@ export const isSimilarSQLEditorTab = (
return true;
};
-export const isSimilarToDefaultSQLEditorTabTitle = (title: string) => {
- const regex = /(^|\s)(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2})$/;
- return regex.test(title);
-};
-
export const suggestedTabTitleForSQLEditorConnection = (
conn: SQLEditorConnection
) => {
@@ -118,7 +110,7 @@ export const suggestedTabTitleForSQLEditorConnection = (
};
export const isConnectedSQLEditorTab = (tab: SQLEditorTab) => {
- const { instance, database } = connectionForSQLEditorTab(tab);
+ const { instance, database } = getConnectionForSQLEditorTab(tab);
if (!instance) {
return false;
}
@@ -133,45 +125,6 @@ export const isConnectedSQLEditorTab = (tab: SQLEditorTab) => {
return database && isValidDatabaseName(database.name);
};
-export const tryConnectToCoreSQLEditorTab = (
- tab: CoreSQLEditorTab,
- overrideTitle = true,
- newTab = false
-) => {
- const tabStore = useSQLEditorTabStore();
- if (newTab) {
- tabStore.addTab({}, true);
- }
-
- const currentTab = tabStore.currentTab;
- if (currentTab) {
- if (isSimilarSQLEditorTab(tab, currentTab)) {
- // Don't go further if the connection doesn't change.
- return;
- }
- tabStore.updateCurrentTab(tab);
- if (
- overrideTitle &&
- isSimilarToDefaultSQLEditorTabTitle(currentTab.title)
- ) {
- const title = suggestedTabTitleForSQLEditorConnection(tab.connection);
- tabStore.updateCurrentTab({
- title,
- });
- }
- return;
- }
-
- // Otherwise select or add a new tab and set its connection.
- const title = suggestedTabTitleForSQLEditorConnection(tab.connection);
- tabStore.selectOrAddSimilarNewTab(
- tab,
- false /* beside */,
- title /* defaultTabTitle */
- );
- tabStore.updateCurrentTab(tab);
-};
-
export const getAdminDataSourceRestrictionOfDatabase = (
database: ComposedDatabase
) => {
diff --git a/frontend/src/views/sql-editor/AsidePanel/WorksheetPane/SheetList/SheetTree.vue b/frontend/src/views/sql-editor/AsidePanel/WorksheetPane/SheetList/SheetTree.vue
index 65df811a26..e69cf71365 100644
--- a/frontend/src/views/sql-editor/AsidePanel/WorksheetPane/SheetList/SheetTree.vue
+++ b/frontend/src/views/sql-editor/AsidePanel/WorksheetPane/SheetList/SheetTree.vue
@@ -375,7 +375,10 @@ const nodeProps = ({ option }: { option: TreeOption }) => {
}
if (node.worksheet) {
if (node.worksheet.type === "worksheet") {
- openWorksheetByName(node.worksheet.name, e.metaKey || e.ctrlKey);
+ openWorksheetByName({
+ worksheet: node.worksheet.name,
+ forceNewTab: e.metaKey || e.ctrlKey,
+ });
} else {
const tab = tabStore.draftList.find(
(draft) => draft.id === node.worksheet?.name
diff --git a/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/ConnectionPane.vue b/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/ConnectionPane.vue
index 6d6b5113bc..9cf49c2519 100644
--- a/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/ConnectionPane.vue
+++ b/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/ConnectionPane.vue
@@ -217,12 +217,10 @@ import {
import { instanceNamePrefix } from "@/store/modules/v1/common";
import type {
ComposedDatabase,
- CoreSQLEditorTab,
QueryDataSourceType,
SQLEditorTreeNode,
} from "@/types";
import {
- DEFAULT_SQL_EDITOR_TAB_MODE,
getDataSourceTypeI18n,
isValidDatabaseGroupName,
isValidDatabaseName,
@@ -243,7 +241,6 @@ import {
getValuesFromSearchParams,
isDatabaseV1Queryable,
isDescendantOf,
- tryConnectToCoreSQLEditorTab,
useDynamicLocalStorage,
} from "@/utils";
import { useSQLEditorContext } from "../../context";
@@ -391,16 +388,10 @@ watch(
selectedDatabases.length > 0
) {
const database = databaseStore.getDatabaseByName(selectedDatabases[0]);
- const coreTab: CoreSQLEditorTab = {
- connection: {
- ...emptySQLEditorConnection(),
- instance: database.instance,
- database: database.name,
- },
- worksheet: "",
- mode: DEFAULT_SQL_EDITOR_TAB_MODE,
- };
- tryConnectToCoreSQLEditorTab(coreTab);
+ setConnection(database, {
+ newTab: false,
+ context: editorContext,
+ });
}
tabStore.updateBatchQueryContext({
databases: selectedDatabases,
@@ -479,15 +470,20 @@ const connectedDatabases = computed(() =>
resolveOpeningDatabaseListFromSQLEditorTabList()
);
+// The connection panel should:
+// - change the connection for the current tab
+// - connect to a new tab, this will create a new worksheet
const connect = (node: SQLEditorTreeNode) => {
- if (!isDatabaseV1Queryable(node.meta.target as ComposedDatabase)) {
+ if (node.disabled || node.meta.type !== "database") {
return;
}
- setConnection(node, {
- extra: {
- worksheet: tabStore.currentTab?.worksheet ?? "",
- mode: tabStore.currentTab?.mode ?? DEFAULT_SQL_EDITOR_TAB_MODE,
- },
+ const database = node.meta.target as ComposedDatabase;
+ if (!isDatabaseV1Queryable(database)) {
+ return;
+ }
+ setConnection(database, {
+ mode: tabStore.currentTab?.mode,
+ newTab: false,
context: editorContext,
});
if (tabStore.currentTab?.batchQueryContext?.databases.length === 1) {
diff --git a/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/actions.tsx b/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/actions.tsx
index 43a50b6cd5..e44ae23948 100644
--- a/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/actions.tsx
+++ b/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/actions.tsx
@@ -9,13 +9,14 @@ import { computed, ref } from "vue";
import { useRouter } from "vue-router";
import { t } from "@/plugins/i18n";
import { PROJECT_V1_ROUTE_DATABASE_DETAIL } from "@/router/dashboard/projectV1";
+import { useSQLEditorTabStore } from "@/store";
import {
type ComposedDatabase,
- type CoreSQLEditorTab,
DEFAULT_SQL_EDITOR_TAB_MODE,
instanceOfSQLEditorTreeNode,
isConnectableSQLEditorTreeNode,
type Position,
+ type SQLEditorConnection,
type SQLEditorTabMode as TabMode,
type SQLEditorTreeNode as TreeNode,
} from "@/types";
@@ -26,7 +27,7 @@ import {
instanceV1HasAlterSchema,
instanceV1HasReadonlyMode,
setDefaultDataSourceForConn,
- tryConnectToCoreSQLEditorTab,
+ suggestedTabTitleForSQLEditorConnection,
} from "@/utils";
import { type SQLEditorContext, useSQLEditorContext } from "../../context";
@@ -66,6 +67,7 @@ export const useDropdown = () => {
const items: DropdownOptionWithTreeNode[] = [];
if (isConnectableSQLEditorTreeNode(node)) {
+ const database = node.meta.target as ComposedDatabase;
const instance = instanceOfSQLEditorTreeNode(node);
if (instance && instanceV1HasReadonlyMode(instance)) {
items.push({
@@ -73,8 +75,9 @@ export const useDropdown = () => {
label: t("sql-editor.connect"),
icon: () => <LinkIcon class="w-4 h-4" />,
onSelect: () => {
- setConnection(node, {
+ setConnection(database, {
context: editorContext,
+ newTab: false,
});
showConnectionPanel.value = false;
},
@@ -84,8 +87,7 @@ export const useDropdown = () => {
label: t("sql-editor.connect-in-new-tab"),
icon: () => <LinkIcon class="w-4 h-4" />,
onSelect: () => {
- setConnection(node, {
- extra: { worksheet: "", mode: DEFAULT_SQL_EDITOR_TAB_MODE },
+ setConnection(database, {
newTab: true,
context: editorContext,
});
@@ -99,9 +101,10 @@ export const useDropdown = () => {
label: t("sql-editor.connect-in-admin-mode"),
icon: () => <WrenchIcon class="w-4 h-4" />,
onSelect: () => {
- setConnection(node, {
- extra: { worksheet: "", mode: "ADMIN" },
+ setConnection(database, {
+ mode: "ADMIN",
context: editorContext,
+ newTab: false,
});
showConnectionPanel.value = false;
},
@@ -164,41 +167,48 @@ export const useDropdown = () => {
return { show, position, context, options, handleSelect, handleClickoutside };
};
+// setConnection will:
+// - when newTab == false && exist current tab: connect to the current tab
+// - otherwise create a new worksheet then open the tab
export const setConnection = (
- node: TreeNode<"database">,
+ database: ComposedDatabase,
options: {
- extra?: { worksheet: string; mode: TabMode };
- newTab?: boolean;
+ mode?: TabMode;
+ newTab: boolean;
context: SQLEditorContext;
}
) => {
- if (!node) {
- return;
- }
- if (!isConnectableSQLEditorTreeNode(node)) {
- // one more guard
- return;
- }
const {
- extra = {
- worksheet: "",
- mode: DEFAULT_SQL_EDITOR_TAB_MODE,
- },
+ mode = DEFAULT_SQL_EDITOR_TAB_MODE,
newTab = false,
context,
} = options;
- const database = node.meta.target;
- const coreTab: CoreSQLEditorTab = {
- connection: {
- instance: database.instance,
- database: database.name,
- },
- ...extra,
+ const connection: SQLEditorConnection = {
+ instance: database.instance,
+ database: database.name,
};
- setDefaultDataSourceForConn(coreTab.connection, database);
- tryConnectToCoreSQLEditorTab(coreTab, /* overrideTitle */ true, newTab);
+ setDefaultDataSourceForConn(connection, database);
- if (context) {
+ const tabStore = useSQLEditorTabStore();
+ if (!newTab && tabStore.currentTab) {
+ tabStore.updateCurrentTab({
+ mode,
+ connection,
+ status: "DIRTY",
+ });
context.asidePanelTab.value = "SCHEMA";
+ } else {
+ // create new worksheet and set connection
+ context
+ .createWorksheet({
+ title: suggestedTabTitleForSQLEditorConnection(connection),
+ database: connection.database,
+ })
+ .then((tab) => {
+ if (tab) {
+ tabStore.updateTab(tab.id, { mode });
+ context.asidePanelTab.value = "SCHEMA";
+ }
+ });
}
};
diff --git a/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue b/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue
index c9c0adcf7f..b898ae967f 100644
--- a/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue
@@ -256,9 +256,6 @@ const allowSave = computed(() => {
if (!showSheetsFeature.value) {
return false;
}
- if (isEmptyStatement.value) {
- return false;
- }
const tab = currentTab.value;
if (!tab) {
return false;
@@ -276,9 +273,6 @@ const allowSave = computed(() => {
if (tab.status === "CLEAN") {
return false;
}
- if (!tab.connection.database) {
- return false;
- }
return true;
});
diff --git a/frontend/src/views/sql-editor/EditorCommon/SheetConnectionIcon.vue b/frontend/src/views/sql-editor/EditorCommon/SheetConnectionIcon.vue
index bcfd3b4912..fb2ed4a756 100644
--- a/frontend/src/views/sql-editor/EditorCommon/SheetConnectionIcon.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/SheetConnectionIcon.vue
@@ -8,7 +8,7 @@ import { UnlinkIcon } from "lucide-vue-next";
import { computed } from "vue";
import { EngineIcon } from "@/components/Icon";
import { type SQLEditorTab } from "@/types";
-import { connectionForSQLEditorTab, isConnectedSQLEditorTab } from "@/utils";
+import { getConnectionForSQLEditorTab, isConnectedSQLEditorTab } from "@/utils";
const props = defineProps<{
tab: SQLEditorTab;
@@ -16,5 +16,7 @@ const props = defineProps<{
const connected = computed(() => isConnectedSQLEditorTab(props.tab));
-const instance = computed(() => connectionForSQLEditorTab(props.tab).instance);
+const instance = computed(
+ () => getConnectionForSQLEditorTab(props.tab).instance
+);
</script>
diff --git a/frontend/src/views/sql-editor/Sheet/context.ts b/frontend/src/views/sql-editor/Sheet/context.ts
index f5312a2ca0..85a386aa68 100644
--- a/frontend/src/views/sql-editor/Sheet/context.ts
+++ b/frontend/src/views/sql-editor/Sheet/context.ts
@@ -14,18 +14,16 @@ import {
useSQLEditorTabStore,
useWorkSheetStore,
} from "@/store";
-import type { SQLEditorTab } from "@/types";
+import type { SQLEditorTab, SQLEditorTabMode } from "@/types";
import { DEBOUNCE_SEARCH_DELAY } from "@/types";
import {
type Worksheet,
Worksheet_Visibility,
} from "@/types/proto-es/v1/worksheet_service_pb";
import {
- emptySQLEditorConnection,
extractWorksheetConnection,
getSheetStatement,
isWorksheetReadableV1,
- suggestedTabTitleForSQLEditorConnection,
useDynamicLocalStorage,
} from "@/utils";
import { useFolderByView } from "./folder";
@@ -539,62 +537,53 @@ export const provideSheetContext = () => {
return context;
};
-export const openWorksheetByName = async (
- name: string,
- forceNewTab = false
-) => {
- const worksheet = await useWorkSheetStore().getOrFetchWorksheetByName(name);
- if (!worksheet) {
- return false;
+export const openWorksheetByName = async ({
+ worksheet,
+ forceNewTab,
+ mode,
+}: {
+ worksheet: string;
+ forceNewTab: boolean;
+ mode?: SQLEditorTabMode;
+}) => {
+ const sheet = await useWorkSheetStore().getOrFetchWorksheetByName(worksheet);
+ if (!sheet) {
+ return undefined;
}
- if (!isWorksheetReadableV1(worksheet)) {
+ if (!isWorksheetReadableV1(sheet)) {
pushNotification({
module: "bytebase",
style: "CRITICAL",
title: t("common.access-denied"),
});
- return false;
+ return undefined;
}
const tabStore = useSQLEditorTabStore();
const openingSheetTab = tabStore.openTabList.find(
- (tab) => tab.worksheet === worksheet.name
+ (tab) => tab.worksheet === sheet.name
);
- const statement = getSheetStatement(worksheet);
- const connection = await extractWorksheetConnection(worksheet);
+ if (openingSheetTab && !forceNewTab) {
+ // Switch to a sheet tab if it's open already.
+ tabStore.setCurrentTabId(openingSheetTab.id);
+ if (mode && mode !== openingSheetTab.mode) {
+ tabStore.updateTab(openingSheetTab.id, { mode });
+ }
+ return openingSheetTab;
+ }
+ const statement = getSheetStatement(sheet);
+ const connection = await extractWorksheetConnection(sheet);
const newTab: Partial<SQLEditorTab> = {
connection,
- worksheet: worksheet.name,
- title: worksheet.title,
+ worksheet: sheet.name,
+ title: sheet.title,
statement,
status: "CLEAN",
+ mode: mode ?? "WORKSHEET",
};
- if (openingSheetTab) {
- // Switch to a sheet tab if it's open already.
- tabStore.setCurrentTabId(openingSheetTab.id);
- return true;
- } else if (forceNewTab) {
- tabStore.addTab(newTab, true /* beside */);
- } else {
- // Open the sheet in a "temp" tab otherwise.
- tabStore.addTab(newTab);
- }
-
- return true;
-};
-
-export const addNewSheet = () => {
- const tabStore = useSQLEditorTabStore();
- const curr = tabStore.currentTab;
- const connection = curr ? { ...curr.connection } : emptySQLEditorConnection();
- const title = suggestedTabTitleForSQLEditorConnection(connection);
- tabStore.addTab({
- title,
- connection,
- status: "CLEAN",
- });
+ return tabStore.addTab(newTab, forceNewTab /* beside */);
};
diff --git a/frontend/src/views/sql-editor/TabList/TabItem/TabItem.vue b/frontend/src/views/sql-editor/TabList/TabItem/TabItem.vue
index 1d0dd9a8ec..11caf5c6a2 100644
--- a/frontend/src/views/sql-editor/TabList/TabItem/TabItem.vue
+++ b/frontend/src/views/sql-editor/TabList/TabItem/TabItem.vue
@@ -36,7 +36,7 @@
import { computed, reactive } from "vue";
import { useSQLEditorTabStore } from "@/store";
import { type SQLEditorTab, UNKNOWN_ID } from "@/types";
-import { connectionForSQLEditorTab, hexToRgb } from "@/utils";
+import { getConnectionForSQLEditorTab, hexToRgb } from "@/utils";
import AdminLabel from "./AdminLabel.vue";
import Label from "./Label.vue";
import Prefix from "./Prefix.vue";
@@ -65,7 +65,7 @@ const tabStore = useSQLEditorTabStore();
const isCurrentTab = computed(() => props.tab.id === tabStore.currentTabId);
const environment = computed(() => {
- const { database } = connectionForSQLEditorTab(props.tab);
+ const { database } = getConnectionForSQLEditorTab(props.tab);
const environment = database?.effectiveEnvironmentEntity;
if (environment?.id === String(UNKNOWN_ID)) {
return;
diff --git a/frontend/src/views/sql-editor/context.ts b/frontend/src/views/sql-editor/context.ts
index 5358db5b05..9fb75ab4bc 100644
--- a/frontend/src/views/sql-editor/context.ts
+++ b/frontend/src/views/sql-editor/context.ts
@@ -75,7 +75,9 @@ export type SQLEditorContext = {
}: {
title?: string;
folders?: string[];
- }) => Promise<void>;
+ statement?: string;
+ database?: string;
+ }) => Promise<SQLEditorTab | undefined>;
};
export const KEY = Symbol(
@@ -116,14 +118,17 @@ export const provideSQLEditorContext = () => {
title = "new worksheet",
statement = "",
folders = [],
+ database = "",
}: {
title?: string;
statement?: string;
folders?: string[];
+ database?: string;
}) => {
const newWorksheet = await worksheetStore.createWorksheet(
create(WorksheetSchema, {
- title: title,
+ title,
+ database,
content: new TextEncoder().encode(statement),
project: editorStore.project,
visibility: Worksheet_Visibility.PRIVATE,
@@ -140,10 +145,17 @@ export const provideSQLEditorContext = () => {
);
}
+ const tab = await openWorksheetByName({
+ worksheet: newWorksheet.name,
+ forceNewTab: true,
+ });
nextTick(() => {
- openWorksheetByName(newWorksheet.name, true);
- showConnectionPanel.value = true;
+ if (tab && !tab.connection?.database) {
+ showConnectionPanel.value = true;
+ }
});
+
+ return tab;
};
const context: SQLEditorContext = {