Skip to content

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

feat(sql-editor): SQL Editor project view (#11024)

Liu Jia3722ce9553d
diff --git a/frontend/src/components/ProjectMember/ProjectMemberTable/RoleDescription.vue b/frontend/src/components/ProjectMember/ProjectMemberTable/RoleDescription.vue
index 1c0fcb7bc8..1d6d199ce2 100644
--- a/frontend/src/components/ProjectMember/ProjectMemberTable/RoleDescription.vue
+++ b/frontend/src/components/ProjectMember/ProjectMemberTable/RoleDescription.vue
@@ -12,7 +12,7 @@
</template>
<script lang="ts" setup>
-import { computed, defineProps, onMounted, ref } from "vue";
+import { computed, onMounted, ref } from "vue";
import { issueServiceClient } from "@/grpcweb";
import { pushNotification } from "@/store";
import { UNKNOWN_ID } from "@/types";
diff --git a/frontend/src/components/ProvideSQLEditorContext.vue b/frontend/src/components/ProvideSQLEditorContext.vue
index c97530892f..a4222a1c55 100644
--- a/frontend/src/components/ProvideSQLEditorContext.vue
+++ b/frontend/src/components/ProvideSQLEditorContext.vue
@@ -1,90 +1,144 @@
<template>
- <slot v-if="!isLoading" />
- <div
- v-else
- class="absolute bg-white/50 inset-0 flex flex-col items-center justify-center"
- >
- <NSpin size="medium" />
- </div>
+ <teleport to="#sql-editor-debug">
+ <li>[ProvideContext]project: {{ editorStore.project }}</li>
+ <li>[ProvideContext]strictProject: {{ editorStore.strictProject }}</li>
+ <li>
+ [ProvideContext]projectContextReady:
+ {{ editorStore.projectContextReady }}
+ </li>
+ <li>
+ [ProvideContext]databaseCount: {{ editorStore.databaseList.length }}
+ </li>
+ <li>
+ [ProvideContext]allowViewALLProjects:
+ {{ editorStore.allowViewALLProjects }}
+ </li>
+ </teleport>
+ <slot />
</template>
<script lang="ts" setup>
-import { NSpin } from "naive-ui";
-import { onMounted, computed, watch, ref } from "vue";
+import { head, omit } from "lodash-es";
+import { computed, nextTick, onMounted, watch } from "vue";
import { useI18n } from "vue-i18n";
import { useRoute, useRouter } from "vue-router";
+import { useEmitteryEventListener } from "@/composables/useEmitteryEventListener";
import {
SQL_EDITOR_DETAIL_MODULE,
SQL_EDITOR_HOME_MODULE,
SQL_EDITOR_SHARE_MODULE,
} from "@/router/sqlEditor";
import {
- useEnvironmentV1Store,
useInstanceV1Store,
- usePolicyV1Store,
useProjectV1Store,
- useRoleStore,
- useSettingV1Store,
- useSQLEditorStore,
- useTabStore,
- pushNotification,
useCurrentUserV1,
- useWorkSheetStore,
useDatabaseV1Store,
+ useSQLEditorStore,
+ useSQLEditorTabStore,
+ useWorkSheetStore,
+ pushNotification,
useFilterStore,
} from "@/store";
-import { useSQLEditorTreeStore } from "@/store/modules/sqlEditorTree";
-import { projectNamePrefix } from "@/store/modules/v1/common";
import {
- Connection,
- CoreTabInfo,
- TabMode,
+ DEFAULT_PROJECT_V1_NAME,
+ DEFAULT_SQL_EDITOR_TAB_MODE,
+ SQLEditorConnection,
+ UNKNOWN_ID,
UNKNOWN_USER_NAME,
- unknownProject,
} from "@/types";
-import { UNKNOWN_ID } from "@/types";
import { State } from "@/types/proto/v1/common";
import {
- PolicyType,
- PolicyResourceType,
-} from "@/types/proto/v1/org_policy_service";
-import {
- emptyConnection,
+ emptySQLEditorConnection,
+ extractProjectResourceName,
+ getSheetStatement,
+ hasProjectPermissionV2,
idFromSlug,
- worksheetNameFromSlug,
+ isDatabaseV1Queryable,
+ isWorksheetReadableV1,
projectNameFromSheetSlug,
- worksheetSlugV1,
+ suggestedTabTitleForSQLEditorConnection,
+ worksheetNameFromSlug,
connectionV1Slug as makeConnectionV1Slug,
- isWorksheetReadableV1,
- getSuggestedTabNameFromConnection,
- hasProjectPermissionV2,
+ worksheetSlugV1,
} from "@/utils";
+import {
+ extractWorksheetConnection,
+ useSheetContext,
+} from "@/views/sql-editor/Sheet";
+import { useSQLEditorContext } from "@/views/sql-editor/context";
const { t } = useI18n();
const route = useRoute();
const router = useRouter();
-const isLoading = ref<boolean>(true);
-
-const currentUserV1 = useCurrentUserV1();
+const me = useCurrentUserV1();
const projectStore = useProjectV1Store();
-const instanceStore = useInstanceV1Store();
const databaseStore = useDatabaseV1Store();
-const policyV1Store = usePolicyV1Store();
-const sqlEditorStore = useSQLEditorStore();
-const treeStore = useSQLEditorTreeStore();
-const tabStore = useTabStore();
+const instanceStore = useInstanceV1Store();
+const editorStore = useSQLEditorStore();
const worksheetStore = useWorkSheetStore();
+const tabStore = useSQLEditorTabStore();
+const { isFetching: isFetchingWorksheet } = useSheetContext();
const { filter } = useFilterStore();
+const { events: editorEvents, maybeSwitchProject } = useSQLEditorContext();
+
+const initializeProjects = async () => {
+ const projectInQuery = route.query.project as string;
+ if (typeof projectInQuery === "string" && projectInQuery) {
+ const project = `projects/${projectInQuery}`;
+ editorStore.strictProject = true;
+ editorStore.project = project;
+ await projectStore.getOrFetchProjectByName(project, true /* silent */);
+ } else {
+ const projectList = await projectStore.fetchProjectList(false);
+ const lastView = editorStore.storedLastViewedProject;
+ if (
+ lastView &&
+ projectList.findIndex((proj) => proj.name === lastView) >= 0
+ ) {
+ editorStore.project = lastView;
+ } else {
+ const projectListWithoutDefaultProject = projectList.filter(
+ (proj) => proj.name !== DEFAULT_PROJECT_V1_NAME
+ );
+ editorStore.project =
+ head(projectListWithoutDefaultProject)?.name ??
+ head(projectList)?.name ??
+ "";
+ }
+ editorStore.strictProject = false;
+ }
+
+ tabStore.maybeInitProject(editorStore.project);
+};
+
+const handleProjectSwitched = async () => {
+ const { project } = editorStore;
+ if (project) {
+ await projectStore.getOrFetchProjectByName(project, true /* silent */);
+ } else {
+ await projectStore.fetchProjectList(false /* !showDeleted */);
+ }
+ tabStore.maybeInitProject(project);
+};
+
+const prepareInstances = async () => {
+ const { project } = editorStore;
+ if (project) {
+ await instanceStore.fetchProjectInstanceList(
+ extractProjectResourceName(project)
+ );
+ } else {
+ await instanceStore.fetchInstanceList();
+ }
+};
const prepareDatabases = async () => {
// It will also be called when user logout
- if (currentUserV1.value.name === UNKNOWN_USER_NAME) {
+ if (me.value.name === UNKNOWN_USER_NAME) {
return;
}
- let filter = "";
- if (route.query.project) {
- filter = `project == "${projectNamePrefix}${route.query.project}"`;
- }
+ const { project } = editorStore;
+ const filter = project ? `project == "${project}"` : "";
// `databaseList` is the database list accessible by current user.
// Only accessible instances and databases will be listed in the tree.
@@ -96,37 +150,7 @@ const prepareDatabases = async () => {
})
).filter((db) => db.syncState === State.ACTIVE);
- treeStore.databaseList = databaseList;
-};
-
-const prepareProjects = async () => {
- const projectName = route.query.project;
- if (projectName) {
- try {
- const project = await projectStore.getOrFetchProjectByName(
- `${projectNamePrefix}${projectName}`,
- true /* silent */
- );
- treeStore.selectedProject = project;
- } catch (error) {
- treeStore.selectedProject = unknownProject();
- }
- } else {
- await useProjectV1Store().fetchProjectList(false);
- }
-};
-
-const prepareInstances = async () => {
- const projectName = route.query.project;
- if (projectName) {
- await useInstanceV1Store().fetchProjectInstanceList(projectName as string);
- } else {
- await useInstanceV1Store().fetchInstanceList();
- }
-};
-
-const initializeTree = async () => {
- treeStore.buildTree();
+ editorStore.databaseList = databaseList;
};
const prepareSheet = async () => {
@@ -139,35 +163,30 @@ const prepareSheet = async () => {
try {
const project = await projectStore.getOrFetchProjectByName(projectName);
- if (
- !hasProjectPermissionV2(
- project,
- currentUserV1.value,
- "bb.databases.query"
- )
- ) {
+ if (!hasProjectPermissionV2(project, me.value, "bb.databases.query")) {
return false;
}
} catch {
// Nothing
}
+ await maybeSwitchProject(projectName);
const sheetName = worksheetNameFromSlug(sheetSlug);
const openingSheetTab = tabStore.tabList.find(
- (tab) => tab.sheetName == sheetName
+ (tab) => tab.sheet == sheetName
);
- sqlEditorStore.isFetchingSheet = true;
+ isFetchingWorksheet.value = true;
const sheet = await worksheetStore.getOrFetchSheetByName(sheetName);
- sqlEditorStore.isFetchingSheet = false;
+ isFetchingWorksheet.value = false;
if (!sheet) {
if (openingSheetTab) {
// If a sheet is open in a tab but it returns 404 NOT_FOUND
// that means the sheet has been deleted somewhere else.
// We need to turn the sheet to an unsaved tab.
- openingSheetTab.sheetName = undefined;
- openingSheetTab.isSaved = false;
+ openingSheetTab.sheet = "";
+ openingSheetTab.status = "DIRTY";
}
return false;
}
@@ -179,45 +198,38 @@ const prepareSheet = async () => {
});
return false;
}
+
if (openingSheetTab) {
// Switch to a sheet tab if it's open already.
+ // and don't touch it
tabStore.setCurrentTabId(openingSheetTab.id);
- } else {
- // Open the sheet in a "temp" tab otherwise.
- tabStore.addTab();
+ return true;
}
- let insId = String(UNKNOWN_ID);
- let dbId = String(UNKNOWN_ID);
- if (sheet.database) {
- try {
- const database = await databaseStore.getOrFetchDatabaseByName(
- sheet.database,
- true /* silent */
- );
- insId = database.instanceEntity.uid;
- dbId = database.uid;
- } catch {
- // Skip.
- }
- }
-
- tabStore.updateCurrentTab({
- sheetName,
- name: sheet.title,
- statement: new TextDecoder().decode(sheet.content),
- isSaved: true,
- connection: {
- ...emptyConnection(),
- // TODO: legacy instance id.
- instanceId: insId,
- databaseId: dbId,
- },
+ // Open the sheet in a new tab otherwise.
+ tabStore.addTab({
+ connection: extractWorksheetConnection(sheet),
+ sheet: sheet.name,
+ title: sheet.title,
+ statement: getSheetStatement(sheet),
+ status: "CLEAN",
});
return true;
};
+const connect = (connection: SQLEditorConnection) => {
+ tabStore.selectOrAddSimilarNewTab(
+ {
+ connection,
+ sheet: "",
+ mode: DEFAULT_SQL_EDITOR_TAB_MODE,
+ },
+ /* beside */ false,
+ /* defaultTitle */ suggestedTabTitleForSQLEditorConnection(connection)
+ );
+};
+
const prepareConnectionSlug = async () => {
const connectionSlug = (route.params.connectionSlug as string) || "";
const [instanceSlug, databaseSlug = ""] = connectionSlug.split("_");
@@ -233,30 +245,46 @@ const prepareConnectionSlug = async () => {
if (Number.isNaN(databaseId)) {
// connected to instance
- const connection = await treeStore.fetchConnectionByInstanceId(
+ const instance = await useInstanceV1Store().getOrFetchInstanceByUID(
String(instanceId)
);
- connect(connection);
+ if (instance.uid !== String(UNKNOWN_ID)) {
+ connect({
+ instance: instance.name,
+ database: "",
+ });
+ return true;
+ }
} else {
- // connected to db
- const connection = await treeStore.fetchConnectionByInstanceIdAndDatabaseId(
- String(instanceId),
+ const database = await useDatabaseV1Store().getOrFetchDatabaseByUID(
String(databaseId)
);
- connect({
- ...connection,
- schema: filter.schema,
- table: filter.table,
- });
+ if (database.uid !== String(UNKNOWN_ID)) {
+ if (!isDatabaseV1Queryable(database, me.value)) {
+ router.push({
+ name: "error.403",
+ });
+ }
+
+ // connected to db
+ await maybeSwitchProject(database.project);
+ connect({
+ instance: database.instance,
+ database: database.name,
+ schema: filter.schema,
+ table: filter.table,
+ });
+ return true;
+ }
}
- return true;
+ return false;
};
-const setConnectionFromQuery = async () => {
+const initializeConnectionFromQuery = async () => {
// Priority:
// 1. idFromSlug in sheetSlug
// 2. instanceId and databaseId in connectionSlug
- // 3. datanase in global filter
+ // 3. database in global filter
// 4. disconnected
if (await prepareSheet()) {
@@ -270,15 +298,18 @@ const setConnectionFromQuery = async () => {
if (filter.database) {
const database = await databaseStore.getOrFetchDatabaseByName(
filter.database,
- true
+ /* silent */ true
);
- connect({
- instanceId: database.instanceEntity.uid,
- databaseId: database.uid,
- schema: filter.schema,
- table: filter.table,
- });
- return;
+ if (database.uid !== String(UNKNOWN_ID)) {
+ await maybeSwitchProject(database.project);
+ connect({
+ instance: database.instance,
+ database: database.name,
+ schema: filter.schema,
+ table: filter.table,
+ });
+ return;
+ }
}
// Keep disconnected otherwise
@@ -291,16 +322,18 @@ const setConnectionFromQuery = async () => {
// 2. /sql-editor/{connection_slug} - unsaved tabs
// 3. /sql-editor - clean tabs
const syncURLWithConnection = () => {
- const connection = computed(() => tabStore.currentTab.connection);
+ const connection = computed(
+ () => tabStore.currentTab?.connection ?? emptySQLEditorConnection()
+ );
watch(
[
- () => connection.value.instanceId,
- () => connection.value.databaseId,
- () => connection.value.schema,
- () => connection.value.table,
- () => tabStore.currentTab.sheetName,
+ () => tabStore.currentTab?.sheet,
+ () => connection.value?.instance,
+ () => connection.value?.database,
+ () => connection.value?.schema,
+ () => connection.value?.table,
],
- ([instanceId, databaseId, schema, table, sheetName]) => {
+ ([sheetName, instanceName, databaseName, schema, table]) => {
if (sheetName) {
const sheet = worksheetStore.getSheetByName(sheetName);
if (sheet) {
@@ -310,119 +343,91 @@ const syncURLWithConnection = () => {
sheetSlug: worksheetSlugV1(sheet),
},
});
+ return;
} else {
- // A sheet is not found, fallback to an unsaved tab.
- tabStore.updateCurrentTab({
- sheetName: undefined,
- isSaved: false,
- });
+ const tab = tabStore.currentTab;
+ if (tab) {
+ tab.sheet = "";
+ tab.status = "DIRTY";
+ }
}
- return;
}
- if (instanceId !== String(UNKNOWN_ID)) {
- const instance = instanceStore.getInstanceByUID(instanceId);
- const database = databaseStore.getDatabaseByUID(databaseId); // might be <<Unknown database>> here
- // Sometimes the instance and/or the database might be <<Unknown>> since
- // they might be deleted somewhere else during the life of the page.
- // So we need to sync the connection values for cleaning up to prevent
- // exceptions.
- tabStore.updateCurrentTab({
- connection: {
- ...tabStore.currentTab.connection,
- instanceId: instance.uid,
- databaseId: database.uid,
- table,
- schema,
- },
- });
-
- router.replace({
- name: SQL_EDITOR_DETAIL_MODULE,
- params: {
- connectionSlug: makeConnectionV1Slug(instance, database),
- },
- query: {
- filter: table
- ? JSON.stringify({
- table,
- schema,
- })
- : undefined,
- },
+ const query = omit({ ...route.query }, "filter");
+ if (table) {
+ query.filter = JSON.stringify({
+ table,
+ schema,
});
- return;
+ }
+ if (databaseName) {
+ const database = databaseStore.getDatabaseByName(databaseName);
+ if (database.uid !== String(UNKNOWN_ID)) {
+ router.replace({
+ name: SQL_EDITOR_DETAIL_MODULE,
+ params: {
+ connectionSlug: makeConnectionV1Slug(
+ database.instanceEntity,
+ database
+ ),
+ },
+ query,
+ });
+ return;
+ }
+ }
+ if (instanceName) {
+ const instance = instanceStore.getInstanceByName(instanceName);
+ if (instance.uid !== String(UNKNOWN_ID)) {
+ router.replace({
+ name: SQL_EDITOR_DETAIL_MODULE,
+ params: {
+ connectionSlug: makeConnectionV1Slug(instance),
+ },
+ query,
+ });
+ return;
+ }
}
router.replace({
name: SQL_EDITOR_HOME_MODULE,
});
- },
- { immediate: true }
- );
-};
-
-const connect = (connection: Connection) => {
- const tab = tabStore.currentTab;
- if (tab.sheetName) {
- // Don't touch a saved sheet.
- tabStore.addTab();
- return;
- }
- const target: CoreTabInfo = {
- connection,
- mode: TabMode.ReadOnly,
- };
-
- const name = getSuggestedTabNameFromConnection(target.connection);
- tabStore.selectOrAddSimilarTab(
- target,
- /* beside */ false,
- /* defaultTabName */ name
+ }
);
- tabStore.updateCurrentTab(target);
};
onMounted(async () => {
- await router.isReady();
-
- if (treeStore.state === "UNSET") {
- treeStore.state = "LOADING";
-
- // Prepare roles, workspace policies and settings first.
- await Promise.all([
- useSettingV1Store().fetchSettingList(),
- useRoleStore().fetchRoleList(),
- useEnvironmentV1Store().fetchEnvironments(),
- policyV1Store.fetchPolicies({
- resourceType: PolicyResourceType.WORKSPACE,
- }),
- policyV1Store.fetchPolicies({
- resourceType: PolicyResourceType.ENVIRONMENT,
- policyType: PolicyType.DISABLE_COPY_DATA,
- }),
- ]);
- // Then prepare the other resources.
- await Promise.all([prepareInstances(), prepareProjects()]);
-
- await prepareDatabases();
-
- await setConnectionFromQuery();
-
- await initializeTree();
- treeStore.state = "READY";
- }
+ editorStore.projectContextReady = false;
+ await initializeProjects();
+ await prepareInstances();
+ await prepareDatabases();
+ tabStore.maybeInitProject(editorStore.project);
+ editorStore.projectContextReady = true;
+ nextTick(() => {
+ editorEvents.emit("project-context-ready", {
+ project: editorStore.project,
+ });
+ });
watch(
- () => currentUserV1.value.name,
- (name) => {
- if (name === UNKNOWN_USER_NAME) {
- // Cleanup when user signed out
- treeStore.cleanup();
- tabStore.reset();
- }
+ () => editorStore.project,
+ async () => {
+ editorStore.projectContextReady = false;
+ await handleProjectSwitched();
+ await prepareInstances();
+ await prepareDatabases();
+ tabStore.maybeInitProject(editorStore.project);
+ editorStore.projectContextReady = true;
+ nextTick(() => {
+ editorEvents.emit("project-context-ready", {
+ project: editorStore.project,
+ });
+ });
}
);
+ initializeConnectionFromQuery();
syncURLWithConnection();
- isLoading.value = false;
});
+
+useEmitteryEventListener;
</script>
diff --git a/frontend/src/components/v2/Select/ProjectSelect.vue b/frontend/src/components/v2/Select/ProjectSelect.vue
index 445f624c08..10286baacb 100644
--- a/frontend/src/components/v2/Select/ProjectSelect.vue
+++ b/frontend/src/components/v2/Select/ProjectSelect.vue
@@ -41,7 +41,7 @@ interface ProjectSelectOption extends SelectOption {
const props = withDefaults(
defineProps<{
disabled?: boolean;
- project?: string | undefined; // UNKNOWN_ID(-1) to "ALL"
+ project?: string | undefined | null; // UNKNOWN_ID(-1) to "ALL"
allowedProjectRoleList?: string[]; // Empty array([]) to "ALL"
allowedProjectTenantModeList?: TenantMode[];
allowedProjectWorkflowTypeList?: Workflow[];
diff --git a/frontend/src/composables/useExecuteSQL.ts b/frontend/src/composables/useExecuteSQL.ts
index a5f50b99fc..c45763e1e6 100644
--- a/frontend/src/composables/useExecuteSQL.ts
+++ b/frontend/src/composables/useExecuteSQL.ts
@@ -1,34 +1,39 @@
-import { cloneDeep, isEmpty } from "lodash-es";
+import { isEmpty } from "lodash-es";
import { Status } from "nice-grpc-common";
import { markRaw } from "vue";
import { useI18n } from "vue-i18n";
import { parseSQL } from "@/components/MonacoEditor/sqlParser";
import {
pushNotification,
- useTabStore,
- useSQLEditorStore,
useCurrentUserV1,
useDatabaseV1Store,
+ useSQLEditorStore,
+ useSQLEditorTabStore,
+ RESULT_ROWS_LIMIT,
+ useSQLStore,
+ useSQLEditorQueryHistoryStore,
} from "@/store";
import {
ComposedDatabase,
- ExecuteConfig,
- ExecuteOption,
SQLResultSetV1,
UNKNOWN_ID,
BBNotificationStyle,
+ SQLEditorQueryParams,
} from "@/types";
import {
Advice_Status,
advice_StatusToJSON,
} from "@/types/proto/v1/sql_service";
-import { hasPermissionToCreateChangeDatabaseIssue } from "@/utils";
+import {
+ emptySQLEditorTabQueryContext,
+ hasPermissionToCreateChangeDatabaseIssue,
+} from "@/utils";
const useExecuteSQL = () => {
const { t } = useI18n();
const currentUser = useCurrentUserV1();
const databaseStore = useDatabaseV1Store();
- const tabStore = useTabStore();
+ const tabStore = useSQLEditorTabStore();
const sqlEditorStore = useSQLEditorStore();
const notify = (
@@ -44,59 +49,66 @@ const useExecuteSQL = () => {
});
};
- const preflight = (query: string) => {
+ const preflight = (params: SQLEditorQueryParams) => {
const tab = tabStore.currentTab;
+ if (!tab) {
+ return false;
+ }
- if (tab.isExecutingSQL) {
+ if (tab.queryContext?.status === "EXECUTING") {
notify("INFO", t("common.tips"), t("sql-editor.can-not-execute-query"));
return false;
}
- const isDisconnected = tabStore.isDisconnected;
- if (isDisconnected) {
+ if (tabStore.isDisconnected) {
notify("CRITICAL", t("sql-editor.select-connection"));
return false;
}
- if (isEmpty(query)) {
+ if (isEmpty(params.statement)) {
notify("CRITICAL", t("sql-editor.notify-empty-statement"));
return false;
}
- tab.isExecutingSQL = true;
+ tab.queryContext = {
+ ...emptySQLEditorTabQueryContext(),
+ params,
+ status: "EXECUTING",
+ };
return true;
};
const cleanup = () => {
const tab = tabStore.currentTab;
- tab.isExecutingSQL = false;
+ if (!tab) return;
+ if (!tab.queryContext) return;
+ tab.queryContext.status = "IDLE";
};
- const executeReadonly = async (
- query: string,
- config: ExecuteConfig,
- option?: Partial<ExecuteOption>
- ) => {
- if (!preflight(query)) {
+ const executeReadonly = async (params: SQLEditorQueryParams) => {
+ if (!preflight(params)) {
return cleanup();
}
const tab = tabStore.currentTab;
- const { data } = await parseSQL(query);
+ if (!tab) {
+ return;
+ }
+ const queryContext = tab.queryContext!;
+ const batchQueryContext = tab.batchQueryContext;
+ const { data } = await parseSQL(params.statement);
if (data === undefined) {
notify("CRITICAL", t("sql-editor.notify-invalid-sql-statement"));
return cleanup();
}
- let selectStatement = query;
- if (option?.explain) {
- selectStatement = `EXPLAIN ${selectStatement}`;
- }
+ const statement = params.explain
+ ? `EXPLAIN ${params.statement}`
+ : params.statement;
- const batchQueryContext = tab.batchQueryContext;
- const selectedDatabase = useDatabaseV1Store().getDatabaseByUID(
- tab.connection.databaseId
+ const selectedDatabase = useDatabaseV1Store().getDatabaseByName(
+ params.connection.database
);
const databaseName =
selectedDatabase.uid === String(UNKNOWN_ID)
@@ -108,10 +120,10 @@ const useExecuteSQL = () => {
if (
databaseName &&
batchQueryContext &&
- batchQueryContext.selectedDatabaseNames.length > 0
+ batchQueryContext.databases.length > 0
) {
- for (const databaseName of batchQueryContext.selectedDatabaseNames) {
- const database = databaseStore.getDatabaseByName(databaseName);
+ for (const databaseResourceName of batchQueryContext.databases) {
+ const database = databaseStore.getDatabaseByName(databaseResourceName);
if (database.name === selectedDatabase.name) {
continue;
}
@@ -119,21 +131,19 @@ const useExecuteSQL = () => {
}
}
- const databaseQueryResultMap = new Map<string, SQLResultSetV1>();
+ const queryResultMap = new Map<string, SQLResultSetV1>();
for (const database of batchQueryDatabases) {
- databaseQueryResultMap.set(database.name, {
+ queryResultMap.set(database.name, {
error: "",
results: [],
advices: [],
allowExport: false,
});
}
- tabStore.updateCurrentTab({
- databaseQueryResultMap,
- });
+ queryContext.results = queryResultMap;
const fail = (database: ComposedDatabase, result: SQLResultSetV1) => {
- databaseQueryResultMap.set(database.name, {
+ queryResultMap.set(database.name, {
error: result.error,
results: [],
advices: result.advices,
@@ -142,13 +152,8 @@ const useExecuteSQL = () => {
});
};
- const abortController = new AbortController();
- tabStore.updateTab(tab.id, {
- queryContext: {
- beginTimestampMS: Date.now(),
- abortController,
- },
- });
+ const { abortController } = queryContext;
+ queryContext.beginTimestampMS = Date.now();
for (const database of batchQueryDatabases) {
const isUnknownDatabase = database.uid === String(UNKNOWN_ID);
if (abortController.signal.aborted) {
@@ -163,28 +168,29 @@ const useExecuteSQL = () => {
});
continue;
}
- const instanceId = isUnknownDatabase
- ? tab.connection.instanceId
- : database.instanceEntity.uid;
+ const instance = isUnknownDatabase
+ ? params.connection.instance
+ : database.instance;
const databaseName = isUnknownDatabase ? "" : database.databaseName;
const dataSourceId =
- instanceId === tab.connection.instanceId
- ? tab.connection.dataSourceId
- : undefined;
+ instance === params.connection.instance
+ ? params.connection.dataSourceId ?? ""
+ : "";
try {
- const sqlResultSet = await sqlEditorStore.executeQuery(
+ const resultSet = await useSQLStore().queryReadonly(
{
- instanceId: instanceId,
- databaseName: databaseName,
+ name: instance,
+ connectionDatabase: databaseName,
dataSourceId: dataSourceId,
- statement: selectStatement,
+ statement,
+ limit: RESULT_ROWS_LIMIT,
},
abortController.signal
);
let adviceStatus: "SUCCESS" | "ERROR" | "WARNING" = "SUCCESS";
let adviceNotifyMessage = "";
- for (const advice of sqlResultSet.advices) {
+ for (const advice of resultSet.advices) {
if (advice.status === Advice_Status.SUCCESS) {
continue;
}
@@ -212,14 +218,15 @@ const useExecuteSQL = () => {
);
}
- if (sqlResultSet.error) {
+ if (resultSet.error) {
// The error message should be consistent with the one from the backend.
if (
- sqlResultSet.error === "Support SELECT sql statement only" &&
- sqlResultSet.status === Status.INVALID_ARGUMENT
+ resultSet.error === "Support SELECT sql statement only" &&
+ resultSet.status === Status.INVALID_ARGUMENT
) {
- const { databaseId } = tab.connection;
- const database = databaseStore.getDatabaseByUID(databaseId);
+ const database = databaseStore.getDatabaseByName(
+ params.connection.database
+ );
// Show a tips to navigate to issue creation
// if the user is allowed to create issue in the project.
if (
@@ -228,17 +235,15 @@ const useExecuteSQL = () => {
currentUser.value
)
) {
- sqlEditorStore.setSQLEditorState({
- isShowExecutingHint: true,
- });
+ sqlEditorStore.isShowExecutingHint = true;
cleanup();
}
- fail(database, sqlResultSet);
+ fail(database, resultSet);
} else {
- fail(database, sqlResultSet);
+ fail(database, resultSet);
}
} else {
- databaseQueryResultMap.set(database.name, markRaw(sqlResultSet));
+ queryResultMap.set(database.name, markRaw(resultSet));
}
} catch (error: any) {
fail(database, error.response?.data?.message ?? String(error));
@@ -246,17 +251,9 @@ const useExecuteSQL = () => {
}
// After all the queries are executed, we update the tab with the latest query result map.
- tabStore.updateTab(tab.id, {
- databaseQueryResultMap: cloneDeep(databaseQueryResultMap),
- executeParams: {
- query,
- config,
- option,
- },
- });
// Refresh the query history list when the query executed successfully
// (with or without warnings).
- sqlEditorStore.fetchQueryHistoryList();
+ useSQLEditorQueryHistoryStore().fetchQueryHistoryList();
cleanup();
};
diff --git a/frontend/src/layouts/SQLEditorLayout.vue b/frontend/src/layouts/SQLEditorLayout.vue
index b306903c3a..ead8fd8e61 100644
--- a/frontend/src/layouts/SQLEditorLayout.vue
+++ b/frontend/src/layouts/SQLEditorLayout.vue
@@ -1,26 +1,77 @@
<template>
<div class="relative h-screen overflow-hidden flex flex-col">
+ <ul
+ id="sql-editor-debug"
+ class="hidden text-xs font-mono max-h-[33vh] max-w-[40vw] overflow-auto fixed bottom-0 right-0 p-2 bg-white/50 border border-gray-400 z-[999999]"
+ ></ul>
+
<BannersWrapper v-if="showBanners" />
<!-- Suspense is experimental, be aware of the potential change -->
- <Suspense>
- <template #default>
- <ProvideSQLEditorContext>
- <router-view />
- </ProvideSQLEditorContext>
- </template>
+ <Suspense v-if="ready">
+ <ProvideSQLEditorContext>
+ <router-view />
+ </ProvideSQLEditorContext>
</Suspense>
</div>
</template>
<script lang="ts" setup>
-import { computed } from "vue";
+import { computed, ref } from "vue";
+import { onMounted } from "vue";
+import { useRouter } from "vue-router";
import BannersWrapper from "@/components/BannersWrapper.vue";
import ProvideSQLEditorContext from "@/components/ProvideSQLEditorContext.vue";
-import { usePageMode } from "@/store";
+import {
+ useEnvironmentV1Store,
+ usePageMode,
+ usePolicyV1Store,
+ useRoleStore,
+ useSettingV1Store,
+} from "@/store";
+import {
+ PolicyResourceType,
+ PolicyType,
+} from "@/types/proto/v1/org_policy_service";
+import { provideSecondarySidebarContext } from "@/views/sql-editor/SecondarySidebar";
+import { provideSheetContext } from "@/views/sql-editor/Sheet";
+import { provideSQLEditorContext } from "@/views/sql-editor/context";
+const router = useRouter();
const pageMode = usePageMode();
+// provide context for SQL Editor
+provideSQLEditorContext();
+// provide context for sheets
+provideSheetContext();
+provideSecondarySidebarContext();
+
const showBanners = computed(() => {
return pageMode.value === "BUNDLED";
});
+
+const ready = ref(false);
+
+// We may tweak the resource loading here, and pre-load some frontend component
+// resources, and make a loading screen here in the future.
+const prepare = async () => {
+ await router.isReady();
+
+ const policyV1Store = usePolicyV1Store();
+ // Prepare roles, workspace policies and settings.
+ await Promise.all([
+ useSettingV1Store().fetchSettingList(),
+ useRoleStore().fetchRoleList(),
+ useEnvironmentV1Store().fetchEnvironments(),
+ policyV1Store.fetchPolicies({
+ resourceType: PolicyResourceType.WORKSPACE,
+ }),
+ policyV1Store.fetchPolicies({
+ resourceType: PolicyResourceType.ENVIRONMENT,
+ policyType: PolicyType.DISABLE_COPY_DATA,
+ }),
+ ]);
+ ready.value = true;
+};
+
+onMounted(prepare);
</script>
diff --git a/frontend/src/plugins/ai/components/AIChatToSQL.vue b/frontend/src/plugins/ai/components/AIChatToSQL.vue
index 30176c9872..365bca53e4 100644
--- a/frontend/src/plugins/ai/components/AIChatToSQL.vue
+++ b/frontend/src/plugins/ai/components/AIChatToSQL.vue
@@ -6,14 +6,9 @@
import { useLocalStorage } from "@vueuse/core";
import Emittery from "emittery";
import { computed, reactive, toRef } from "vue";
-import {
- useCurrentTab,
- useInstanceV1ByUID,
- useDatabaseV1ByUID,
- useMetadata,
-} from "@/store";
+import { useMetadata, useConnectionOfCurrentSQLEditorTab } from "@/store";
import { useSettingV1Store } from "@/store/modules/v1/setting";
-import { Connection } from "@/types";
+import { SQLEditorConnection } from "@/types";
import { DatabaseMetadataView } from "@/types/proto/v1/database_service";
import type { AIContextEvents } from "../types";
@@ -37,7 +32,7 @@ const emit = defineEmits<{
(
event: "apply-statement",
statement: string,
- conn: Connection,
+ conn: SQLEditorConnection,
run: boolean
): void;
}>();
@@ -57,14 +52,8 @@ const openAIKey = computed(() => openAIKeySetting?.value?.stringValue ?? "");
const openAIEndpoint = computed(
() => openAIEndpointSetting?.value?.stringValue ?? ""
);
-const tab = useCurrentTab();
+const { connection, instance, database } = useConnectionOfCurrentSQLEditorTab();
-const { instance } = useInstanceV1ByUID(
- computed(() => tab.value.connection.instanceId)
-);
-const { database } = useDatabaseV1ByUID(
- computed(() => tab.value.connection.databaseId)
-);
const databaseMetadata = useMetadata(
database.value.name,
false /* !skipCache */,
@@ -74,7 +63,7 @@ const databaseMetadata = useMetadata(
const events: AIContextEvents = new Emittery();
events.on("apply-statement", ({ statement, run }) => {
- emit("apply-statement", statement, tab.value.connection, run);
+ emit("apply-statement", statement, connection.value, run);
});
const autoRun = useLocalStorage("bb.plugin.ai.auto-run", false);
diff --git a/frontend/src/plugins/ai/components/ActionBar.vue b/frontend/src/plugins/ai/components/ActionBar.vue
index 9d17f847b1..789ad3333c 100644
--- a/frontend/src/plugins/ai/components/ActionBar.vue
+++ b/frontend/src/plugins/ai/components/ActionBar.vue
@@ -5,7 +5,7 @@
<div
class="action-left gap-x-2 flex overflow-x-auto sm:overflow-x-hidden items-center"
>
- <NButton size="small" @click="tab.editMode = 'SQL-EDITOR'">
+ <NButton size="small" @click="tab!.editMode = 'SQL-EDITOR'">
<template #icon>
<heroicons:chevron-left />
</template>
@@ -35,10 +35,10 @@
</template>
<script lang="ts" setup>
-import { useCurrentTab } from "@/store";
+import { useCurrentSQLEditorTab } from "@/store";
import { useAIContext } from "../logic";
-const tab = useCurrentTab();
+const tab = useCurrentSQLEditorTab();
const { events, showHistoryDialog } = useAIContext();
</script>
diff --git a/frontend/src/plugins/ai/components/ChatPanel.vue b/frontend/src/plugins/ai/components/ChatPanel.vue
index b3a83f65ae..83df909ecd 100644
--- a/frontend/src/plugins/ai/components/ChatPanel.vue
+++ b/frontend/src/plugins/ai/components/ChatPanel.vue
@@ -16,7 +16,11 @@
<div v-if="isChatMode" class="flex items-center gap-2 w-full">
<DynamicSuggestions class="flex-1" @enter="requestAI" />
</div>
- <PromptInput @focus="tab.editMode = 'CHAT-TO-SQL'" @enter="requestAI" />
+ <PromptInput
+ v-if="tab"
+ @focus="tab.editMode = 'CHAT-TO-SQL'"
+ @enter="requestAI"
+ />
</div>
<template v-if="isChatMode">
@@ -28,8 +32,9 @@
<script lang="ts" setup>
import { Axios, AxiosResponse } from "axios";
import { head } from "lodash-es";
+import { storeToRefs } from "pinia";
import { computed, reactive, watch } from "vue";
-import { useCurrentTab } from "@/store";
+import { useSQLEditorTabStore } from "@/store";
import { engineNameV1 } from "@/utils";
import { onConnectionChanged, useAIContext, useCurrentChat } from "../logic";
import { useConversationStore } from "../store";
@@ -48,9 +53,9 @@ const state = reactive<LocalState>({
loading: false,
});
-const tab = useCurrentTab();
+const { currentTab: tab } = storeToRefs(useSQLEditorTabStore());
const store = useConversationStore();
-const isChatMode = computed(() => tab.value.editMode === "CHAT-TO-SQL");
+const isChatMode = computed(() => tab.value?.editMode === "CHAT-TO-SQL");
const context = useAIContext();
const { events, openAIKey, openAIEndpoint, autoRun, showHistoryDialog } =
@@ -65,6 +70,7 @@ const requestAI = async (query: string) => {
const conversation = selectedConversation.value;
if (!conversation) return;
const t = tab.value;
+ if (!t) return;
const { messageList } = conversation;
if (messageList.length === 0) {
@@ -215,6 +221,7 @@ onConnectionChanged(() => {
});
events.on("new-conversation", async () => {
+ if (!tab.value) return;
showHistoryDialog.value = false;
const c = await store.createConversation({
name: "",
@@ -229,7 +236,8 @@ watch(
if (ready && list.length === 0) {
store.createConversation({
name: "",
- ...tab.value.connection,
+ instance: tab.value?.connection.instance ?? "",
+ database: tab.value?.connection.database ?? "",
});
}
},
diff --git a/frontend/src/plugins/ai/components/HistoryPanel/ConversationList.vue b/frontend/src/plugins/ai/components/HistoryPanel/ConversationList.vue
index e2f0479e78..2ccb4bbbb8 100644
--- a/frontend/src/plugins/ai/components/HistoryPanel/ConversationList.vue
+++ b/frontend/src/plugins/ai/components/HistoryPanel/ConversationList.vue
@@ -77,7 +77,7 @@ import { head } from "lodash-es";
import { NPopconfirm } from "naive-ui";
import scrollIntoView from "scroll-into-view-if-needed";
import { reactive, watch } from "vue";
-import { useCurrentTab } from "@/store";
+import { useCurrentSQLEditorTab } from "@/store";
import { useAIContext, useCurrentChat } from "../../logic";
import { useConversationStore } from "../../store";
import type { Conversation } from "../../types";
@@ -87,7 +87,7 @@ type LocalState = {
rename: Conversation | undefined;
};
-const tab = useCurrentTab();
+const tab = useCurrentSQLEditorTab();
const store = useConversationStore();
const { events } = useAIContext();
const { list, ready, selected } = useCurrentChat();
@@ -97,10 +97,7 @@ const state = reactive<LocalState>({
});
watch(
- [
- () => tab.value.connection.instanceId,
- () => tab.value.connection.databaseId,
- ],
+ [() => tab.value?.connection.instance, () => tab.value?.connection.database],
() => {
state.rename = undefined;
},
diff --git a/frontend/src/plugins/ai/logic/useChatByTab.ts b/frontend/src/plugins/ai/logic/useChatByTab.ts
index dd766dc523..3b0616ad61 100644
--- a/frontend/src/plugins/ai/logic/useChatByTab.ts
+++ b/frontend/src/plugins/ai/logic/useChatByTab.ts
@@ -1,7 +1,7 @@
import { last } from "lodash-es";
import { computed, ref, watch } from "vue";
-import { useCurrentTab } from "@/store";
-import { TabInfo } from "@/types";
+import { useSQLEditorTabStore } from "@/store";
+import { SQLEditorTab } from "@/types";
import { useConversationStore } from "../store";
import { AIChatInfo, Conversation } from "../types";
import { useAIContext } from "./context";
@@ -9,18 +9,17 @@ import { useAIContext } from "./context";
const chatsByTab = new Map<string, AIChatInfo>();
export const useChatByTab = () => {
- const tab = useCurrentTab();
const store = useConversationStore();
- const initializeChat = (tab: TabInfo): AIChatInfo => {
+ const initializeChat = (tab: SQLEditorTab): AIChatInfo => {
const ready = ref(false);
store.fetchConversationListByConnection(tab.connection).then(() => {
ready.value = true;
});
const list = computed(() => {
- const { instanceId, databaseId } = tab.connection;
+ const { instance, database } = tab.connection;
return store.conversationList.filter(
- (c) => c.instanceId === instanceId && c.databaseId === databaseId
+ (c) => c.instance === instance && c.database === database
);
});
const selected = ref<Conversation>();
@@ -38,8 +37,11 @@ export const useChatByTab = () => {
return { list, ready, selected };
};
- const getChatByTab = (tab: TabInfo) => {
- const key = JSON.stringify(tab.connection);
+ const getChatByTab = (tab: SQLEditorTab) => {
+ const key = JSON.stringify({
+ instance: tab.connection.instance,
+ database: tab.connection.database,
+ });
const existed = chatsByTab.get(key);
if (existed) return existed;
const chat = initializeChat(tab);
@@ -48,7 +50,8 @@ export const useChatByTab = () => {
};
return computed(() => {
- return getChatByTab(tab.value);
+ const tab = useSQLEditorTabStore().currentTab!;
+ return getChatByTab(tab);
});
};
diff --git a/frontend/src/plugins/ai/logic/utils.ts b/frontend/src/plugins/ai/logic/utils.ts
index 10f77045f4..3b399a2c09 100644
--- a/frontend/src/plugins/ai/logic/utils.ts
+++ b/frontend/src/plugins/ai/logic/utils.ts
@@ -1,25 +1,28 @@
import { watch } from "vue";
-import { useCurrentTab } from "@/store";
-import type { Connection } from "@/types";
+import { useCurrentSQLEditorTab } from "@/store";
+import type { SQLEditorConnection } from "@/types";
import { Engine } from "@/types/proto/v1/common";
import { DatabaseMetadata } from "@/types/proto/v1/database_service";
import { engineNameV1 } from "@/utils";
export const onConnectionChanged = (
- fn: (newConn: Connection, oldConn: Connection | undefined) => void,
+ fn: (
+ newConn: SQLEditorConnection,
+ oldConn: SQLEditorConnection | undefined
+ ) => void,
immediate = false
) => {
- const tab = useCurrentTab();
+ const tab = useCurrentSQLEditorTab();
return watch(
[
- () => tab.value.connection.instanceId,
- () => tab.value.connection.databaseId,
+ () => tab.value?.connection.instance,
+ () => tab.value?.connection.database,
],
(newValues, oldValues) => {
fn(
- { instanceId: newValues[0], databaseId: newValues[1] },
+ { instance: newValues[0] ?? "", database: newValues[1] ?? "" },
oldValues[0] && oldValues[1]
- ? { instanceId: oldValues[0], databaseId: oldValues[1] }
+ ? { instance: oldValues[0] ?? "", database: oldValues[1] ?? "" }
: undefined
);
},
diff --git a/frontend/src/plugins/ai/store/conversation.ts b/frontend/src/plugins/ai/store/conversation.ts
index 06f9395230..49076feb67 100644
--- a/frontend/src/plugins/ai/store/conversation.ts
+++ b/frontend/src/plugins/ai/store/conversation.ts
@@ -4,7 +4,7 @@ import PouchDB from "pouchdb";
import PouchDBFind from "pouchdb-find";
import { v1 as uuidv1 } from "uuid";
import { computed, reactive, ref, unref, watchEffect } from "vue";
-import { Connection, MaybeRef } from "@/types";
+import { MaybeRef, SQLEditorConnection } from "@/types";
import { Conversation, Message } from "../types";
type RowStatus = "NORMAL" | "ARCHIVED";
@@ -133,13 +133,15 @@ export const useConversationStore = defineStore("ai-conversation", () => {
return [...conversationById.values()];
});
- const fetchConversationListByConnection = async (conn: Connection) => {
+ const fetchConversationListByConnection = async (
+ conn: SQLEditorConnection
+ ) => {
const conversationEntityList = (
await conversations.find({
selector: {
row_status: { $eq: "NORMAL" },
- instanceId: { $eq: conn.instanceId },
- databaseId: { $eq: conn.databaseId },
+ instance: { $eq: conn.instance },
+ database: { $eq: conn.database },
},
})
).docs;
@@ -270,7 +272,9 @@ export const useConversationStore = defineStore("ai-conversation", () => {
};
});
-export const useConversationListByConnection = (conn: MaybeRef<Connection>) => {
+export const useConversationListByConnection = (
+ conn: MaybeRef<SQLEditorConnection>
+) => {
const store = useConversationStore();
const ready = ref(false);
watchEffect(async () => {
@@ -279,9 +283,9 @@ export const useConversationListByConnection = (conn: MaybeRef<Connection>) => {
ready.value = true;
});
const list = computed(() => {
- const { instanceId, databaseId } = unref(conn);
+ const { instance, database } = unref(conn);
return store.conversationList.filter(
- (c) => c.instanceId === instanceId && c.databaseId === databaseId
+ (c) => c.instance === instance && c.database === database
);
});
return { list, ready };
diff --git a/frontend/src/plugins/ai/types/conversation.ts b/frontend/src/plugins/ai/types/conversation.ts
index d77ad1424a..499ec443ea 100644
--- a/frontend/src/plugins/ai/types/conversation.ts
+++ b/frontend/src/plugins/ai/types/conversation.ts
@@ -1,5 +1,3 @@
-import type { InstanceId, DatabaseId } from "@/types";
-
export type MessageAuthor = "USER" | "AI";
export type MessageStatus = "LOADING" | "DONE" | "FAILED";
@@ -19,7 +17,7 @@ export type Conversation = {
id: string; // uuid
created_ts: number; // ms
name: string;
- instanceId: InstanceId;
- databaseId: DatabaseId;
+ instance: string;
+ database: string;
messageList: Message[];
};
diff --git a/frontend/src/plugins/sql-lsp/server/server.ts b/frontend/src/plugins/sql-lsp/server/server.ts
index 3cd8335b57..a093238562 100644
--- a/frontend/src/plugins/sql-lsp/server/server.ts
+++ b/frontend/src/plugins/sql-lsp/server/server.ts
@@ -5,7 +5,9 @@ import type {
CompletionItem,
} from "vscode-languageserver/browser";
import { CompletionTriggerKind } from "vscode-languageserver/browser";
-import { EngineTypesUsingSQL } from "@/types/sqlEditor";
+// when this file is imported as WebWorker we need to import stuff clearly from a file
+// or strange thing might happen lol
+import { EngineTypesUsingSQL } from "@/types/sqlEditor/editor";
import { complete } from "./complete";
import { initializeConnection } from "./initializeConnection";
diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts
index 648cf21e89..c733f81332 100644
--- a/frontend/src/router/index.ts
+++ b/frontend/src/router/index.ts
@@ -6,12 +6,12 @@ import {
useAuthStore,
useActuatorV1Store,
useRouterStore,
- useTabStore,
useCurrentUserV1,
usePageMode,
useProjectV1Store,
useDatabaseV1Store,
useInstanceV1Store,
+ useSQLEditorTabStore,
} from "@/store";
import authRoutes, {
AUTH_2FA_SETUP_MODULE,
@@ -110,7 +110,7 @@ router.beforeEach((to, from, next) => {
to.name === AUTH_MFA_MODULE ||
to.name === AUTH_PASSWORD_FORGOT_MODULE
) {
- useTabStore().reset();
+ useSQLEditorTabStore().reset();
useDatabaseV1Store().reset();
useProjectV1Store().reset();
useInstanceV1Store().reset();
diff --git a/frontend/src/store/modules/index.ts b/frontend/src/store/modules/index.ts
index ffb131a8a3..b72f5b865a 100644
--- a/frontend/src/store/modules/index.ts
+++ b/frontend/src/store/modules/index.ts
@@ -5,8 +5,6 @@ export * from "./notification";
export * from "./slowQueryPolicy";
export * from "./router";
export * from "./sqlEditor";
-export * from "./sqlEditorTree";
-export * from "./tab";
export * from "./uistate";
export * from "./sqlReview";
export * from "./onboardingState";
diff --git a/frontend/src/store/modules/sqlEditor.ts b/frontend/src/store/modules/sqlEditor.ts
deleted file mode 100644
index c376877442..0000000000
--- a/frontend/src/store/modules/sqlEditor.ts
+++ /dev/null
@@ -1,95 +0,0 @@
-import { defineStore } from "pinia";
-import {
- SQLEditorState,
- QueryInfo,
- QueryHistory,
- ActivitySQLEditorQueryPayload,
-} from "@/types";
-import { UNKNOWN_ID } from "@/types";
-import { useInstanceV1Store, useSQLStore, useActivityV1Store } from "./v1";
-
-// set the limit to 1000 temporarily to avoid the query timeout and page crash
-export const RESULT_ROWS_LIMIT = 1000;
-
-export const useSQLEditorStore = defineStore("sqlEditor", {
- state: (): SQLEditorState => ({
- isShowExecutingHint: false,
- shouldFormatContent: false,
- // Related data and status
- queryHistoryList: [],
- isFetchingQueryHistory: false,
- isFetchingSheet: false,
- }),
-
- actions: {
- setSQLEditorState(payload: Partial<SQLEditorState>) {
- Object.assign(this, payload);
- },
- setShouldFormatContent(payload: boolean) {
- this.shouldFormatContent = payload;
- },
- setQueryHistoryList(payload: QueryHistory[]) {
- this.queryHistoryList = payload;
- },
- setIsFetchingQueryHistory(payload: boolean) {
- this.isFetchingQueryHistory = payload;
- },
- async executeQuery(
- {
- instanceId,
- databaseName,
- dataSourceId,
- statement,
- }: Pick<
- QueryInfo,
- "instanceId" | "databaseName" | "dataSourceId" | "statement"
- >,
- signal: AbortSignal
- ) {
- const instance = useInstanceV1Store().getInstanceByUID(
- String(instanceId)
- );
- const response = await useSQLStore().queryReadonly(
- {
- name: instance.name,
- connectionDatabase: databaseName || "",
- dataSourceId: dataSourceId || "",
- statement,
- limit: RESULT_ROWS_LIMIT,
- },
- signal
- );
-
- return response;
- },
- async fetchQueryHistoryList() {
- this.setIsFetchingQueryHistory(true);
- const activityList =
- await useActivityV1Store().fetchActivityListForQueryHistory({
- limit: 20,
- order: "desc",
- });
- const queryHistoryList: QueryHistory[] = activityList.map(
- (history): QueryHistory => {
- const payload = JSON.parse(
- history.payload
- ) as ActivitySQLEditorQueryPayload;
- return {
- name: history.name,
- creator: history.creator,
- createTime: history.createTime ?? new Date(),
- statement: payload.statement,
- durationNs: payload.durationNs,
- instanceId: payload.instanceId || UNKNOWN_ID,
- instanceName: payload.instanceName,
- databaseId: payload.databaseId || UNKNOWN_ID,
- databaseName: payload.databaseName,
- error: payload.error,
- };
- }
- );
- this.setQueryHistoryList(queryHistoryList);
- this.setIsFetchingQueryHistory(false);
- },
- },
-});
diff --git a/frontend/src/store/modules/sqlEditor/editor.ts b/frontend/src/store/modules/sqlEditor/editor.ts
new file mode 100644
index 0000000000..5a17c39e5e
--- /dev/null
+++ b/frontend/src/store/modules/sqlEditor/editor.ts
@@ -0,0 +1,55 @@
+import { useLocalStorage } from "@vueuse/core";
+import { defineStore } from "pinia";
+import { computed, ref, watch } from "vue";
+import { ComposedDatabase } from "@/types";
+import { hasWorkspacePermissionV2 } from "@/utils";
+import { useCurrentUserV1 } from "../auth";
+import { useProjectV1Store } from "../v1";
+
+// set the limit to 1000 temporarily to avoid the query timeout and page crash
+export const RESULT_ROWS_LIMIT = 1000;
+
+export const useSQLEditorStore = defineStore("sqlEditor", () => {
+ // empty to "ALL" projects for high-privileged users
+ const project = ref<string>("");
+ // if `true`, won't show project selector and not allowed to switch to other projects
+ const strictProject = ref<boolean>(false);
+ // `false` if we are preparing project-scoped resources
+ // we should render a skeleton layout with spinner placeholders
+ const projectContextReady = ref<boolean>(false);
+ const storedLastViewedProject = useLocalStorage<string>(
+ "bb.sql-editor.last-viewed-project",
+ ""
+ );
+
+ const currentProject = computed(() => {
+ if (project.value) {
+ return useProjectV1Store().getProjectByName(project.value);
+ }
+ return undefined;
+ });
+ const allowViewALLProjects = computed(() => {
+ const me = useCurrentUserV1();
+ return hasWorkspacePermissionV2(me.value, "bb.projects.list");
+ });
+
+ // `databaseList` is query-able databases scoped by `project`
+ const databaseList = ref<ComposedDatabase[]>([]);
+
+ watch(project, (project) => {
+ storedLastViewedProject.value = project;
+ });
+
+ const isShowExecutingHint = ref(false);
+
+ return {
+ project,
+ strictProject,
+ projectContextReady,
+ storedLastViewedProject,
+ currentProject,
+ allowViewALLProjects,
+ databaseList,
+ isShowExecutingHint,
+ };
+});
diff --git a/frontend/src/store/modules/sqlEditor/index.ts b/frontend/src/store/modules/sqlEditor/index.ts
new file mode 100644
index 0000000000..8f62bc4914
--- /dev/null
+++ b/frontend/src/store/modules/sqlEditor/index.ts
@@ -0,0 +1,5 @@
+export * from "./editor";
+export * from "./tab";
+export * from "./tree";
+export * from "./queryHistory";
+export * from "./webTerminal";
diff --git a/frontend/src/store/modules/sqlEditor/queryHistory.ts b/frontend/src/store/modules/sqlEditor/queryHistory.ts
new file mode 100644
index 0000000000..4e8044b1e7
--- /dev/null
+++ b/frontend/src/store/modules/sqlEditor/queryHistory.ts
@@ -0,0 +1,70 @@
+import { defineStore } from "pinia";
+import { ref } from "vue";
+import {
+ ActivitySQLEditorQueryPayload,
+ SQLEditorQueryHistory,
+ UNKNOWN_ID,
+} from "@/types";
+import { emptySQLEditorConnection } from "@/utils";
+import {
+ useActivityV1Store,
+ useDatabaseV1Store,
+ useInstanceV1Store,
+} from "../v1";
+
+export const useSQLEditorQueryHistoryStore = defineStore(
+ "sqlEditorQueryHistory",
+ () => {
+ const isFetching = ref(false);
+ const queryHistoryList = ref<SQLEditorQueryHistory[]>([]);
+
+ const fetchQueryHistoryList = async () => {
+ isFetching.value = true;
+ const activityList =
+ await useActivityV1Store().fetchActivityListForQueryHistory({
+ limit: 20,
+ order: "desc",
+ });
+ const historyList = activityList.map<SQLEditorQueryHistory>(
+ (activity) => {
+ const payload = JSON.parse(
+ activity.payload
+ ) as ActivitySQLEditorQueryPayload;
+
+ const connection = emptySQLEditorConnection();
+ const database = useDatabaseV1Store().getDatabaseByUID(
+ String(payload.databaseId) || String(UNKNOWN_ID)
+ );
+ if (database.uid !== String(UNKNOWN_ID)) {
+ connection.instance = database.instance;
+ connection.database = database.name;
+ } else {
+ const instance = useInstanceV1Store().getInstanceByUID(
+ String(payload.instanceId) || String(UNKNOWN_ID)
+ );
+ if (instance.uid !== String(UNKNOWN_ID))
+ connection.instance = instance.name;
+ }
+ return {
+ name: activity.name,
+ creator: activity.creator,
+ createTime: activity.createTime ?? new Date(),
+ statement: payload.statement,
+ durationNs: payload.durationNs,
+ instance: connection.instance,
+ database: connection.database,
+ error: payload.error,
+ };
+ }
+ );
+ isFetching.value = false;
+ queryHistoryList.value = historyList;
+ };
+
+ return {
+ isFetching,
+ queryHistoryList,
+ fetchQueryHistoryList,
+ };
+ }
+);
diff --git a/frontend/src/store/modules/sqlEditor/tab.ts b/frontend/src/store/modules/sqlEditor/tab.ts
new file mode 100644
index 0000000000..15a9de9599
--- /dev/null
+++ b/frontend/src/store/modules/sqlEditor/tab.ts
@@ -0,0 +1,360 @@
+import { MaybeRef, useLocalStorage, watchThrottled } from "@vueuse/core";
+import { head, pick, uniqBy } from "lodash-es";
+import { defineStore, storeToRefs } from "pinia";
+import { computed, reactive, unref } from "vue";
+import type {
+ SQLEditorConnection,
+ SQLEditorTreeNodeMeta,
+ CoreSQLEditorTab,
+ SQLEditorTab,
+} from "@/types";
+import {
+ WebStorageHelper,
+ defaultSQLEditorTab,
+ emptySQLEditorConnection,
+ isDisconnectedSQLEditorTab,
+ isSimilarSQLEditorTab,
+} from "@/utils";
+import { useDatabaseV1Store, useInstanceV1Store } from "../v1";
+import { useSQLEditorStore } from "./editor";
+import { useWebTerminalStore } from "./webTerminal";
+
+const LOCAL_STORAGE_KEY_PREFIX = "bb.sql-editor-tab";
+const KEYS = {
+ tabIdList: "tab-id-list",
+ currentTabId: "current-tab-id",
+ tab: (id: string) => `tab.${id}`,
+};
+
+// Only store the core fields of a tab.
+// Don't store anything which might be too large.
+const PERSISTENT_TAB_FIELDS = [
+ "id",
+ "title",
+ "connection",
+ "statement",
+ "mode",
+ "sheet",
+ "status",
+ "batchQueryContext",
+] as const;
+type PersistentTab = Pick<SQLEditorTab, typeof PERSISTENT_TAB_FIELDS[number]>;
+
+// `tabsById` stores all PersistentTab items across all projects
+const tabsById = reactive(new Map<string, SQLEditorTab>());
+
+export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {
+ // re-expose selected project in sqlEditorStore for shortcut
+ const { project } = storeToRefs(useSQLEditorStore());
+
+ // states
+ const storage = new WebStorageHelper(LOCAL_STORAGE_KEY_PREFIX);
+ const tabIdListMapByProject = useLocalStorage<Record<string, string[]>>(
+ `${LOCAL_STORAGE_KEY_PREFIX}.${KEYS.tabIdList}`,
+ {}
+ );
+ const currentTabIdMapByProject = useLocalStorage<
+ Record<string, string | undefined>
+ >(`${LOCAL_STORAGE_KEY_PREFIX}.${KEYS.currentTabId}`, {});
+ const initializedProjects = new Set<string>();
+ const maybeInitProject = (project: string) => {
+ if (initializedProjects.has(project)) {
+ return;
+ }
+
+ const storedTabIdList = tabIdListMapByProject.value[project] ?? [];
+ // Load tabs
+ const validTabIdList: string[] = [];
+ storedTabIdList.forEach((id) => {
+ const storedTab = storage.load<PersistentTab | undefined>(
+ KEYS.tab(id),
+ undefined
+ );
+ if (!storedTab) return;
+ const tab = reactive<SQLEditorTab>({
+ ...defaultSQLEditorTab(),
+ ...storedTab,
+ id,
+ });
+ watchTab(tab, false /* !immediate */);
+ tabsById.set(id, tab);
+ validTabIdList.push(id);
+ });
+
+ tabIdListMapByProject.value[project] = validTabIdList;
+
+ // Load currentTabId
+ const storedCurrentTabId = currentTabIdMapByProject.value[project];
+ if (!storedCurrentTabId || !validTabIdList.includes(storedCurrentTabId)) {
+ // storedCurrentTabId is not in tabIdList
+ // fallback to the first tab or nothing
+ currentTabIdMapByProject.value[project] = head(validTabIdList) ?? "";
+ }
+
+ initializedProjects.add(project);
+ };
+
+ // computed states
+ // `tabIdList` is the tabIdList in current project
+ // it's a combination of `project` and `tabIdListMapByProject`
+ const tabIdList = computed({
+ get() {
+ // _maybeInitProject(project.value);
+ return tabIdListMapByProject.value[project.value] ?? [];
+ },
+ set(list) {
+ tabIdListMapByProject.value[project.value] = list;
+ },
+ });
+ // `currentTabId` is the currentTabId in current project
+ // it's a combination of `project` and `currentTabIdMapByProject`
+ const currentTabId = computed({
+ get() {
+ // _maybeInitProject(project.value);
+ return currentTabIdMapByProject.value[project.value] ?? "";
+ },
+ set(id) {
+ currentTabIdMapByProject.value[project.value] = id;
+ },
+ });
+ const tabById = (id: string) => {
+ return tabsById.get(id);
+ };
+ const tabList = computed(() => {
+ return tabIdList.value.map((id) => {
+ return tabById(id) ?? defaultSQLEditorTab();
+ });
+ });
+ const currentTab = computed(() => {
+ // _maybeInitProject(project.value);
+ const currId = currentTabId.value;
+ if (!currId) return undefined;
+ return tabsById.get(currId);
+ });
+
+ // actions
+ /**
+ *
+ * @param payload
+ * @param beside `true` to add the tab beside currentTab, `false` to add the tab to the last, default to `false`
+ * @returns
+ */
+ const addTab = (payload?: Partial<SQLEditorTab>, beside = false) => {
+ const newTab = reactive<SQLEditorTab>({
+ ...defaultSQLEditorTab(),
+ ...payload,
+ });
+
+ const { id } = newTab;
+ const position = tabIdList.value.indexOf(currentTabId.value ?? "");
+ if (beside && position >= 0) {
+ tabIdList.value.splice(position + 1, 0, id);
+ } else {
+ tabIdList.value.push(id);
+ }
+ currentTabId.value = id;
+ tabsById.set(id, newTab);
+
+ watchTab(newTab, true /* immediate */);
+ };
+ const removeTab = (tab: SQLEditorTab) => {
+ const { id } = tab;
+ const position = tabIdList.value.indexOf(id);
+ if (position < 0) return;
+ tabIdList.value.splice(position, 1);
+ tabsById.delete(id);
+ storage.remove(KEYS.tab(id));
+
+ if (tab.mode === "ADMIN") {
+ useWebTerminalStore().clearQueryStateByTab(id);
+ }
+ };
+ const updateTab = (id: string, payload: Partial<SQLEditorTab>) => {
+ const tab = tabById(id);
+ if (!tab) return;
+ Object.assign(tab, payload);
+ };
+ const updateCurrentTab = (payload: Partial<SQLEditorTab>) => {
+ const id = currentTabId.value;
+ if (!id) return;
+ updateTab(id, payload);
+ };
+ const setCurrentTabId = (id: string) => {
+ currentTabId.value = id;
+ };
+ const selectOrAddSimilarNewTab = (
+ tab: CoreSQLEditorTab,
+ beside = false,
+ defaultTitle?: string
+ ) => {
+ const curr = currentTab.value;
+ if (curr) {
+ if (
+ isDisconnectedSQLEditorTab(curr) ||
+ isSimilarSQLEditorTab(tab, curr)
+ ) {
+ curr.connection = tab.connection;
+ curr.sheet = tab.sheet;
+ curr.mode = tab.mode;
+ if (defaultTitle) {
+ curr.title = defaultTitle;
+ }
+ return;
+ }
+ }
+ const similarNewTab = tabList.value.find(
+ (tmp) => tmp.status === "NEW" && isSimilarSQLEditorTab(tmp, tab)
+ );
+ if (similarNewTab) {
+ setCurrentTabId(similarNewTab.id);
+ } else {
+ addTab(
+ {
+ ...tab,
+ title: defaultTitle,
+ },
+ beside
+ );
+ }
+ };
+ // clean persistent tabs that are not in the `tabIdList` anymore
+ const _cleanup = () => {
+ const prefix = `${LOCAL_STORAGE_KEY_PREFIX}.tab.`;
+ const keys = storage.keys().filter((key) => key.startsWith(prefix));
+ const flattenTabIdSet = new Set(
+ Object.keys(tabIdListMapByProject.value).flatMap(
+ (project) => tabIdListMapByProject.value[project]
+ )
+ );
+ keys.forEach((key) => {
+ const id = key.substring(prefix.length);
+ if (!flattenTabIdSet.has(id)) {
+ storage.remove(KEYS.tab(id));
+ }
+ });
+ };
+ // watch the field changes of a tab, store it to localStorage
+ // when needed, but not to frequently (for performance consideration)
+ const watchTab = (tab: SQLEditorTab, immediate: boolean) => {
+ // Use a throttled watcher to reduce the performance overhead when writing.
+ watchThrottled(
+ () => pick(tab, ...PERSISTENT_TAB_FIELDS) as PersistentTab,
+ (persistentTab) => {
+ storage.save<PersistentTab>(KEYS.tab(persistentTab.id), persistentTab);
+ },
+ { deep: true, immediate, throttle: 100, trailing: true }
+ );
+ };
+ // Load tabs session from localStorage
+ // Reset if failed
+ const initAll = () => {
+ const projects = Object.keys(tabIdListMapByProject.value);
+ // initialize all stored projects
+ projects.forEach((project) => {
+ maybeInitProject(project);
+ });
+ // initialize current project if needed (when it's not stored)
+ maybeInitProject(project.value);
+
+ _cleanup();
+ };
+ initAll();
+
+ const reset = () => {
+ storage.clear();
+ tabIdListMapByProject.value = {};
+ currentTabIdMapByProject.value = {};
+ initAll();
+ };
+
+ // some shortcuts
+ const isDisconnected = computed(() => {
+ const tab = currentTab.value;
+ if (!tab) return true;
+ return isDisconnectedSQLEditorTab(tab);
+ });
+
+ return {
+ tabIdList,
+ tabList,
+ currentTabId,
+ currentTab,
+ tabById,
+ addTab,
+ removeTab,
+ updateTab,
+ updateCurrentTab,
+ setCurrentTabId,
+ selectOrAddSimilarNewTab,
+ maybeInitProject,
+ reset,
+ tabIdListMapByProject,
+ currentTabIdMapByProject,
+ isDisconnected,
+ };
+});
+
+export const useCurrentSQLEditorTab = () => {
+ return storeToRefs(useSQLEditorTabStore()).currentTab;
+};
+
+export const isSQLEditorTabClosable = (tab: SQLEditorTab) => {
+ const { tabList } = useSQLEditorTabStore();
+
+ if (tabList.length > 1) {
+ // Not the only one tab
+ return true;
+ }
+ if (tabList.length === 1) {
+ // It's the only one tab, and it's closable if it's a sheet tab
+ return !!tab.sheet;
+ }
+ return false;
+};
+
+export const useSQLEditorConnectionDetail = (
+ connection: MaybeRef<SQLEditorConnection>
+) => {
+ const instance = computed(() => {
+ return useInstanceV1Store().getInstanceByName(unref(connection).instance);
+ });
+
+ const database = computed(() => {
+ return useDatabaseV1Store().getDatabaseByName(unref(connection).database);
+ });
+
+ const environment = computed(() => {
+ return unref(connection).database
+ ? instance.value.environmentEntity
+ : database.value.effectiveEnvironmentEntity;
+ });
+
+ return { connection, instance, database, environment };
+};
+
+export const useConnectionOfCurrentSQLEditorTab = () => {
+ const store = useSQLEditorTabStore();
+ const connection = computed(() => {
+ return store.currentTab?.connection ?? emptySQLEditorConnection();
+ });
+
+ const { instance, database, environment } =
+ useSQLEditorConnectionDetail(connection);
+
+ return { connection, instance, database, environment };
+};
+
+export const resolveOpeningDatabaseListFromSQLEditorTabList = () => {
+ const { tabList } = useSQLEditorTabStore();
+ return uniqBy(
+ tabList.flatMap<SQLEditorTreeNodeMeta<"database">>((tab) => {
+ const { database } = tab.connection;
+ if (database) {
+ const db = useDatabaseV1Store().getDatabaseByName(database);
+ return [{ type: "database", target: db }];
+ }
+ return [];
+ }),
+ (meta) => meta.target.name
+ );
+};
diff --git a/frontend/src/store/modules/sqlEditorTree.ts b/frontend/src/store/modules/sqlEditor/tree.ts
similarity index 63%
rename from frontend/src/store/modules/sqlEditorTree.ts
rename to frontend/src/store/modules/sqlEditor/tree.ts
index 4fcbcae781..19717459db 100644
--- a/frontend/src/store/modules/sqlEditorTree.ts
+++ b/frontend/src/store/modules/sqlEditor/tree.ts
@@ -1,6 +1,6 @@
import { useLocalStorage } from "@vueuse/core";
-import { cloneDeep, head, isFunction, orderBy, uniqBy } from "lodash-es";
-import { defineStore } from "pinia";
+import { cloneDeep, isFunction, orderBy } from "lodash-es";
+import { defineStore, storeToRefs } from "pinia";
import { v4 as uuidv4 } from "uuid";
import { computed, reactive, ref, watch } from "vue";
import {
@@ -15,15 +15,10 @@ import {
isValidSQLEditorTreeFactor as isValidFactor,
extractSQLEditorLabelFactor as extractLabelFactor,
unknownEnvironment,
- UNKNOWN_ID,
- SQLEditorTreeNodeMeta as NodeMeta,
- ExpandableTreeNodeTypes,
RichSchemaMetadata,
RichTableMetadata,
- SQLEditorTreeNodeType,
StatefulSQLEditorTreeFactor as StatefulFactor,
LeafTreeNodeTypes,
- Connection,
DEFAULT_PROJECT_V1_NAME,
RichViewMetadata,
TextTarget,
@@ -31,40 +26,27 @@ import {
RichExternalTableMetadata,
} from "@/types";
import { Environment } from "@/types/proto/v1/environment_service";
-import { emptyConnection, getSemanticLabelValue, groupBy } from "@/utils";
-import { useFilterStore } from "./filter";
-import { useTabStore } from "./tab";
+import { getSemanticLabelValue, groupBy } from "@/utils";
+import { useFilterStore } from "../filter";
import {
- useActuatorV1Store,
- useDBSchemaV1Store,
- useDatabaseV1Store,
useEnvironmentV1Store,
useInstanceV1Store,
useProjectV1Store,
-} from "./v1";
+} from "../v1";
+import { useSQLEditorStore } from "./editor";
export const ROOT_NODE_ID = "ROOT";
-const defaultProjectFactor: StatefulFactor = {
- factor: "project",
- disabled: false,
-};
-
const defaultEnvironmentFactor: StatefulFactor = {
factor: "environment",
disabled: false,
};
-export const useSQLEditorTreeStore = defineStore("SQL-Editor-Tree", () => {
- const actuatorStore = useActuatorV1Store();
+export const useSQLEditorTreeStore = defineStore("sqlEditorTree", () => {
const { filter } = useFilterStore();
const defaultFactorList = (): StatefulFactor[] => {
- if (actuatorStore.customTheme === "lixiang") {
- return [defaultEnvironmentFactor];
- } else {
- return [defaultProjectFactor];
- }
+ return [defaultEnvironmentFactor];
};
const factorListInLocalStorage = useLocalStorage<StatefulFactor[]>(
@@ -101,7 +83,10 @@ export const useSQLEditorTreeStore = defineStore("SQL-Editor-Tree", () => {
);
const nodeListMapById = reactive(new Map<string, TreeNode[]>());
// states
- const databaseList = ref<ComposedDatabase[]>([]);
+ // re-expose `databaseList`, `project`, `currentProject` from sqlEditor store for shortcuts
+ const { databaseList, project, currentProject } = storeToRefs(
+ useSQLEditorStore()
+ );
const factorList = ref<StatefulFactor[]>(
cloneDeep(factorListInLocalStorage.value)
);
@@ -112,8 +97,8 @@ export const useSQLEditorTreeStore = defineStore("SQL-Editor-Tree", () => {
return database.name === filter.database;
});
}
- if (filter.project || selectedProject.value) {
- const projectName = filter.project ?? selectedProject.value?.name;
+ if (filter.project || currentProject.value) {
+ const projectName = filter.project ?? currentProject.value?.name;
return databaseList.value.filter((database) => {
return database.project === projectName;
});
@@ -123,15 +108,16 @@ export const useSQLEditorTreeStore = defineStore("SQL-Editor-Tree", () => {
});
const filteredFactorList = computed(() => {
return factorList.value
- .filter((sf) =>
- selectedProject.value ? sf.factor !== defaultProjectFactor.factor : true
- )
+ .filter((sf) => {
+ if (!currentProject.value) {
+ return true;
+ }
+ return sf.factor !== "project";
+ })
.filter((sf) => !sf.disabled)
.map((sf) => sf.factor);
});
- const selectedProject = ref<ComposedProject>();
const state = ref<TreeState>("UNSET");
- const expandedKeys = ref<string[]>([]); // mixed factor type
const tree = ref<TreeNode[]>([]);
const collectNode = <T extends NodeType>(node: TreeNode<T>) => {
@@ -146,101 +132,18 @@ export const useSQLEditorTreeStore = defineStore("SQL-Editor-Tree", () => {
target: NodeTarget<T>
) => {
const id = idForSQLEditorTreeNodeTarget(type, target);
- return nodeListMapById.get(id) ?? [];
+ return (nodeListMapById.get(id) ?? []) as TreeNode<T>[];
};
- const openNodesRecursively = (node: TreeNode, keys: Set<string>) => {
- if (ExpandableTreeNodeTypes.includes(node.meta.type)) {
- keys.add(node.key);
- }
- if (node.parent) {
- openNodesRecursively(node.parent, keys);
- }
- };
- const expandNodes = <T extends SQLEditorTreeNodeType>(
- type: T,
- target: NodeTarget<T>
- ) => {
- const nodes = nodesByTarget(type, target);
- const keys = new Set(expandedKeys.value);
- nodes.forEach((node) => {
- keys.add(node.key);
- });
- expandedKeys.value = Array.from(keys);
- };
const buildTree = () => {
nodeListMapById.clear();
tree.value = buildTreeImpl(
filteredDatabaseList.value,
filteredFactorList.value
);
- const openingDatabaseList = resolveOpeningDatabaseListFromTabList();
- const keys = new Set<string>();
- // Recursively expand opening databases' parent nodes
- openingDatabaseList.forEach((meta) => {
- const db = meta.target;
- const nodes = nodesByTarget("database", db);
- nodes.forEach((node) => openNodesRecursively(node, keys));
- });
- const tab = useTabStore().currentTab;
- // Expand current tab's connected database node
- if (
- tab.connection.databaseId &&
- tab.connection.databaseId !== String(UNKNOWN_ID)
- ) {
- const db = useDatabaseV1Store().getDatabaseByUID(
- tab.connection.databaseId
- );
- const node = head(nodesByTarget("database", db));
- if (node) {
- keys.add(node.key);
- }
- }
- expandedKeys.value = Array.from(keys);
- };
- const fetchConnectionByInstanceIdAndDatabaseId = async (
- instanceId: string,
- databaseId: string
- ): Promise<Connection> => {
- try {
- const [db, _] = await Promise.all([
- useDatabaseV1Store().getOrFetchDatabaseByUID(
- databaseId,
- true /* silent */
- ),
- useInstanceV1Store().getOrFetchInstanceByUID(instanceId),
- ]);
- await useDBSchemaV1Store().getOrFetchTableList(db.name);
-
- return {
- instanceId,
- databaseId,
- };
- } catch {
- // Fallback to disconnected if error occurs such as 404.
- return { instanceId: String(UNKNOWN_ID), databaseId: String(UNKNOWN_ID) };
- }
- };
- const fetchConnectionByInstanceId = async (
- instanceId: string
- ): Promise<Connection> => {
- try {
- await useInstanceV1Store().getOrFetchInstanceByUID(instanceId);
-
- return {
- instanceId,
- databaseId: String(UNKNOWN_ID),
- };
- } catch {
- // Fallback to disconnected if error occurs such as 404.
- return { instanceId: String(UNKNOWN_ID), databaseId: String(UNKNOWN_ID) };
- }
};
const cleanup = () => {
- databaseList.value = [];
- selectedProject.value = undefined;
tree.value = [];
- expandedKeys.value = [];
factorList.value = defaultFactorList();
nodeListMapById.clear();
state.value = "UNSET";
@@ -253,82 +156,40 @@ export const useSQLEditorTreeStore = defineStore("SQL-Editor-Tree", () => {
},
{ immediate: true, deep: true }
);
+ watch(
+ project,
+ (project) => {
+ if (project) {
+ const position = factorList.value.findIndex(
+ (sf) => sf.factor === "project"
+ );
+ if (position > 0) {
+ factorList.value.splice(position, 1);
+ if (factorList.value.length === 0) {
+ factorList.value = defaultFactorList();
+ }
+ }
+ }
+ },
+ {
+ immediate: true,
+ }
+ );
return {
- expandedKeys,
databaseList,
factorList,
filteredFactorList,
- selectedProject,
+ currentProject: currentProject,
state,
tree,
collectNode,
nodesByTarget,
- expandNodes,
buildTree,
- fetchConnectionByInstanceIdAndDatabaseId,
- fetchConnectionByInstanceId,
cleanup,
};
});
-export const searchConnectionByName = (
- instanceId: string,
- databaseId: string,
- instanceName: string,
- databaseName: string
-): Connection => {
- const connection = emptyConnection();
- const store = useSQLEditorTreeStore();
-
- if (instanceId !== String(UNKNOWN_ID)) {
- // If we found instanceId and/or databaseId, use the IDs first.
- connection.instanceId = instanceId;
- if (databaseId !== String(UNKNOWN_ID)) {
- connection.databaseId = databaseId;
- }
-
- return connection;
- }
-
- // Search the instance and database by name otherwise.
- // Remain this part for legacy sheet support.
- const rootNodes = store.tree;
- for (let i = 0; i < rootNodes.length; i++) {
- const maybeInstanceNode = rootNodes[i];
- if (maybeInstanceNode.meta.type !== "instance") {
- // Skip if we met dirty data.
- continue;
- }
- if (maybeInstanceNode.label === instanceName) {
- connection.instanceId = (
- maybeInstanceNode.meta.target as ComposedInstance
- ).uid;
- if (databaseName) {
- const { children = [] } = maybeInstanceNode;
- for (let j = 0; j < children.length; j++) {
- const maybeDatabaseNode = children[j];
- if (maybeDatabaseNode.meta.type !== "database") {
- // Skip if we met dirty data.
- continue;
- }
- if (maybeDatabaseNode.label === databaseName) {
- connection.databaseId = (
- maybeDatabaseNode.meta.target as ComposedDatabase
- ).uid;
- // Don't go further since we've found the databaseId
- break;
- }
- }
- }
- // Don't go further since we've found the instanceId
- break;
- }
- }
-
- return connection;
-};
-
export const keyForSQLEditorTreeNodeTarget = <T extends NodeType>(
type: T,
target: NodeTarget<T>
@@ -391,12 +252,12 @@ export const idForSQLEditorTreeNodeTarget = <T extends NodeType>(
return `labels/${kv.key}:${kv.value}`;
}
if (type === "expandable-text") {
- const { text, type } = target as NodeTarget<"expandable-text">;
- return `texts-${type}/${typeof text === "function" ? text() : text}`;
+ const { text, id, type } = target as NodeTarget<"expandable-text">;
+ return `texts-${type}/${id}/${typeof text === "function" ? text() : text}`;
}
if (type === "dummy") {
- const dummyType = (target as NodeTarget<"dummy">).type;
- return `dummy-${dummyType}`;
+ const { type, id } = target as NodeTarget<"dummy">;
+ return `dummy-${type}/${id}`;
}
throw new Error(
@@ -604,18 +465,3 @@ const getSemanticFactorValue = (db: ComposedDatabase, factor: Factor) => {
console.error("should never reach this line", db, factor);
return "";
};
-
-export const resolveOpeningDatabaseListFromTabList = () => {
- const { tabList } = useTabStore();
- return uniqBy(
- tabList.flatMap<NodeMeta<"database">>((tab) => {
- const { databaseId } = tab.connection;
- if (databaseId !== String(UNKNOWN_ID)) {
- const db = useDatabaseV1Store().getDatabaseByUID(databaseId);
- return [{ type: "database", target: db }];
- }
- return [];
- }),
- (meta) => meta.target.name
- );
-};
diff --git a/frontend/src/store/modules/v1/webTerminal.ts b/frontend/src/store/modules/sqlEditor/webTerminal.ts
similarity index 88%
rename from frontend/src/store/modules/v1/webTerminal.ts
rename to frontend/src/store/modules/sqlEditor/webTerminal.ts
index 684b5e1403..92aeeba5de 100644
--- a/frontend/src/store/modules/v1/webTerminal.ts
+++ b/frontend/src/store/modules/sqlEditor/webTerminal.ts
@@ -3,16 +3,16 @@ import { uniqueId } from "lodash-es";
import { ClientError, Status } from "nice-grpc-common";
import { defineStore } from "pinia";
import { fromEventPattern, map, Observable, Subscription } from "rxjs";
-import { markRaw, ref } from "vue";
+import { markRaw, ref, shallowRef } from "vue";
import { useCancelableTimeout } from "@/composables/useCancelableTimeout";
import {
SQLResultSetV1,
StreamingQueryController,
- TabInfo,
+ SQLEditorTab,
UNKNOWN_ID,
WebTerminalQueryItemV1,
- WebTerminalQueryParamsV1,
WebTerminalQueryState,
+ SQLEditorQueryParams,
} from "@/types";
import { Duration } from "@/types/proto/google/protobuf/duration";
import {
@@ -24,18 +24,17 @@ import {
extractGrpcErrorMessage,
getErrorCode as extractGrpcStatusCode,
} from "@/utils/grpcweb";
-import { useDatabaseV1Store } from "./database";
-import { useInstanceV1Store } from "./instance";
+import { useDatabaseV1Store, useInstanceV1Store } from "../v1";
const ENDPOINT = "/v1:adminExecute";
const SIG_ABORT = 3000 + Status.ABORTED;
const QUERY_TIMEOUT_MS = 5000;
const MAX_QUERY_ITEM_COUNT = 20;
-export const useWebTerminalV1Store = defineStore("webTerminal_v1", () => {
- const map = ref(new Map<string, WebTerminalQueryState>());
+export const useWebTerminalStore = defineStore("webTerminal", () => {
+ const map = shallowRef(new Map<string, WebTerminalQueryState>());
- const getQueryStateByTab = (tab: TabInfo) => {
+ const getQueryStateByTab = (tab: SQLEditorTab) => {
const existed = map.value.get(tab.id);
if (existed) return existed;
@@ -45,14 +44,14 @@ export const useWebTerminalV1Store = defineStore("webTerminal_v1", () => {
return qs;
};
- const clearQueryStateByTab = (tab: TabInfo) => {
- map.value.delete(tab.id);
+ const clearQueryStateByTab = (id: string) => {
+ map.value.delete(id);
};
return { getQueryStateByTab, clearQueryStateByTab };
});
-const createQueryState = (tab: TabInfo): WebTerminalQueryState => {
+const createQueryState = (tab: SQLEditorTab): WebTerminalQueryState => {
return {
tab,
queryItemList: ref([createInitialQueryItemByTab(tab)]),
@@ -61,7 +60,9 @@ const createQueryState = (tab: TabInfo): WebTerminalQueryState => {
};
};
-const createInitialQueryItemByTab = (tab: TabInfo): WebTerminalQueryItemV1 => {
+const createInitialQueryItemByTab = (
+ tab: SQLEditorTab
+): WebTerminalQueryItemV1 => {
return createQueryItemV1(tab.statement);
};
@@ -74,10 +75,10 @@ export const createQueryItemV1 = (
status,
});
-const createStreamingQueryController = (tab: TabInfo) => {
+const createStreamingQueryController = (tab: SQLEditorTab) => {
const status: StreamingQueryController["status"] = ref("DISCONNECTED");
const events: StreamingQueryController["events"] = markRaw(new Emittery());
- const input$ = fromEventPattern<WebTerminalQueryParamsV1>(
+ const input$ = fromEventPattern<SQLEditorQueryParams>(
(handler) => events.on("query", handler),
(handler) => events.off("query", handler)
);
@@ -289,19 +290,18 @@ export const mockAffectedV1Rows0 = (): QueryResult => {
};
const mapRequest = (
- tab: TabInfo,
- params: WebTerminalQueryParamsV1
+ tab: SQLEditorTab,
+ params: SQLEditorQueryParams
): AdminExecuteRequest => {
- const { option, query } = params;
+ const { connection, statement, explain } = params;
- const { instanceId, databaseId } = tab.connection;
- const instance = useInstanceV1Store().getInstanceByUID(instanceId);
- const database = useDatabaseV1Store().getDatabaseByUID(databaseId);
+ const instance = useInstanceV1Store().getInstanceByName(connection.instance);
+ const database = useDatabaseV1Store().getDatabaseByName(connection.database);
const request = AdminExecuteRequest.fromJSON({
name: instance.name,
connectionDatabase:
database.uid === String(UNKNOWN_ID) ? "" : database.databaseName,
- statement: option?.explain ? `EXPLAIN ${query}` : query,
+ statement: explain ? `EXPLAIN ${statement}` : statement,
});
return request;
};
diff --git a/frontend/src/store/modules/tab.ts b/frontend/src/store/modules/tab.ts
deleted file mode 100644
index 202c77d131..0000000000
--- a/frontend/src/store/modules/tab.ts
+++ /dev/null
@@ -1,280 +0,0 @@
-import { watchThrottled } from "@vueuse/core";
-import { pick } from "lodash-es";
-import { defineStore } from "pinia";
-import { computed, reactive, ref, toRef, watch } from "vue";
-import { TabInfo, CoreTabInfo, AnyTabInfo, TabMode } from "@/types";
-import {
- getDefaultTab,
- isTempTab,
- isSimilarTab,
- WebStorageHelper,
- isDisconnectedTab,
-} from "@/utils";
-import { useWebTerminalV1Store } from "./v1";
-import { useWorkSheetStore } from "./v1/worksheet";
-
-const LOCAL_STORAGE_KEY_PREFIX = "bb.sql-editor.tab-list";
-const KEYS = {
- tabIdList: "tab-id-list",
- currentTabId: "current-tab-id",
- tab: (id: string) => `tab.${id}`,
-};
-
-// Only store the core fields of a tab.
-// Don't store anything which might be too large.
-const PERSISTENT_TAB_FIELDS = [
- "id",
- "name",
- "connection",
- "isSaved",
- "savedAt",
- "statement",
- "sheetName",
- "mode",
- "batchQueryContext",
-] as const;
-type PersistentTabInfo = Pick<TabInfo, typeof PERSISTENT_TAB_FIELDS[number]>;
-
-export const useTabStore = defineStore("tab", () => {
- const storage = new WebStorageHelper("bb.sql-editor.tab-list", localStorage);
-
- // states
- // We store the tabIdList and the tabs separately.
- // This index-entity modeling enables us to update one tab entity at a time,
- // and reduce the performance costing while writing localStorage.
- const tabs = ref(new Map<string, TabInfo>());
- const tabIdList = ref<string[]>([]);
- const currentTabId = ref<string>();
-
- // getters
- const getTabById = (id: string) => {
- return tabs.value.get(id) ?? getDefaultTab();
- };
- const tabList = computed((): TabInfo[] => tabIdList.value.map(getTabById));
- const currentTab = computed((): TabInfo => {
- return getTabById(currentTabId.value ?? "");
- });
- const isDisconnected = computed((): boolean => {
- return isDisconnectedTab(currentTab.value);
- });
-
- // actions
- const addTab = (payload?: AnyTabInfo, beside = false) => {
- const newTab = reactive<TabInfo>({
- ...getDefaultTab(),
- ...payload,
- });
-
- const { id } = newTab;
- const index = tabIdList.value.indexOf(currentTabId.value ?? "");
- if (beside && index >= 0) {
- tabIdList.value.splice(index + 1, 0, id);
- } else {
- tabIdList.value.push(id);
- }
- currentTabId.value = id;
- tabs.value.set(id, newTab);
-
- watchTab(newTab, false);
- };
- const removeTab = (tab: TabInfo) => {
- const id = tab.id;
- const index = tabIdList.value.indexOf(id);
- if (index >= 0) {
- tabIdList.value.splice(index, 1);
- tabs.value.delete(id);
- storage.remove(KEYS.tab(id));
-
- if (tab.mode === TabMode.Admin) {
- useWebTerminalV1Store().clearQueryStateByTab(tab);
- }
- }
- };
- const updateCurrentTab = (payload: AnyTabInfo) => {
- updateTab(currentTabId.value ?? "", payload);
- };
- const updateTab = (tabId: string, payload: AnyTabInfo) => {
- const tab = getTabById(tabId);
- Object.assign(tab, payload);
- };
- const setCurrentTabId = (id: string) => {
- currentTabId.value = id;
- };
- const selectOrAddSimilarTab = (
- tab: CoreTabInfo,
- beside = false,
- defaultName?: string
- ) => {
- if (isDisconnected.value) {
- if (defaultName) {
- currentTab.value.name = defaultName;
- }
- return;
- }
- if (isSimilarTab(tab, currentTab.value)) {
- return;
- }
- const similarTab = tabList.value.find((tmp) => isSimilarTab(tmp, tab));
- if (similarTab) {
- setCurrentTabId(similarTab.id);
- } else {
- addTab(tab, beside);
- if (defaultName) {
- currentTab.value.name = defaultName;
- }
- }
- };
- const selectOrAddTempTab = (newTab?: AnyTabInfo) => {
- if (isDisconnected.value) {
- return;
- }
- if (isTempTab(currentTab.value)) {
- return;
- }
- const tempTab = tabList.value.find(isTempTab);
- if (tempTab) {
- setCurrentTabId(tempTab.id);
- } else {
- addTab(newTab);
- }
- };
- const _cleanup = (tabIdList: string[]) => {
- const prefix = `${LOCAL_STORAGE_KEY_PREFIX}.tab.`;
- const keys = storage.keys().filter((key) => key.startsWith(prefix));
- keys.forEach((key) => {
- const id = key.substring(prefix.length);
- if (tabIdList.indexOf(id) < 0) {
- storage.remove(KEYS.tab(id));
- }
- });
- };
-
- // watchers
- const watchTab = (tab: TabInfo, immediate: boolean) => {
- const dirtyFields = [
- () => tab.name,
- () => tab.sheetName,
- () => tab.statement,
- () => tab.connection,
- () => tab.batchQueryContext,
- ];
- watch(dirtyFields, () => {
- tab.isFreshNew = false;
- });
-
- // Use a throttled watcher to reduce the performance overhead when writing.
- watchThrottled(
- () => pick(tab, ...PERSISTENT_TAB_FIELDS),
- (tabPartial: PersistentTabInfo) => {
- storage.save(KEYS.tab(tabPartial.id), tabPartial);
- },
- { deep: true, immediate, throttle: 100, trailing: true }
- );
- };
-
- // Load session from local storage.
- // Reset if failed.
- const init = () => {
- // Load tabIdList and currentTabId
- tabIdList.value = storage.load(KEYS.tabIdList, []);
- currentTabId.value = storage.load(KEYS.currentTabId, "");
- if (tabIdList.value.indexOf(currentTabId.value) < 0) {
- // currentTabId is not in tabIdList accidentally
- // fallback to the first tab
- currentTabId.value = tabIdList.value[0];
- }
-
- // Load tab details
- tabIdList.value.forEach((id) => {
- const tabPartial = storage.load<PersistentTabInfo | undefined>(
- KEYS.tab(id),
- undefined
- );
- maybeMigrateLegacyTab(storage, tabPartial);
- // Use a stored tab info if possible.
- // Fallback to getDefaultTab() otherwise.
- const tab = reactive<TabInfo>({
- ...getDefaultTab(),
- ...tabPartial,
- id,
- });
- // Legacy id support
- tab.connection.databaseId = String(tab.connection.databaseId);
- tab.connection.instanceId = String(tab.connection.instanceId);
- watchTab(tab, false);
- tabs.value.set(id, tab);
- });
-
- // Fetch opening sheets if needed
- const sheetV1Store = useWorkSheetStore();
- tabList.value.forEach((tab) => {
- if (tab.sheetName) {
- sheetV1Store.getOrFetchSheetByName(tab.sheetName);
- }
- });
-
- // Clean up unused stored tabs
- _cleanup(tabIdList.value);
-
- watch(
- currentTabId,
- (id) => {
- storage.save(KEYS.currentTabId, id);
- },
- { immediate: true }
- );
- watch(
- tabIdList,
- (idList) => {
- storage.save(KEYS.tabIdList, idList);
- },
- { deep: true, immediate: true }
- );
- };
- init();
-
- const reset = () => {
- storage.clear();
- init();
- };
-
- // exposure
- return {
- tabIdList,
- tabList,
- currentTabId,
- currentTab,
- isDisconnected,
- getTabById,
- addTab,
- removeTab,
- updateTab,
- updateCurrentTab,
- setCurrentTabId,
- selectOrAddTempTab,
- selectOrAddSimilarTab,
- reset,
- };
-});
-
-export const useCurrentTab = () => {
- const store = useTabStore();
- return toRef(store, "currentTab");
-};
-
-const maybeMigrateLegacyTab = (
- storage: WebStorageHelper,
- tab: PersistentTabInfo | undefined
-) => {
- if (!tab) return;
- const { connection } = tab;
- if (
- typeof connection.databaseId === "number" ||
- typeof connection.instanceId === "number"
- ) {
- connection.databaseId = String(connection.databaseId);
- connection.instanceId = String(connection.instanceId);
- storage.save(KEYS.tab(tab.id), tab);
- }
- return tab;
-};
diff --git a/frontend/src/store/modules/v1/index.ts b/frontend/src/store/modules/v1/index.ts
index 662b1b23ae..7d681a3f44 100644
--- a/frontend/src/store/modules/v1/index.ts
+++ b/frontend/src/store/modules/v1/index.ts
@@ -17,7 +17,6 @@ export * from "./experimental-issue";
export * from "./subscription";
export * from "./actuator";
export * from "./sql";
-export * from "./webTerminal";
export * from "./repository";
export * from "./vcs";
export * from "./changeHistory";
diff --git a/frontend/src/store/modules/v1/worksheet.ts b/frontend/src/store/modules/v1/worksheet.ts
index ce0a2a8b8c..78d6fc3932 100644
--- a/frontend/src/store/modules/v1/worksheet.ts
+++ b/frontend/src/store/modules/v1/worksheet.ts
@@ -15,7 +15,7 @@ import {
getStatementSize,
} from "@/utils";
import { useCurrentUserV1 } from "../auth";
-import { useTabStore } from "../tab";
+import { useSQLEditorTabStore } from "../sqlEditor";
import { getUserEmailFromIdentifier } from "./common";
type WorksheetView = "FULL" | "BASIC";
@@ -221,17 +221,20 @@ export const useWorkSheetStore = defineStore("worksheet_v1", () => {
});
export const useWorkSheetAndTabStore = defineStore("worksheet_and_tab", () => {
- const tabStore = useTabStore();
+ const tabStore = useSQLEditorTabStore();
const sheetStore = useWorkSheetStore();
const me = useCurrentUserV1();
const currentSheet = computed(() => {
const tab = tabStore.currentTab;
- const name = tab.sheetName;
- if (!name) {
+ if (!tab) {
return undefined;
}
- return sheetStore.getSheetByName(name);
+ const { sheet } = tab;
+ if (!sheet) {
+ return undefined;
+ }
+ return sheetStore.getSheetByName(sheet);
});
const isCreator = computed(() => {
diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts
index 66aac1a2e0..f801ca9417 100644
--- a/frontend/src/types/index.ts
+++ b/frontend/src/types/index.ts
@@ -27,8 +27,6 @@ export * from "./sqlAdvice";
export * from "./store";
export * from "./vcs";
export * from "./sqlEditor";
-export * from "./sqlEditorTree";
-export * from "./tab";
export * from "./sheet";
export * from "./sqlReview";
export * from "./utils";
diff --git a/frontend/src/types/sqlEditor.ts b/frontend/src/types/sqlEditor/editor.ts
similarity index 72%
rename from frontend/src/types/sqlEditor.ts
rename to frontend/src/types/sqlEditor/editor.ts
index 459a2258f7..7f66f88a59 100644
--- a/frontend/src/types/sqlEditor.ts
+++ b/frontend/src/types/sqlEditor/editor.ts
@@ -1,6 +1,6 @@
import type * as monaco from "monaco-editor";
-import type { InstanceId, DatabaseId, EngineType } from "../types";
-import { Engine } from "./proto/v1/common";
+import type { EngineType } from "@/types";
+import { Engine } from "../proto/v1/common";
export type EditorModel = monaco.editor.ITextModel;
export type EditorPosition = monaco.Position;
@@ -71,8 +71,8 @@ export enum SortText {
KEYWORD = "3",
}
-export interface QueryHistory {
- name: string;
+export type SQLEditorQueryHistory = {
+ name: string; // Format: logs/{uid}
// Standard fields
// creator in users/{email} format.
@@ -82,9 +82,22 @@ export interface QueryHistory {
// Domain fields
statement: string;
durationNs: number;
- instanceName: string;
- databaseName: string;
- instanceId: InstanceId;
- databaseId: DatabaseId;
+ instance: string;
+ database: string;
error: string;
+};
+
+export interface SQLEditorConnection {
+ instance: string; // instance resource name, empty if not connected
+ database: string; // database resource name, empty if not connected to a database
+ dataSourceId?: string;
+ schema?: string;
+ table?: string;
}
+
+export type SQLEditorQueryParams = {
+ connection: SQLEditorConnection; // the connection snapshot of the query
+ statement: string; // the statement snapshot of the query
+ engine: Engine;
+ explain: boolean;
+};
diff --git a/frontend/src/types/sqlEditor/index.ts b/frontend/src/types/sqlEditor/index.ts
new file mode 100644
index 0000000000..6cad6a7266
--- /dev/null
+++ b/frontend/src/types/sqlEditor/index.ts
@@ -0,0 +1,3 @@
+export * from "./editor";
+export * from "./tab";
+export * from "./tree";
diff --git a/frontend/src/types/sqlEditor/tab.ts b/frontend/src/types/sqlEditor/tab.ts
new file mode 100644
index 0000000000..8b6832d847
--- /dev/null
+++ b/frontend/src/types/sqlEditor/tab.ts
@@ -0,0 +1,51 @@
+import { SQLResultSetV1 } from "../v1/sql";
+import { SQLEditorConnection, SQLEditorQueryParams } from "./editor";
+
+export type SQLEditorEditMode = "SQL-EDITOR" | "CHAT-TO-SQL";
+
+export type SQLEditorTabStatus =
+ | "NEW" // just created and untouched
+ | "DIRTY" // edited
+ | "CLEAN"; // saved to a remote sheet
+
+// STANDARD not supported by backend so far
+export type SQLEditorTabMode = "STANDARD" | "READONLY" | "ADMIN";
+export const DEFAULT_SQL_EDITOR_TAB_MODE: SQLEditorTabMode = "READONLY";
+
+export type BatchQueryContext = {
+ // databases is used to store the selected database names.
+ // Format: instances/{instance}/databases/{database}
+ databases: string[];
+};
+
+export type SQLEditorTabQueryContext = {
+ beginTimestampMS: number;
+ abortController: AbortController;
+ status: "IDLE" | "EXECUTING";
+
+ params: SQLEditorQueryParams;
+ results: Map<string /* database or instance */, SQLResultSetV1>;
+};
+
+export type SQLEditorTab = {
+ // basic fields
+ id: string; // uuid
+ title: string; // display title, should be synced with sheet's title once saved
+ sheet: string; // if ref to a local or remote sheet
+ connection: SQLEditorConnection;
+ status: SQLEditorTabStatus;
+ statement: string; // local editing statement, might be out-of-sync to ref sheet's statement
+ selectedStatement: string;
+ mode: SQLEditorTabMode;
+ editMode: SQLEditorEditMode;
+
+ // SQL query related fields
+ // won't be saved to localStorage
+ queryContext?: SQLEditorTabQueryContext;
+ batchQueryContext?: BatchQueryContext;
+};
+
+export type CoreSQLEditorTab = Pick<
+ SQLEditorTab,
+ "sheet" | "connection" | "mode"
+>;
diff --git a/frontend/src/types/sqlEditorTree.ts b/frontend/src/types/sqlEditor/tree.ts
similarity index 92%
rename from frontend/src/types/sqlEditorTree.ts
rename to frontend/src/types/sqlEditor/tree.ts
index f897830aa4..7f34ba180e 100644
--- a/frontend/src/types/sqlEditorTree.ts
+++ b/frontend/src/types/sqlEditor/tree.ts
@@ -2,16 +2,16 @@ import { TreeOption } from "naive-ui";
import { RenderFunction } from "vue";
import { t } from "@/plugins/i18n";
import { useSQLEditorTreeStore } from "@/store";
-import { Engine } from "./proto/v1/common";
+import { Engine } from "../proto/v1/common";
import {
ExternalTableMetadata,
SchemaMetadata,
TableMetadata,
TablePartitionMetadata,
ViewMetadata,
-} from "./proto/v1/database_service";
-import { Environment } from "./proto/v1/environment_service";
-import { ComposedDatabase, ComposedInstance, ComposedProject } from "./v1";
+} from "../proto/v1/database_service";
+import { Environment } from "../proto/v1/environment_service";
+import { ComposedDatabase, ComposedInstance, ComposedProject } from "../v1";
export type SQLEditorTreeFactor =
| "project"
@@ -66,11 +66,21 @@ export type RichViewMetadata = {
};
export type TextTarget<E extends boolean> = {
expandable: E;
+ id: string;
type: SQLEditorTreeNodeType;
text: string | (() => string);
render?: RenderFunction;
searchable?: boolean;
};
+export type LabelTarget = {
+ key: string;
+ value: string;
+};
+export type DummyTarget = {
+ id: string;
+ type: SQLEditorTreeNodeType;
+ error?: unknown;
+};
export type SQLEditorTreeNodeTarget<T extends SQLEditorTreeNodeType = any> =
T extends "project"
@@ -92,11 +102,11 @@ export type SQLEditorTreeNodeTarget<T extends SQLEditorTreeNodeType = any> =
: T extends "view"
? RichViewMetadata
: T extends "label"
- ? { key: string; value: string }
+ ? LabelTarget
: T extends "expandable-text"
? TextTarget<true>
: T extends "dummy"
- ? { type: SQLEditorTreeNodeType; error?: unknown }
+ ? DummyTarget
: never;
export type SQLEditorTreeState = "UNSET" | "LOADING" | "READY";
@@ -126,6 +136,8 @@ export const isValidSQLEditorTreeFactor = (
export const ExpandableTreeNodeTypes: readonly SQLEditorTreeNodeType[] = [
"instance",
+ "database",
+ "schema",
"environment",
"project",
"table",
@@ -157,7 +169,7 @@ export const readableSQLEditorTreeFactor = (
) => {
const treeStore = useSQLEditorTreeStore();
if (factor === "project") {
- if (treeStore.selectedProject) {
+ if (treeStore.currentProject) {
return t("common.database");
} else {
return t("common.project");
diff --git a/frontend/src/types/tab.ts b/frontend/src/types/tab.ts
deleted file mode 100644
index 0d9449a323..0000000000
--- a/frontend/src/types/tab.ts
+++ /dev/null
@@ -1,71 +0,0 @@
-import { SQLResultSetV1 } from "./v1/sql";
-
-export type ExecuteConfig = {
- databaseType: string;
-};
-
-export type ExecuteOption = {
- explain: boolean;
-};
-
-export type Connection = {
- instanceId: string;
- databaseId: string;
- dataSourceId?: string;
- schema?: string;
- table?: string;
-};
-
-export enum TabMode {
- ReadOnly = 1,
- Admin = 2,
-}
-
-export type TabSheetType =
- | "TEMP" // Unsaved local sheet
- | "CLEAN" // Saved and untouched sheet
- | "DIRTY"; // Saved remotely, touched and unsaved locally
-
-export type EditMode = "SQL-EDITOR" | "CHAT-TO-SQL";
-
-export interface BatchQueryContext {
- // selectedDatabaseNames is used to store the selected database names.
- // Format: instances/{instance}/databases/{database}
- selectedDatabaseNames: string[];
-}
-
-export type QueryContext = {
- beginTimestampMS: number;
- abortController: AbortController;
-};
-
-export interface TabInfo {
- id: string;
- name: string;
- connection: Connection;
- isSaved: boolean;
- savedAt: string;
- statement: string;
- selectedStatement: string;
- mode: TabMode;
- editMode: EditMode;
- executeParams?: {
- query: string;
- config: ExecuteConfig;
- option?: Partial<ExecuteOption>;
- };
- isExecutingSQL: boolean;
- sheetName?: string;
- isFreshNew?: boolean;
- // batchQueryContext saves the context of batch query, including the selected labels.
- batchQueryContext?: BatchQueryContext;
- // queryContext saves the context of a query, including beginTimestampMS and abortController
- queryContext?: QueryContext;
- // databaseQueryResultMap is used to store the query result of each database.
- // It's used for the case that the user selects multiple databases to query.
- // The key is the databaseName. Format: instances/{instance}/databases/{database}
- databaseQueryResultMap?: Map<string, SQLResultSetV1>;
-}
-
-export type CoreTabInfo = Pick<TabInfo, "connection" | "sheetName" | "mode">;
-export type AnyTabInfo = Partial<TabInfo>;
diff --git a/frontend/src/types/v1/webTerminal.ts b/frontend/src/types/v1/webTerminal.ts
index 1c590d9960..f56112c98c 100644
--- a/frontend/src/types/v1/webTerminal.ts
+++ b/frontend/src/types/v1/webTerminal.ts
@@ -1,6 +1,7 @@
import Emittery from "emittery";
import { ComputedRef, Ref } from "vue";
-import { ExecuteConfig, ExecuteOption, TabInfo } from "../tab";
+import { SQLEditorQueryParams } from "../sqlEditor";
+import { SQLEditorTab } from "../sqlEditorTab";
import { SQLResultSetV1 } from "./sql";
/**
@@ -18,16 +19,10 @@ import { SQLResultSetV1 } from "./sql";
* -(has a)> websocket streaming connection
*/
-export type WebTerminalQueryParamsV1 = {
- query: string;
- config: ExecuteConfig;
- option?: Partial<ExecuteOption>;
-};
-
export type WebTerminalQueryItemV1 = {
id: string;
sql: string;
- params?: WebTerminalQueryParamsV1;
+ params?: SQLEditorQueryParams;
resultSet?: SQLResultSetV1;
status: "IDLE" | "RUNNING" | "FINISHED";
};
@@ -40,7 +35,7 @@ export type QueryTimer = {
};
export type QueryEvents = Emittery<{
- query: WebTerminalQueryParamsV1;
+ query: SQLEditorQueryParams;
result: SQLResultSetV1;
}>;
@@ -51,7 +46,7 @@ export type StreamingQueryController = {
};
export type WebTerminalQueryState = {
- tab: TabInfo;
+ tab: SQLEditorTab;
queryItemList: Ref<WebTerminalQueryItemV1[]>;
controller: StreamingQueryController;
timer: QueryTimer;
diff --git a/frontend/src/utils/index.ts b/frontend/src/utils/index.ts
index 90f4833ad2..7f5bafc22f 100644
--- a/frontend/src/utils/index.ts
+++ b/frontend/src/utils/index.ts
@@ -16,7 +16,7 @@ export * from "./types";
export * from "./util";
export * from "./label";
export * from "./string";
-export * from "./tab";
+export * from "./sqlEditor";
export * from "./task";
export * from "./pev2";
export * from "./web-storage";
diff --git a/frontend/src/utils/sqlEditor.ts b/frontend/src/utils/sqlEditor.ts
new file mode 100644
index 0000000000..79f5adec16
--- /dev/null
+++ b/frontend/src/utils/sqlEditor.ts
@@ -0,0 +1,166 @@
+import dayjs from "dayjs";
+import { v1 as uuidv1 } from "uuid";
+import {
+ useDatabaseV1Store,
+ useInstanceV1Store,
+ useSQLEditorTabStore,
+} from "@/store";
+import {
+ ComposedDatabase,
+ ComposedInstance,
+ CoreSQLEditorTab,
+ DEFAULT_SQL_EDITOR_TAB_MODE,
+ SQLEditorConnection,
+ SQLEditorTab,
+ SQLEditorTabQueryContext,
+ UNKNOWN_ID,
+} from "@/types";
+import { Engine } from "@/types/proto/v1/common";
+import { instanceV1AllowsCrossDatabaseQuery } from "./v1/instance";
+
+export const defaultSQLEditorTab = (): SQLEditorTab => {
+ return {
+ id: uuidv1(),
+ title: defaultSQLEditorTabTitle(),
+ connection: emptySQLEditorConnection(),
+ statement: "",
+ selectedStatement: "",
+ status: "NEW",
+ mode: DEFAULT_SQL_EDITOR_TAB_MODE,
+ sheet: "",
+ editMode: "SQL-EDITOR",
+ };
+};
+
+export const defaultSQLEditorTabTitle = () => {
+ return dayjs().format("YYYY-MM-DD HH:mm");
+};
+export const emptySQLEditorConnection = (): SQLEditorConnection => {
+ return {
+ instance: "",
+ database: "",
+ };
+};
+
+export const connectionForSQLEditorTab = (tab: SQLEditorTab) => {
+ const target: {
+ instance: ComposedInstance | undefined;
+ database: ComposedDatabase | undefined;
+ } = {
+ instance: undefined,
+ database: undefined,
+ };
+ const { connection } = tab;
+ if (connection.database) {
+ const database = useDatabaseV1Store().getDatabaseByName(
+ connection.database
+ );
+ target.database = database;
+ target.instance = database.instanceEntity;
+ } else if (connection.instance) {
+ const instance = useInstanceV1Store().getInstanceByUID(connection.instance);
+ target.instance = instance;
+ }
+ return target;
+};
+
+const isSameSQLEditorConnection = (
+ a: SQLEditorConnection,
+ b: SQLEditorConnection
+): boolean => {
+ return a.instance === b.instance && a.database === b.database;
+};
+
+export const isSimilarSQLEditorTab = (
+ a: CoreSQLEditorTab,
+ b: CoreSQLEditorTab
+): boolean => {
+ return (
+ isSameSQLEditorConnection(a.connection, b.connection) &&
+ a.sheet === b.sheet &&
+ a.mode === b.mode
+ );
+};
+
+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
+) => {
+ const instance = useInstanceV1Store().getInstanceByName(conn.instance);
+ const database = useDatabaseV1Store().getDatabaseByName(conn.database);
+ const parts: string[] = [];
+ if (database.uid !== String(UNKNOWN_ID)) {
+ parts.push(database.databaseName);
+ } else if (instance.uid !== String(UNKNOWN_ID)) {
+ parts.push(instance.title);
+ }
+ parts.push(defaultSQLEditorTabTitle());
+ return parts.join(" ");
+};
+
+export const isDisconnectedSQLEditorTab = (tab: SQLEditorTab) => {
+ const { connection } = tab;
+ if (!connection.instance) {
+ return true;
+ }
+ const instance = useInstanceV1Store().getInstanceByName(connection.instance);
+ if (instanceV1AllowsCrossDatabaseQuery(instance)) {
+ // Connecting to instance directly.
+ return false;
+ }
+ return connection.database === "";
+};
+
+export const tryConnectToCoreSQLEditorTab = (
+ tab: CoreSQLEditorTab,
+ overrideTitle = true
+) => {
+ const tabStore = useSQLEditorTabStore();
+ const currentTab = tabStore.currentTab;
+ if (currentTab) {
+ if (isSimilarSQLEditorTab(tab, currentTab)) {
+ // Don't go further if the connection doesn't change.
+ return;
+ }
+ if (currentTab.status === "NEW" || !currentTab.sheet) {
+ // If the current tab is "fresh new", update its connection directly.
+ 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 emptySQLEditorTabQueryContext = (): SQLEditorTabQueryContext => ({
+ beginTimestampMS: Date.now(),
+ abortController: new AbortController(),
+ status: "IDLE",
+ results: new Map(),
+ params: {
+ connection: emptySQLEditorConnection(),
+ engine: Engine.MYSQL,
+ explain: false,
+ statement: "",
+ },
+});
diff --git a/frontend/src/utils/tab.ts b/frontend/src/utils/tab.ts
deleted file mode 100644
index ccedaf9d1b..0000000000
--- a/frontend/src/utils/tab.ts
+++ /dev/null
@@ -1,152 +0,0 @@
-import dayjs from "dayjs";
-import { v1 as uuidv1 } from "uuid";
-import { useDatabaseV1Store, useInstanceV1Store, useTabStore } from "@/store";
-import type {
- ComposedDatabase,
- ComposedInstance,
- Connection,
- CoreTabInfo,
- TabInfo,
- TabSheetType,
-} from "@/types";
-import { UNKNOWN_ID, TabMode } from "@/types";
-import { instanceV1AllowsCrossDatabaseQuery } from "./v1/instance";
-
-export const getDefaultTabName = () => {
- return dayjs().format("YYYY-MM-DD HH:mm");
-};
-
-export const isSimilarDefaultTabName = (name: string) => {
- const regex = /(^|\s)(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2})$/;
- return regex.test(name);
-};
-
-export const emptyConnection = (): Connection => {
- return {
- instanceId: String(UNKNOWN_ID),
- databaseId: String(UNKNOWN_ID),
- };
-};
-
-export const getDefaultTab = (): TabInfo => {
- return {
- id: uuidv1(),
- name: getDefaultTabName(),
- connection: emptyConnection(),
- isSaved: true,
- savedAt: dayjs().format("YYYY-MM-DD HH:mm:ss"),
- statement: "",
- selectedStatement: "",
- mode: TabMode.ReadOnly,
- editMode: "SQL-EDITOR",
- isExecutingSQL: false,
- };
-};
-
-export const isTempTab = (tab: TabInfo): boolean => {
- if (tab.sheetName) return false;
- if (!tab.isSaved) return false;
- if (tab.statement) return false;
- return true;
-};
-
-export const sheetTypeForTab = (tab: TabInfo): TabSheetType => {
- if (!tab.sheetName) {
- return "TEMP";
- }
- if (tab.isSaved) {
- return "CLEAN";
- }
- return "DIRTY";
-};
-
-export const connectionForTab = (tab: TabInfo) => {
- const target: {
- instance: ComposedInstance | undefined;
- database: ComposedDatabase | undefined;
- } = {
- instance: undefined,
- database: undefined,
- };
- const { instanceId, databaseId } = tab.connection;
- if (databaseId !== String(UNKNOWN_ID)) {
- const database = useDatabaseV1Store().getDatabaseByUID(databaseId);
- target.database = database;
- target.instance = database.instanceEntity;
- } else if (instanceId !== String(UNKNOWN_ID)) {
- const instance = useInstanceV1Store().getInstanceByUID(instanceId);
- target.instance = instance;
- }
- return target;
-};
-
-const isSameConnection = (a: Connection, b: Connection): boolean => {
- return a.instanceId === b.instanceId && a.databaseId === b.databaseId;
-};
-
-export const isSimilarTab = (a: CoreTabInfo, b: CoreTabInfo): boolean => {
- return (
- isSameConnection(a.connection, b.connection) &&
- a.sheetName === b.sheetName &&
- a.mode === b.mode
- );
-};
-
-export const getSuggestedTabNameFromConnection = (conn: Connection) => {
- const instance = useInstanceV1Store().getInstanceByUID(conn.instanceId);
- const database = useDatabaseV1Store().getDatabaseByUID(conn.databaseId);
- const parts: string[] = [];
- if (database.uid !== String(UNKNOWN_ID)) {
- parts.push(database.databaseName);
- } else if (instance.uid !== String(UNKNOWN_ID)) {
- parts.push(instance.title);
- }
- parts.push(getDefaultTabName());
- return parts.join(" ");
-};
-
-export const isDisconnectedTab = (tab: TabInfo) => {
- const { instanceId, databaseId } = tab.connection;
- if (instanceId === String(UNKNOWN_ID)) {
- return true;
- }
- const instance = useInstanceV1Store().getInstanceByUID(instanceId);
- if (instanceV1AllowsCrossDatabaseQuery(instance)) {
- // Connecting to instance directly.
- return false;
- }
- return databaseId === String(UNKNOWN_ID);
-};
-
-export const tryConnectToCoreTab = (tab: CoreTabInfo) => {
- const tabStore = useTabStore();
-
- if (!tabStore.currentTabId) {
- tabStore.addTab({
- name: getSuggestedTabNameFromConnection(tab.connection),
- connection: tab.connection,
- // The newly created tab is "clean" so its connection can be changed
- isFreshNew: true,
- });
- return;
- } else if (isSimilarTab(tab, tabStore.currentTab)) {
- // Don't go further if the connection doesn't change.
- return;
- }
- if (tabStore.currentTab.isFreshNew || !tabStore.currentTab.sheetName) {
- // If the current tab is "fresh new" or unsaved, update its connection directly.
- tabStore.updateCurrentTab({
- ...tab,
- name: getSuggestedTabNameFromConnection(tab.connection),
- });
- } else {
- // Otherwise select or add a new tab and set its connection.
- const name = getSuggestedTabNameFromConnection(tab.connection);
- tabStore.selectOrAddSimilarTab(
- tab,
- false /* beside */,
- name /* defaultTabName */
- );
- tabStore.updateCurrentTab(tab);
- }
-};
diff --git a/frontend/src/views/sql-editor/AccessDenied.vue b/frontend/src/views/sql-editor/AccessDenied.vue
new file mode 100644
index 0000000000..3507c97348
--- /dev/null
+++ b/frontend/src/views/sql-editor/AccessDenied.vue
@@ -0,0 +1,8 @@
+<template>
+ <div class="w-full h-full flex flex-col items-center justify-center">
+ <img src="@/assets/illustration/403.webp" class="max-h-[40%]" />
+ <div class="textinfolabel">
+ {{ $t("database.access-denied") }}
+ </div>
+ </div>
+</template>
diff --git a/frontend/src/views/sql-editor/AsidePanel/AsidePanel.vue b/frontend/src/views/sql-editor/AsidePanel/AsidePanel.vue
index ac2785bea9..5d8470b480 100644
--- a/frontend/src/views/sql-editor/AsidePanel/AsidePanel.vue
+++ b/frontend/src/views/sql-editor/AsidePanel/AsidePanel.vue
@@ -1,13 +1,70 @@
<template>
<div class="aside-panel h-full flex flex-col overflow-hidden">
- <GroupingBar />
- <div class="flex-1 overflow-hidden">
+ <div
+ v-if="!strictProject"
+ class="flex flex-row items-center gap-x-1 px-1 pt-1"
+ >
+ <ProjectSelect
+ style="width: 100%"
+ size="small"
+ class="project-select"
+ :project="projectUID"
+ :include-all="false"
+ :loading="!projectContextReady"
+ @update:project="handleSwitchProject"
+ />
+ </div>
+ <div class="flex-1 overflow-hidden pt-1">
<DatabaseTree />
</div>
</div>
</template>
<script lang="ts" setup>
+import { storeToRefs } from "pinia";
+import { computed, watch } from "vue";
+import { ProjectSelect } from "@/components/v2";
+import {
+ useProjectV1Store,
+ useSQLEditorTreeStore,
+ useSQLEditorStore,
+} from "@/store";
+import { UNKNOWN_ID } from "@/types";
+import { useSQLEditorContext } from "../context";
import DatabaseTree from "./DatabaseTree.vue";
-import GroupingBar from "./GroupingBar";
+
+const editorStore = useSQLEditorStore();
+const treeStore = useSQLEditorTreeStore();
+const { events } = useSQLEditorContext();
+const { project, projectContextReady, strictProject } =
+ storeToRefs(editorStore);
+
+const projectUID = computed(() => {
+ return treeStore.currentProject?.uid ?? null;
+});
+
+watch([project, projectContextReady], ([project, ready]) => {
+ if (!ready) {
+ treeStore.state = "LOADING";
+ } else {
+ treeStore.buildTree();
+ treeStore.state = "READY";
+ events.emit("tree-ready");
+ }
+});
+
+const handleSwitchProject = (uid: string | undefined) => {
+ if (!uid || uid === String(UNKNOWN_ID)) {
+ project.value = "";
+ } else {
+ const proj = useProjectV1Store().getProjectByUID(uid);
+ project.value = proj.name;
+ }
+};
</script>
+
+<style lang="postcss" scoped>
+.project-select :deep(.n-base-selection) {
+ --n-height: 30px !important;
+}
+</style>
diff --git a/frontend/src/views/sql-editor/AsidePanel/DatabaseHoverPanel.vue b/frontend/src/views/sql-editor/AsidePanel/DatabaseHoverPanel.vue
index f4c35793e3..4bf3496996 100644
--- a/frontend/src/views/sql-editor/AsidePanel/DatabaseHoverPanel.vue
+++ b/frontend/src/views/sql-editor/AsidePanel/DatabaseHoverPanel.vue
@@ -99,7 +99,7 @@ const show = computed(
);
const hasProjectContext = computed(() => {
- return treeStore.selectedProject;
+ return !!treeStore.currentProject;
});
useEventListener(popoverRef, "mouseenter", () => {
diff --git a/frontend/src/views/sql-editor/AsidePanel/DatabaseTree.vue b/frontend/src/views/sql-editor/AsidePanel/DatabaseTree.vue
index 5c3c248c5b..b63b817c43 100644
--- a/frontend/src/views/sql-editor/AsidePanel/DatabaseTree.vue
+++ b/frontend/src/views/sql-editor/AsidePanel/DatabaseTree.vue
@@ -1,17 +1,20 @@
<template>
<div
v-if="treeStore.state === 'READY'"
- class="sql-editor-tree p-0.5 gap-y-1 h-full flex flex-col"
+ class="sql-editor-tree gap-y-1 h-full flex flex-col"
>
- <SearchBox v-model:searchPattern="searchPattern" />
+ <div class="flex flex-row gap-x-0.5 px-1 items-center">
+ <SearchBox v-model:searchPattern="searchPattern" class="flex-1" />
+ <GroupingBar class="shrink-0" />
+ </div>
<div
ref="treeContainerElRef"
- class="sql-editor-tree--tree flex-1 pb-1 text-sm overflow-hidden select-none"
+ class="sql-editor-tree--tree flex-1 px-1 pb-1 text-sm overflow-hidden select-none"
:data-height="treeContainerHeight"
>
<NTree
ref="treeRef"
- v-model:expanded-keys="treeStore.expandedKeys"
+ v-model:expanded-keys="expandedKeys"
:block-line="true"
:data="treeStore.tree"
:show-irrelevant-nodes="false"
@@ -60,6 +63,7 @@ import { storeToRefs } from "pinia";
import { ref, computed, nextTick, watch, h } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
+import { useEmitteryEventListener } from "@/composables/useEmitteryEventListener";
import { useExecuteSQL } from "@/composables/useExecuteSQL";
import { SQL_EDITOR_DETAIL_MODULE } from "@/router/sqlEditor";
import {
@@ -69,46 +73,49 @@ import {
useDatabaseV1Store,
useInstanceV1Store,
useIsLoggedIn,
- useTabStore,
pushNotification,
+ useSQLEditorTabStore,
+ resolveOpeningDatabaseListFromSQLEditorTabList,
+ useSQLEditorTreeStore,
+ idForSQLEditorTreeNodeTarget,
+ useConnectionOfCurrentSQLEditorTab,
} from "@/store";
import {
- idForSQLEditorTreeNodeTarget,
- useSQLEditorTreeStore,
-} from "@/store/modules/sqlEditorTree";
-import type {
ComposedDatabase,
ComposedInstance,
- CoreTabInfo,
+ CoreSQLEditorTab,
RichTableMetadata,
+ SQLEditorTabMode,
SQLEditorTreeNode,
SQLEditorTreeNodeTarget,
+ SQLEditorTreeNodeType,
+ UNKNOWN_ID,
} from "@/types";
import {
ConnectableTreeNodeTypes,
- TabMode,
- UNKNOWN_ID,
+ DEFAULT_SQL_EDITOR_TAB_MODE,
+ ExpandableTreeNodeTypes,
instanceOfSQLEditorTreeNode,
isConnectableSQLEditorTreeNode,
languageOfEngineV1,
} from "@/types";
import { Engine } from "@/types/proto/v1/common";
import {
- emptyConnection,
findAncestor,
- formatEngineV1,
- getSuggestedTabNameFromConnection,
hasWorkspacePermissionV2,
instanceV1AllowsCrossDatabaseQuery,
instanceV1HasAlterSchema,
instanceV1HasReadonlyMode,
isDescendantOf,
- tryConnectToCoreTab,
wrapSQLIdentifier,
connectionV1Slug,
+ tryConnectToCoreSQLEditorTab,
+ emptySQLEditorConnection,
+ suggestedTabTitleForSQLEditorConnection,
} from "@/utils";
import { useSQLEditorContext } from "../context";
import DatabaseHoverPanel from "./DatabaseHoverPanel.vue";
+import GroupingBar from "./GroupingBar";
import SearchBox from "./SearchBox/index.vue";
import useSearchHistory from "./SearchBox/useSearchHistory";
import { Label } from "./TreeNode";
@@ -128,7 +135,7 @@ const { t } = useI18n();
const router = useRouter();
const { pageMode } = storeToRefs(useActuatorV1Store());
const treeStore = useSQLEditorTreeStore();
-const tabStore = useTabStore();
+const tabStore = useSQLEditorTabStore();
const databaseStore = useDatabaseV1Store();
const instanceStore = useInstanceV1Store();
const dbSchemaV1Store = useDBSchemaV1Store();
@@ -192,7 +199,7 @@ const dropdownOptions = computed((): DropdownOptionWithTreeNode[] => {
items.push({
key: "connect-in-admin-mode",
label: t("sql-editor.connect-in-admin-mode"),
- onSelect: () => setConnection(node, TabMode.Admin),
+ onSelect: () => setConnection(node, { sheet: "", mode: "ADMIN" }),
});
}
}
@@ -259,10 +266,13 @@ const dropdownOptions = computed((): DropdownOptionWithTreeNode[] => {
// Highlight the current tab's connection node.
const selectedKeys = computed(() => {
- const { instanceId, databaseId } = tabStore.currentTab.connection;
+ const connection = tabStore.currentTab?.connection;
+ if (!connection) {
+ return [];
+ }
- if (databaseId !== String(UNKNOWN_ID)) {
- const database = databaseStore.getDatabaseByUID(databaseId);
+ if (connection.database) {
+ const database = databaseStore.getDatabaseByName(connection.database);
const node = head(treeStore.nodesByTarget("database", database));
if (!node) return [];
const selected = selectedDatabaseSchemaByDatabaseName.value.get(
@@ -295,21 +305,70 @@ const selectedKeys = computed(() => {
}
}
return [node.key];
- } else if (instanceId !== String(UNKNOWN_ID)) {
- const instance = instanceStore.getInstanceByUID(instanceId);
+ } else if (connection.instance) {
+ const instance = instanceStore.getInstanceByName(connection.instance);
const nodes = treeStore.nodesByTarget("instance", instance);
return nodes.map((node) => node.key);
}
return [];
});
+const expandedKeys = ref<string[]>([]);
+const upsertExpandedKeys = (key: string) => {
+ if (expandedKeys.value.includes(key)) {
+ return;
+ }
+ expandedKeys.value.push(key);
+};
+const expandNode = (
+ node: SQLEditorTreeNode | undefined,
+ keys?: Set<string>
+) => {
+ if (!node) {
+ return;
+ }
+ if (ExpandableTreeNodeTypes.includes(node.meta.type)) {
+ if (keys) {
+ keys.add(node.key);
+ } else {
+ upsertExpandedKeys(node.key);
+ }
+ }
+};
+const expandNodeRecursively = (
+ node: SQLEditorTreeNode | undefined,
+ keys?: Set<string>
+) => {
+ if (!node) {
+ return;
+ }
+ expandNode(node, keys);
+
+ if (node.parent) {
+ expandNodeRecursively(node.parent, keys);
+ }
+};
+const expandNodesByType = <T extends SQLEditorTreeNodeType>(
+ type: T,
+ target: SQLEditorTreeNodeTarget<T>
+) => {
+ const nodes = treeStore.nodesByTarget(type, target);
+ nodes.forEach((node) => {
+ expandNodeRecursively(node);
+ });
+
+ return nodes;
+};
const allowAdmin = computed(() =>
hasWorkspacePermissionV2(me.value, "bb.instances.adminExecute")
);
const setConnection = (
node: SQLEditorTreeNode,
- mode: TabMode = TabMode.ReadOnly
+ extra: { sheet: string; mode: SQLEditorTabMode } = {
+ sheet: "",
+ mode: DEFAULT_SQL_EDITOR_TAB_MODE,
+ }
) => {
if (node) {
const { type } = node.meta;
@@ -322,23 +381,23 @@ const setConnection = (
return;
}
}
- const coreTab: CoreTabInfo = {
- connection: emptyConnection(),
- mode,
+ const coreTab: CoreSQLEditorTab = {
+ connection: emptySQLEditorConnection(),
+ ...extra,
};
const conn = coreTab.connection;
// If selected item is instance node
if (type === "instance") {
const instance = node.meta.target as ComposedInstance;
- conn.instanceId = instance.uid;
+ conn.instance = instance.name;
}
// If selected item is database node
if (type === "database") {
const database = node.meta.target as ComposedDatabase;
- conn.instanceId = database.instanceEntity.uid;
- conn.databaseId = database.uid;
+ conn.instance = database.instance;
+ conn.database = database.name;
}
- tryConnectToCoreTab(coreTab);
+ tryConnectToCoreSQLEditorTab(coreTab);
}
};
@@ -359,26 +418,32 @@ const handleSelect = (key: string) => {
}
option.onSelect();
showDropdown.value = false;
+ console.log("handleSelect", key);
};
const handleClickoutside = () => {
showDropdown.value = false;
+ console.log("handleClickoutside");
};
const maybeSelectTable = async (node: SQLEditorTreeNode) => {
const target = node.meta.target as SQLEditorTreeNodeTarget<"table">;
const { database, schema, table } = target;
- if (database.uid !== tabStore.currentTab.connection.databaseId) {
- const coreTab: CoreTabInfo = {
+ if (
+ !tabStore.currentTab ||
+ tabStore.currentTab.connection.database !== database.name
+ ) {
+ const coreTab: CoreSQLEditorTab = {
connection: {
- instanceId: database.instanceEntity.uid,
- databaseId: database.uid,
+ instance: database.instance,
+ database: database.name,
schema: schema.name,
table: table.name,
},
- mode: TabMode.ReadOnly,
+ mode: DEFAULT_SQL_EDITOR_TAB_MODE,
+ sheet: "",
};
- tryConnectToCoreTab(coreTab);
+ tryConnectToCoreSQLEditorTab(coreTab);
await nextTick();
}
@@ -396,29 +461,34 @@ const maybeSelectTable = async (node: SQLEditorTreeNode) => {
table: tableMetadata,
});
- tabStore.updateCurrentTab({
- connection: {
- ...tabStore.currentTab.connection,
- schema: schema.name,
- table: table.name,
- },
- });
+ if (tabStore.currentTab) {
+ tabStore.updateCurrentTab({
+ connection: {
+ ...tabStore.currentTab.connection,
+ schema: schema.name,
+ table: table.name,
+ },
+ });
+ }
};
const maybeSelectExternalTable = async (node: SQLEditorTreeNode) => {
const target = node.meta.target as SQLEditorTreeNodeTarget<"external-table">;
const { database, schema, externalTable } = target;
- if (database.uid !== tabStore.currentTab.connection.databaseId) {
- const coreTab: CoreTabInfo = {
+
+ if (
+ !tabStore.currentTab ||
+ tabStore.currentTab.connection.database !== database.name
+ ) {
+ const coreTab: CoreSQLEditorTab = {
connection: {
- instanceId: database.instanceEntity.uid,
- databaseId: database.uid,
+ instance: database.instance,
+ database: database.name,
},
- mode: TabMode.ReadOnly,
+ mode: DEFAULT_SQL_EDITOR_TAB_MODE,
+ sheet: "",
};
- coreTab.connection.instanceId = database.instanceEntity.uid;
- coreTab.connection.databaseId = database.uid;
- tryConnectToCoreTab(coreTab);
+ tryConnectToCoreSQLEditorTab(coreTab);
await nextTick();
}
@@ -437,36 +507,43 @@ const selectAllFromTableOrView = async (node: SQLEditorTreeNode) => {
const { engine } = database.instanceEntity;
const LIMIT = 50; // default pagesize of SQL Editor
- const runQuery = async (query: string) => {
- const tab: CoreTabInfo = {
+ const runQuery = async (statement: string) => {
+ const tab: CoreSQLEditorTab = {
connection: {
- instanceId: database.instanceEntity.uid,
- databaseId: database.uid,
+ instance: database.instance,
+ database: database.name,
},
- mode: TabMode.ReadOnly,
+ mode: DEFAULT_SQL_EDITOR_TAB_MODE,
+ sheet: "",
};
- if (tabStore.currentTab.isFreshNew || !tabStore.currentTab.sheetName) {
+ if (
+ tabStore.currentTab &&
+ (tabStore.currentTab.status === "NEW" || !tabStore.currentTab.sheet)
+ ) {
// If the current tab is "fresh new" or unsaved, update its connection directly.
tabStore.updateCurrentTab({
...tab,
- name: getSuggestedTabNameFromConnection(tab.connection),
- statement: tabStore.currentTab.statement || query,
+ title: suggestedTabTitleForSQLEditorConnection(tab.connection),
+ statement: tabStore.currentTab.statement || statement,
});
} else {
// Otherwise select or add a new tab and set its connection
tabStore.addTab(
{
...tab,
- name: getSuggestedTabNameFromConnection(tab.connection),
- statement: query,
- isSaved: false,
+ title: suggestedTabTitleForSQLEditorConnection(tab.connection),
+ statement: statement,
+ status: "DIRTY",
},
/* beside */ true
);
}
await nextTick();
- executeReadonly(query, {
- databaseType: formatEngineV1(database.instanceEntity),
+ executeReadonly({
+ statement,
+ connection: { ...tab.connection },
+ explain: false,
+ engine: database.instanceEntity.engine,
});
};
@@ -544,12 +621,14 @@ const nodeProps = ({ option }: { option: TreeOption }) => {
onContextmenu(e: MouseEvent) {
e.preventDefault();
showDropdown.value = false;
+ console.log("onContextmenu", false);
if (node && node.key) {
dropdownContext.value = node;
}
nextTick().then(() => {
showDropdown.value = true;
+ console.log("onContextmenu", true);
dropdownPosition.value.x = e.clientX;
dropdownPosition.value.y = e.clientY;
});
@@ -595,15 +674,20 @@ const nodeProps = ({ option }: { option: TreeOption }) => {
const handleLoadSubTree = (option: TreeOption) => {
const node = option as any as SQLEditorTreeNode;
- const { type, target } = node.meta;
+ const { type } = node.meta;
if (type === "database") {
const request = fetchDatabaseSubTree(node);
request
.then(() => nextTick())
.then(() => {
if ((node.children?.length ?? 0) > 0) {
- treeStore.expandNodes(type, target);
- expandTableTab(target as ComposedDatabase);
+ expandNode(node);
+ if (expandSchemaAndTableNodes(node)) {
+ // if a specified schema node is expanded we stop here
+ return;
+ }
+ // we expand the first schema node otherwise
+ expandFirstSchemaNode(node);
}
});
return request;
@@ -611,78 +695,110 @@ const handleLoadSubTree = (option: TreeOption) => {
return Promise.resolve();
};
-const expandTableTab = (database: ComposedDatabase) => {
- const { schema, table } = tabStore.currentTab.connection;
- const schemaMetadata = dbSchemaV1Store.getSchemaByName(
- database.name,
- schema ?? ""
- );
+/**
+ * returns true if successfully expanded, false if not expanded
+ */
+const expandSchemaAndTableNodes = (
+ databaseNode: SQLEditorTreeNode<"database">
+): boolean => {
+ const tab = tabStore.currentTab;
+ if (!tab) {
+ return false;
+ }
+ const { database, schema, table } = tab.connection;
+ const db = databaseNode.meta.target;
+ if (db.name !== database) {
+ return false;
+ }
+ const schemaMetadata = dbSchemaV1Store.getSchemaByName(db.name, schema ?? "");
if (!schemaMetadata) {
- return;
+ return false;
}
- treeStore.expandNodes("schema", {
- database: database,
- schema: schemaMetadata,
- });
- if (!table) {
- return;
+ const schemaNode = databaseNode.children?.find(
+ (
+ node: SQLEditorTreeNode
+ ): node is
+ | SQLEditorTreeNode<"schema">
+ | SQLEditorTreeNode<"expandable-text"> => {
+ if (node.meta.type === "schema") {
+ return (
+ (node.meta.target as SQLEditorTreeNodeTarget<"schema">).schema
+ .name === schemaMetadata.name
+ );
+ }
+ if (node.meta.type === "expandable-text") {
+ return schemaMetadata.name === "";
+ }
+ return false;
+ }
+ );
+
+ if (!schemaNode) {
+ return false;
+ }
+ expandNode(schemaNode);
+ if (schemaNode.meta.type === "schema") {
+ // a schema node contains a "Tables" `expandable-text` node
+ // so we should also expand the first child
+ expandNode(head(schemaNode.children));
}
- treeStore.expandNodes("expandable-text", {
- type: "table",
- text: () => t("db.tables"),
- expandable: true,
- });
- const tableMetadata = dbSchemaV1Store.getTableByName(
- database.name,
- table,
- schema
- );
+ if (!table) {
+ return true;
+ }
+ const tableMetadata = dbSchemaV1Store.getTableByName(db.name, table, schema);
if (!tableMetadata) {
- return;
+ return true;
}
- treeStore.expandNodes("table", {
- database: database,
- schema: schemaMetadata,
- table: tableMetadata,
- });
- const databaseMetadata = dbSchemaV1Store.getDatabaseMetadata(database.name);
- selectedDatabaseSchemaByDatabaseName.value.set(database.name, {
- db: database,
+ const databaseMetadata = dbSchemaV1Store.getDatabaseMetadata(db.name);
+ selectedDatabaseSchemaByDatabaseName.value.set(db.name, {
+ db: db,
database: databaseMetadata,
schema: schemaMetadata,
table: tableMetadata,
});
+ return true;
+};
+
+/**
+ * returns true if successfully expanded, false if not expanded
+ */
+const expandFirstSchemaNode = (
+ databaseNode: SQLEditorTreeNode<"database">,
+ keys?: Set<string>
+) => {
+ const firstChild = head(databaseNode.children) as SQLEditorTreeNode;
+ expandNode(firstChild);
+ if (firstChild && firstChild.meta.type === "schema") {
+ // a schema node contains a "Tables" `expandable-text` node
+ // so we should also expand the first child
+ expandNode(head(firstChild.children));
+ }
};
// Open corresponding tree node when the connection changed.
+const { instance, database } = useConnectionOfCurrentSQLEditorTab();
watch(
- [
- isLoggedIn,
- () => tabStore.currentTab.connection.instanceId,
- () => tabStore.currentTab.connection.databaseId,
- () => treeStore.state,
- ],
- ([isLoggedIn, instanceId, databaseId, treeState]) => {
+ [isLoggedIn, instance, database, () => treeStore.state],
+ ([isLoggedIn, instance, database, treeState]) => {
if (!isLoggedIn) {
// Don't go further and cleanup the state if we signed out.
- treeStore.expandedKeys = [];
+ // treeStore.expandedKeys = [];
+ expandedKeys.value = [];
return;
}
+
if (treeState !== "READY") {
return;
}
-
- if (instanceId !== String(UNKNOWN_ID)) {
- const instance = instanceStore.getInstanceByUID(instanceId);
- treeStore.expandNodes("instance", instance);
+ if (instance.uid !== String(UNKNOWN_ID)) {
+ expandNodesByType("instance", instance);
}
- if (databaseId !== String(UNKNOWN_ID)) {
- const db = databaseStore.getDatabaseByUID(databaseId);
- treeStore.expandNodes("project", db.projectEntity);
- treeStore.expandNodes("database", db);
+ if (database.uid !== String(UNKNOWN_ID)) {
+ expandNodesByType("project", database.projectEntity);
+ expandNodesByType("database", database);
}
},
{ immediate: true }
@@ -699,6 +815,28 @@ watch(
},
{ immediate: true }
);
+
+useEmitteryEventListener(editorEvents, "tree-ready", async () => {
+ await nextTick();
+ const openingDatabaseList = resolveOpeningDatabaseListFromSQLEditorTabList();
+ const keys = new Set<string>();
+ // Recursively expand opening databases' parent nodes
+ openingDatabaseList.forEach((meta) => {
+ const db = meta.target;
+ const nodes = treeStore.nodesByTarget("database", db);
+ nodes.forEach((node) => expandNodeRecursively(node.parent, keys));
+ });
+ const tab = tabStore.currentTab;
+ // Expand current tab's connected database node
+ if (tab && tab.connection.database) {
+ const db = useDatabaseV1Store().getDatabaseByName(tab.connection.database);
+ const node = head(treeStore.nodesByTarget("database", db));
+ if (node) {
+ keys.add(node.key);
+ }
+ }
+ expandedKeys.value = Array.from(keys);
+});
</script>
<style lang="postcss" scoped>
diff --git a/frontend/src/views/sql-editor/AsidePanel/GroupingBar/FactorItem.vue b/frontend/src/views/sql-editor/AsidePanel/GroupingBar/FactorItem.vue
index 0e76e64a3a..7754a0282c 100644
--- a/frontend/src/views/sql-editor/AsidePanel/GroupingBar/FactorItem.vue
+++ b/frontend/src/views/sql-editor/AsidePanel/GroupingBar/FactorItem.vue
@@ -13,7 +13,7 @@
import { NCheckbox } from "naive-ui";
import { storeToRefs } from "pinia";
import { computed } from "vue";
-import { useSQLEditorTreeStore } from "@/store/modules/sqlEditorTree";
+import { useSQLEditorTreeStore } from "@/store/modules";
import {
SQLEditorTreeFactor as Factor,
readableSQLEditorTreeFactor,
diff --git a/frontend/src/views/sql-editor/AsidePanel/GroupingBar/FactorPanel.vue b/frontend/src/views/sql-editor/AsidePanel/GroupingBar/FactorPanel.vue
index d1b7fc3645..c47a3deb6b 100644
--- a/frontend/src/views/sql-editor/AsidePanel/GroupingBar/FactorPanel.vue
+++ b/frontend/src/views/sql-editor/AsidePanel/GroupingBar/FactorPanel.vue
@@ -1,5 +1,6 @@
<template>
<div class="bg-white flex flex-col gap-y-2 w-max p-2">
+ <FactorTags class="border-b pt-1 pb-2 max-w-[20rem]" />
<FactorItem
v-for="(factor, i) in PRESET_FACTORS"
:key="i"
@@ -24,12 +25,15 @@
import { cloneDeep, orderBy, uniq } from "lodash-es";
import { storeToRefs } from "pinia";
import { computed } from "vue";
-import { useSQLEditorTreeStore } from "@/store/modules/sqlEditorTree";
+import { useSQLEditorTreeStore } from "@/store";
import { SQLEditorTreeFactor as Factor } from "@/types";
+import { useSQLEditorContext } from "../../context";
import FactorItem from "./FactorItem.vue";
+import FactorTags from "./FactorTags.vue";
const treeStore = useSQLEditorTreeStore();
const { databaseList, factorList } = storeToRefs(treeStore);
+const { events } = useSQLEditorContext();
const PRESET_FACTORS: Factor[] = ["project", "instance", "environment"];
@@ -64,5 +68,6 @@ const toggle = (factor: Factor, on: boolean) => {
factorList.value = updatedList;
treeStore.buildTree();
+ events.emit("tree-ready");
};
</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/GroupingBar/FactorTag.vue b/frontend/src/views/sql-editor/AsidePanel/GroupingBar/FactorTag.vue
index 131e560407..4fe821b040 100644
--- a/frontend/src/views/sql-editor/AsidePanel/GroupingBar/FactorTag.vue
+++ b/frontend/src/views/sql-editor/AsidePanel/GroupingBar/FactorTag.vue
@@ -29,7 +29,7 @@
<script setup lang="ts">
import { storeToRefs } from "pinia";
import { computed } from "vue";
-import { useSQLEditorTreeStore } from "@/store/modules/sqlEditorTree";
+import { useSQLEditorTreeStore } from "@/store";
import {
StatefulSQLEditorTreeFactor as StatefulFactor,
readableSQLEditorTreeFactor,
diff --git a/frontend/src/views/sql-editor/AsidePanel/GroupingBar/FactorTags.vue b/frontend/src/views/sql-editor/AsidePanel/GroupingBar/FactorTags.vue
new file mode 100644
index 0000000000..074e33e241
--- /dev/null
+++ b/frontend/src/views/sql-editor/AsidePanel/GroupingBar/FactorTags.vue
@@ -0,0 +1,42 @@
+<template>
+ <div class="flex flex-row items-start flex-wrap gap-x-1.5 gap-y-1.5">
+ <FactorTag
+ v-for="(factor, i) in factorList"
+ :key="i"
+ :factor="factor"
+ :allow-disable="filteredFactorList.length > 1"
+ @toggle-disabled="toggleDisabled(factor, i)"
+ @remove="remove(factor, i)"
+ />
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { storeToRefs } from "pinia";
+import { useSQLEditorTreeStore } from "@/store";
+import { StatefulSQLEditorTreeFactor as StatefulFactor } from "@/types";
+import { useSQLEditorContext } from "../../context";
+import FactorTag from "./FactorTag.vue";
+
+const treeStore = useSQLEditorTreeStore();
+const { events } = useSQLEditorContext();
+const { factorList, filteredFactorList } = storeToRefs(treeStore);
+
+const toggleDisabled = (factor: StatefulFactor, index: number) => {
+ factor.disabled = !factor.disabled;
+ treeStore.buildTree();
+ events.emit("tree-ready");
+};
+
+const remove = (factor: StatefulFactor, index: number) => {
+ factorList.value.splice(index, 1);
+ if (factorList.value.length === 0) {
+ factorList.value.push({
+ factor: "project",
+ disabled: false,
+ });
+ }
+ treeStore.buildTree();
+ events.emit("tree-ready");
+};
+</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/GroupingBar/GroupingBar.vue b/frontend/src/views/sql-editor/AsidePanel/GroupingBar/GroupingBar.vue
index e69dd615c0..75e3660d1d 100644
--- a/frontend/src/views/sql-editor/AsidePanel/GroupingBar/GroupingBar.vue
+++ b/frontend/src/views/sql-editor/AsidePanel/GroupingBar/GroupingBar.vue
@@ -1,79 +1,45 @@
<template>
- <div class="flex flex-row items-start min-h-[34px] pt-0.5 bg-control-bg">
- <div class="flex-1 mt-0.5">
- <NTabs
- v-if="viewMode === 'PRESET'"
- :value="factorList[0].factor"
- type="segment"
+ <NPopover
+ raw
+ :show-arrow="false"
+ to="body"
+ placement="bottom-start"
+ trigger="click"
+ >
+ <template #trigger>
+ <NButton
+ quaternary
size="small"
- class="grouping-bar--tabs"
- @update:value="selectPresetFactor"
+ style="--n-padding: 0 5px"
+ v-bind="$attrs"
>
- <NTab name="project">{{ readableSQLEditorTreeFactor("project") }}</NTab>
- <NTab name="instance">{{ $t("common.instance") }}</NTab>
- </NTabs>
- <div
- v-if="viewMode === 'CUSTOM'"
- class="flex flex-row items-start text-sm"
- >
- <div class="text-control-light ml-2 p-1 whitespace-nowrap mt-0.5">
- {{ $t("sql-editor.grouping") }}
- </div>
- <div
- class="flex flex-row items-start flex-wrap p-1 gap-x-1.5 gap-y-1.5"
- >
- <FactorTag
- v-for="(factor, i) in factorList"
- :key="i"
- :factor="factor"
- :allow-disable="filteredFactorList.length > 1"
- @toggle-disabled="toggleDisabled(factor, i)"
- @remove="remove(factor, i)"
+ <template #icon>
+ <heroicons:adjustments-horizontal
+ class="w-6 h-6"
+ :class="viewMode === 'CUSTOM' && 'text-accent'"
/>
- </div>
- </div>
- </div>
-
- <div class="shrink-0 mt-0.5 p-1">
- <NPopover
- raw
- :show-arrow="false"
- to="body"
- placement="bottom-start"
- trigger="click"
- >
- <template #trigger>
- <NButton quaternary size="small" style="--n-padding: 0 5px">
- <template #icon>
- <heroicons:adjustments-horizontal
- class="w-6 h-6"
- :class="viewMode === 'CUSTOM' && 'text-accent'"
- />
- </template>
- </NButton>
</template>
- <template #default>
- <FactorPanel />
- </template>
- </NPopover>
- </div>
- </div>
+ </NButton>
+ </template>
+ <template #default>
+ <FactorPanel />
+ </template>
+ </NPopover>
</template>
<script lang="ts" setup>
-import { NButton, NPopover, NTab, NTabs } from "naive-ui";
+import { NButton, NPopover } from "naive-ui";
import { storeToRefs } from "pinia";
import { computed } from "vue";
-import { useSQLEditorTreeStore } from "@/store/modules/sqlEditorTree";
-import {
- StatefulSQLEditorTreeFactor as StatefulFactor,
- readableSQLEditorTreeFactor,
-} from "@/types";
+import { useSQLEditorTreeStore } from "@/store";
import FactorPanel from "./FactorPanel.vue";
-import FactorTag from "./FactorTag.vue";
+
+defineOptions({
+ inheritAttrs: false,
+});
const treeStore = useSQLEditorTreeStore();
-const { factorList, filteredFactorList } = storeToRefs(treeStore);
+const { factorList } = storeToRefs(treeStore);
const viewMode = computed((): "PRESET" | "CUSTOM" => {
if (factorList.value.length === 1) {
@@ -84,36 +50,4 @@ const viewMode = computed((): "PRESET" | "CUSTOM" => {
}
return "CUSTOM";
});
-
-const toggleDisabled = (factor: StatefulFactor, index: number) => {
- factor.disabled = !factor.disabled;
- treeStore.buildTree();
-};
-
-const remove = (factor: StatefulFactor, index: number) => {
- factorList.value.splice(index, 1);
- if (factorList.value.length === 0) {
- factorList.value.push({
- factor: "project",
- disabled: false,
- });
- }
- treeStore.buildTree();
-};
-
-const selectPresetFactor = (factor: "project" | "instance") => {
- factorList.value = [
- {
- factor,
- disabled: false,
- },
- ];
- treeStore.buildTree();
-};
</script>
-
-<style lang="postcss" scoped>
-.grouping-bar--tabs :deep(.n-tabs-rail) {
- @apply !bg-transparent;
-}
-</style>
diff --git a/frontend/src/views/sql-editor/AsidePanel/SearchBox/index.vue b/frontend/src/views/sql-editor/AsidePanel/SearchBox/index.vue
index 737ac861fa..e9cd45be5b 100644
--- a/frontend/src/views/sql-editor/AsidePanel/SearchBox/index.vue
+++ b/frontend/src/views/sql-editor/AsidePanel/SearchBox/index.vue
@@ -1,23 +1,21 @@
<template>
- <div class="w-full pt-2 px-2">
- <NAutoComplete
- size="small"
- clear-after-select
- blur-after-select
- :clearable="true"
- :value="searchPattern"
- :placeholder="$t('sql-editor.search-databases')"
- :options="autoCompleteOptions"
- :render-label="renderLabel"
- :get-show="getOptionShow"
- @update:value="$emit('update:search-pattern', $event || '')"
- @select="handleDatabaseSelect"
- >
- <template #prefix>
- <SearchIcon class="w-4 h-auto text-gray-300" />
- </template>
- </NAutoComplete>
- </div>
+ <NAutoComplete
+ size="small"
+ clear-after-select
+ blur-after-select
+ :clearable="true"
+ :value="searchPattern"
+ :placeholder="$t('sql-editor.search-databases')"
+ :options="autoCompleteOptions"
+ :render-label="renderLabel"
+ :get-show="getOptionShow"
+ @update:value="$emit('update:search-pattern', $event || '')"
+ @select="handleDatabaseSelect"
+ >
+ <template #prefix>
+ <SearchIcon class="w-4 h-auto text-gray-300" />
+ </template>
+ </NAutoComplete>
</template>
<script lang="ts" setup>
@@ -27,10 +25,17 @@ import { computed, watchEffect, h } from "vue";
import { useI18n } from "vue-i18n";
import { EnvironmentV1Name, InstanceV1EngineIcon } from "@/components/v2";
import { useDatabaseV1Store } from "@/store";
-import { CoreTabInfo, TabMode } from "@/types";
-import { emptyConnection, tryConnectToCoreTab } from "@/utils";
+import { CoreSQLEditorTab, DEFAULT_SQL_EDITOR_TAB_MODE } from "@/types";
+import {
+ emptySQLEditorConnection,
+ tryConnectToCoreSQLEditorTab,
+} from "@/utils";
import useSearchHistory from "./useSearchHistory";
+defineOptions({
+ name: "SearchBox",
+});
+
const props = defineProps<{
searchPattern: string;
}>();
@@ -80,7 +85,11 @@ const autoCompleteOptions = computed(() => {
const renderLabel = (option: SelectOption) => {
if (option.type === "group") {
- return h("div", { class: "w-full text-sm text-gray-400" }, [option.label]);
+ return h(
+ "div",
+ { class: "w-full text-sm text-gray-400" },
+ String(option.label)
+ );
}
const database = databaseStore.getDatabaseByName(option.value as string);
@@ -111,16 +120,16 @@ const renderLabel = (option: SelectOption) => {
const handleDatabaseSelect = (databaseName: string) => {
const database = databaseStore.getDatabaseByName(databaseName);
- const coreTab: CoreTabInfo = {
+ const coreTab: CoreSQLEditorTab = {
connection: {
- ...emptyConnection(),
- instanceId: database.instanceEntity.uid,
- databaseId: database.uid,
+ ...emptySQLEditorConnection(),
+ instance: database.instance,
+ database: database.name,
},
- sheetName: undefined,
- mode: TabMode.ReadOnly,
+ sheet: "",
+ mode: DEFAULT_SQL_EDITOR_TAB_MODE,
};
- tryConnectToCoreTab(coreTab);
+ tryConnectToCoreSQLEditorTab(coreTab);
};
watchEffect(async () => {
diff --git a/frontend/src/views/sql-editor/AsidePanel/TreeNode/DatabaseNode.vue b/frontend/src/views/sql-editor/AsidePanel/TreeNode/DatabaseNode.vue
index 9ae3f9a334..c326d82b02 100644
--- a/frontend/src/views/sql-editor/AsidePanel/TreeNode/DatabaseNode.vue
+++ b/frontend/src/views/sql-editor/AsidePanel/TreeNode/DatabaseNode.vue
@@ -62,6 +62,6 @@ const hasEnvironmentContext = computed(() => {
});
const hasProjectContext = computed(() => {
- return props.factors.includes("project") || treeStore.selectedProject;
+ return props.factors.includes("project") || !!treeStore.currentProject;
});
</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/common.ts b/frontend/src/views/sql-editor/AsidePanel/common.ts
index 121ae44fdf..be249908e9 100644
--- a/frontend/src/views/sql-editor/AsidePanel/common.ts
+++ b/frontend/src/views/sql-editor/AsidePanel/common.ts
@@ -4,8 +4,8 @@ import {
pushNotification,
useCurrentUserV1,
useDBSchemaV1Store,
+ mapTreeNodeByType,
} from "@/store";
-import { mapTreeNodeByType } from "@/store/modules/sqlEditorTree";
import {
ComposedDatabase,
SQLEditorTreeNode,
@@ -27,6 +27,7 @@ const createDummyNode = (
return mapTreeNodeByType(
"dummy",
{
+ id: parent.key,
type,
error,
},
@@ -45,6 +46,7 @@ const createExpandableTextNode = (
return mapTreeNodeByType(
"expandable-text",
{
+ id: parent.key,
type,
expandable: true,
text,
diff --git a/frontend/src/views/sql-editor/Disconnected.vue b/frontend/src/views/sql-editor/Disconnected.vue
new file mode 100644
index 0000000000..42dc004b1a
--- /dev/null
+++ b/frontend/src/views/sql-editor/Disconnected.vue
@@ -0,0 +1 @@
+<template>Select a database to connect</template>
diff --git a/frontend/src/views/sql-editor/EditorCommon/AdminModeButton.vue b/frontend/src/views/sql-editor/EditorCommon/AdminModeButton.vue
index a1fb782f19..a06373f2b1 100644
--- a/frontend/src/views/sql-editor/EditorCommon/AdminModeButton.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/AdminModeButton.vue
@@ -3,7 +3,7 @@
v-if="showButton"
:size="props.size"
type="warning"
- :disabled="tabStore.isDisconnected"
+ :disabled="isDisconnected"
@click="enterAdminMode"
>
<heroicons-outline:wrench class="-ml-1" />
@@ -13,12 +13,17 @@
<script lang="ts" setup>
import { last } from "lodash-es";
-import { computed, unref } from "vue";
-import { useCurrentUserV1, useTabStore, useWebTerminalV1Store } from "@/store";
-import { TabMode } from "@/types";
+import { storeToRefs } from "pinia";
+import { computed, nextTick, unref } from "vue";
+import {
+ useCurrentUserV1,
+ useSQLEditorTabStore,
+ useWebTerminalStore,
+} from "@/store";
+import { CoreSQLEditorTab } from "@/types";
import {
- getSuggestedTabNameFromConnection,
hasWorkspacePermissionV2,
+ suggestedTabTitleForSQLEditorConnection,
} from "@/utils";
const emit = defineEmits<{
@@ -38,29 +43,43 @@ const allowAdmin = computed(() =>
hasWorkspacePermissionV2(currentUserV1.value, "bb.instances.adminExecute")
);
-const tabStore = useTabStore();
+const tabStore = useSQLEditorTabStore();
+const { currentTab, isDisconnected } = storeToRefs(tabStore);
const showButton = computed(() => {
if (!allowAdmin.value) return false;
- return tabStore.currentTab.mode === TabMode.ReadOnly;
+ const mode = currentTab.value?.mode;
+ return mode === "READONLY" || mode === "STANDARD";
});
-const enterAdminMode = () => {
- const current = tabStore.currentTab;
- const statement = current.statement;
- const target = {
- connection: current.connection,
- mode: TabMode.Admin,
- name: getSuggestedTabNameFromConnection(current.connection),
+const enterAdminMode = async () => {
+ const tab = currentTab.value;
+ if (!tab) {
+ return;
+ }
+ const statement = tab.statement;
+ const target: CoreSQLEditorTab = {
+ connection: { ...tab.connection },
+ mode: "ADMIN",
+ sheet: "",
};
- tabStore.selectOrAddSimilarTab(target, /* beside */ true);
+ tabStore.selectOrAddSimilarNewTab(
+ target,
+ /* beside */ true,
+ /* title */ suggestedTabTitleForSQLEditorConnection(tab.connection)
+ );
tabStore.updateCurrentTab({
...target,
statement,
});
+
+ await nextTick();
+ const current = currentTab.value;
+ if (!current) {
+ return;
+ }
const queryItemList = unref(
- useWebTerminalV1Store().getQueryStateByTab(tabStore.currentTab)
- .queryItemList
+ useWebTerminalStore().getQueryStateByTab(current).queryItemList
);
const queryItem = last(queryItemList || []);
if (queryItem) {
diff --git a/frontend/src/views/sql-editor/EditorCommon/BatchQueryDatabasesSelector.vue b/frontend/src/views/sql-editor/EditorCommon/BatchQueryDatabasesSelector.vue
index ce9eda1185..2ee5129ab9 100644
--- a/frontend/src/views/sql-editor/EditorCommon/BatchQueryDatabasesSelector.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/BatchQueryDatabasesSelector.vue
@@ -110,10 +110,10 @@ import { InstanceV1EngineIcon } from "@/components/v2";
import LabelsColumn from "@/components/v2/Model/DatabaseV1Table/LabelsColumn.vue";
import {
hasFeature,
+ useConnectionOfCurrentSQLEditorTab,
useCurrentUserIamPolicy,
- useDatabaseV1ByUID,
useDatabaseV1Store,
- useTabStore,
+ useSQLEditorTabStore,
} from "@/store/modules";
import { ComposedDatabase } from "@/types";
@@ -124,7 +124,7 @@ interface LocalState {
const { t } = useI18n();
const databaseStore = useDatabaseV1Store();
-const tabStore = useTabStore();
+const tabStore = useSQLEditorTabStore();
const currentUserIamPolicy = useCurrentUserIamPolicy();
const state = reactive<LocalState>({
databaseNameSearch: "",
@@ -132,14 +132,10 @@ const state = reactive<LocalState>({
});
// Save the stringified label key-value pairs.
const currentTab = computed(() => tabStore.currentTab);
-const connection = computed(() => currentTab.value.connection);
+const { database: selectedDatabase } = useConnectionOfCurrentSQLEditorTab();
const selectedDatabaseNames = ref<string[]>([]);
const hasBatchQueryFeature = hasFeature("bb.feature.batch-query");
-const { database: selectedDatabase } = useDatabaseV1ByUID(
- computed(() => String(connection.value.databaseId))
-);
-
const project = computed(() => selectedDatabase.value.projectEntity);
const databases = computed(() => {
@@ -250,16 +246,15 @@ const handleTriggerClick = () => {
watch(selectedDatabaseNames, () => {
tabStore.updateCurrentTab({
batchQueryContext: {
- selectedDatabaseNames: selectedDatabaseNames.value,
+ databases: selectedDatabaseNames.value,
},
});
});
watch(
- () => currentTab.value.batchQueryContext?.selectedDatabaseNames,
- () => {
- selectedDatabaseNames.value =
- currentTab.value.batchQueryContext?.selectedDatabaseNames || [];
+ () => currentTab.value?.batchQueryContext?.databases,
+ (databases) => {
+ selectedDatabaseNames.value = databases ?? [];
},
{
immediate: true,
diff --git a/frontend/src/views/sql-editor/EditorCommon/ConnectionPathBar.vue b/frontend/src/views/sql-editor/EditorCommon/ConnectionPathBar.vue
index 586aec0105..df3ed07bb5 100644
--- a/frontend/src/views/sql-editor/EditorCommon/ConnectionPathBar.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/ConnectionPathBar.vue
@@ -3,11 +3,11 @@
class="w-full flex flex-col sm:flex-row sm:flex-wrap lg:flex-nowrap lg:justify-between items-start bg-white overflow-hidden"
>
<div
- v-if="!tabStore.isDisconnected"
+ v-if="currentTab && !isDisconnected"
class="flex justify-start items-center h-8 px-4 whitespace-nowrap shrink-0 gap-x-4"
>
<NPopover
- v-if="selectedInstance.uid !== String(UNKNOWN_ID)"
+ v-if="instance.uid !== String(UNKNOWN_ID)"
:disabled="!isProductionEnvironment"
>
<template #trigger>
@@ -19,7 +19,7 @@
: 'border-main text-main',
]"
>
- {{ selectedEnvironment.title }}
+ {{ environment.title }}
</div>
</template>
<template #default>
@@ -31,14 +31,14 @@
<label class="flex items-center text-sm space-x-1">
<div
- v-if="selectedInstance.uid !== String(UNKNOWN_ID)"
+ v-if="instance.uid !== String(UNKNOWN_ID)"
class="flex items-center"
>
- <InstanceV1EngineIcon :instance="selectedInstance" show-status />
- <span class="ml-2">{{ selectedInstance.title }}</span>
+ <InstanceV1EngineIcon :instance="instance" show-status />
+ <span class="ml-2">{{ instance.title }}</span>
</div>
<div
- v-if="selectedDatabaseV1.uid !== String(UNKNOWN_ID)"
+ v-if="database.uid !== String(UNKNOWN_ID)"
class="flex items-center"
>
<span class="mx-2">
@@ -47,7 +47,7 @@
/>
</span>
<heroicons-outline:database />
- <span class="ml-2">{{ selectedDatabaseV1.databaseName }}</span>
+ <span class="ml-2">{{ database.databaseName }}</span>
</div>
<div
@@ -58,11 +58,11 @@
</div>
</label>
- <ReadonlyDatasourceHint :instance="selectedInstance" />
+ <ReadonlyDatasourceHint :instance="instance" />
</div>
<div
- v-if="tabStore.isDisconnected && !currentTab.sheetName"
+ v-else
class="flex justify-start items-center h-8 px-4 whitespace-nowrap overflow-x-auto"
>
<div class="text-sm text-control">
@@ -74,46 +74,43 @@
<script lang="ts" setup>
import { NPopover } from "naive-ui";
+import { storeToRefs } from "pinia";
import { computed } from "vue";
import { InstanceV1EngineIcon } from "@/components/v2";
-import { useTabStore, useDatabaseV1ByUID, useInstanceV1ByUID } from "@/store";
-import { TabMode, UNKNOWN_ID } from "@/types";
+import {
+ useConnectionOfCurrentSQLEditorTab,
+ useSQLEditorTabStore,
+} from "@/store";
+import { UNKNOWN_ID } from "@/types";
import { EnvironmentTier } from "@/types/proto/v1/environment_service";
import BatchQueryDatabasesSelector from "./BatchQueryDatabasesSelector.vue";
import ReadonlyDatasourceHint from "./ReadonlyDatasourceHint.vue";
-const tabStore = useTabStore();
-const currentTab = computed(() => tabStore.currentTab);
-const connection = computed(() => currentTab.value.connection);
+const tabStore = useSQLEditorTabStore();
+const { currentTab, isDisconnected } = storeToRefs(tabStore);
-const { instance: selectedInstance } = useInstanceV1ByUID(
- computed(() => connection.value.instanceId)
-);
-
-const { database: selectedDatabaseV1 } = useDatabaseV1ByUID(
- computed(() => String(connection.value.databaseId))
-);
-
-const selectedEnvironment = computed(() => {
- return connection.value.databaseId === `${UNKNOWN_ID}`
- ? selectedInstance.value.environmentEntity
- : selectedDatabaseV1.value.effectiveEnvironmentEntity;
-});
+const { instance, database, environment } =
+ useConnectionOfCurrentSQLEditorTab();
const isProductionEnvironment = computed(() => {
- if (tabStore.isDisconnected) {
+ if (!currentTab.value) {
+ return false;
+ }
+ if (isDisconnected.value) {
return false;
}
- return selectedEnvironment.value.tier === EnvironmentTier.PROTECTED;
+ return environment.value.tier === EnvironmentTier.PROTECTED;
});
const showBatchQuerySelector = computed(() => {
+ const tab = currentTab.value;
return (
+ tab &&
// Only show entry when user selected a database.
- selectedDatabaseV1.value.uid !== String(UNKNOWN_ID) &&
+ database.value.uid !== String(UNKNOWN_ID) &&
// TODO(steven): implement batch query in admin mode.
- currentTab.value.mode !== TabMode.Admin
+ tab.mode !== "ADMIN"
);
});
</script>
diff --git a/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue b/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue
index fe0dc45e30..d927bc158d 100644
--- a/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue
@@ -85,11 +85,7 @@
<template #trigger>
<NButton
size="small"
- :disabled="
- isEmptyStatement ||
- tabStore.isDisconnected ||
- !tabStore.currentTab.isSaved
- "
+ :disabled="!allowShare"
@click="handleShareButtonClick"
>
<carbon:share class="" /> &nbsp; {{ $t("common.share") }}
@@ -117,20 +113,18 @@
<script lang="ts" setup>
import { useElementSize } from "@vueuse/core";
import { NButtonGroup, NButton, NPopover } from "naive-ui";
-import { computed, reactive, ref, unref } from "vue";
+import { storeToRefs } from "pinia";
+import { computed, reactive, ref } from "vue";
import {
- useTabStore,
- useSQLEditorStore,
useUIStateStore,
featureToRef,
- useInstanceV1ByUID,
- useWebTerminalV1Store,
usePageMode,
useActuatorV1Store,
+ useSQLEditorTabStore,
+ useConnectionOfCurrentSQLEditorTab,
} from "@/store";
-import type { ExecuteConfig, ExecuteOption, FeatureType } from "@/types";
-import { TabMode, UNKNOWN_ID } from "@/types";
-import { formatEngineV1, keyboardShortcutStr } from "@/utils";
+import type { FeatureType, SQLEditorQueryParams } from "@/types";
+import { keyboardShortcutStr } from "@/utils";
import { useSQLEditorContext } from "../context";
import AdminModeButton from "./AdminModeButton.vue";
import QueryContextSettingPopover from "./QueryContextSettingPopover.vue";
@@ -141,21 +135,14 @@ interface LocalState {
}
const emit = defineEmits<{
- (
- e: "execute",
- sql: string,
- config: ExecuteConfig,
- option?: ExecuteOption
- ): void;
+ (e: "execute", params: SQLEditorQueryParams): void;
(e: "clear-screen"): void;
}>();
const actuatorStore = useActuatorV1Store();
const state = reactive<LocalState>({});
-const tabStore = useTabStore();
-const sqlEditorStore = useSQLEditorStore();
+const tabStore = useSQLEditorTabStore();
const uiStateStore = useUIStateStore();
-const webTerminalStore = useWebTerminalV1Store();
const { events } = useSQLEditorContext();
const containerRef = ref<HTMLDivElement>();
const { width: containerWidth } = useElementSize(containerRef);
@@ -163,31 +150,33 @@ const hasSharedSQLScriptFeature = featureToRef("bb.feature.shared-sql-script");
const pageMode = usePageMode();
const isStandaloneMode = computed(() => pageMode.value === "STANDALONE");
+const { currentTab, isDisconnected } = storeToRefs(tabStore);
-const connection = computed(() => tabStore.currentTab.connection);
-
-const isDisconnected = computed(() => {
- return tabStore.isDisconnected;
+const isEmptyStatement = computed(() => {
+ const tab = currentTab.value;
+ if (!tab) {
+ return true;
+ }
+ return tab.statement === "";
});
-const isEmptyStatement = computed(
- () => !tabStore.currentTab || tabStore.currentTab.statement === ""
-);
-const isExecutingSQL = computed(() => tabStore.currentTab.isExecutingSQL);
-const { instance: selectedInstance } = useInstanceV1ByUID(
- computed(() => connection.value.instanceId)
+const isExecutingSQL = computed(
+ () => currentTab.value?.queryContext?.status === "EXECUTING"
);
-const selectedInstanceEngine = computed(() => {
- return formatEngineV1(selectedInstance.value);
-});
+const { instance } = useConnectionOfCurrentSQLEditorTab();
const showSheetsFeature = computed(() => {
- return tabStore.currentTab.mode === TabMode.ReadOnly;
+ const mode = currentTab.value?.mode;
+ return mode === "READONLY" || mode === "STANDARD";
});
const showRunSelected = computed(() => {
+ const tab = currentTab.value;
+ if (!tab) {
+ return false;
+ }
return (
- tabStore.currentTab.mode === TabMode.ReadOnly &&
- !!tabStore.currentTab.selectedStatement
+ (tab.mode === "READONLY" || tab.mode === "STANDARD") &&
+ tab.selectedStatement !== ""
);
});
@@ -206,43 +195,64 @@ const allowSave = computed(() => {
if (isEmptyStatement.value) {
return false;
}
- if (tabStore.currentTab.isSaved) {
+ const tab = currentTab.value;
+ if (!tab) {
return false;
}
- // Temporarily disable saving and sharing if we are connected to an instance
- // but not a database.
- if (tabStore.currentTab.connection.databaseId === String(UNKNOWN_ID)) {
+ if (tab.status === "NEW" || tab.status === "CLEAN") {
return false;
}
+
+ return true;
+});
+
+const allowShare = computed(() => {
+ const tab = currentTab.value;
+ if (!tab) return false;
+ if (tab.status === "NEW" || tab.status === "DIRTY") return false;
+ if (isEmptyStatement.value) return false;
+ if (isDisconnected.value) return false;
return true;
});
const showClearScreen = computed(() => {
- return tabStore.currentTab.mode === TabMode.Admin;
+ return currentTab.value?.mode === "ADMIN";
});
const queryList = computed(() => {
- return (
- unref(
- webTerminalStore.getQueryStateByTab(tabStore.currentTab).queryItemList
- ) || []
- );
+ const tab = currentTab.value;
+ if (!tab) {
+ return [];
+ }
+ // TODO: refactor WebTerminal store types
+ // return unref(webTerminalStore.getQueryStateByTab(tab).queryItemList) || [];
+ return [];
});
const showQueryContextSettingPopover = computed(() => {
+ const tab = currentTab.value;
+ if (!tab) {
+ return false;
+ }
return (
- Boolean(selectedInstance.value) &&
- tabStore.currentTab.mode !== TabMode.Admin &&
+ Boolean(instance.value) &&
+ tab.mode !== "ADMIN" &&
actuatorStore.customTheme === "lixiang"
);
});
-const handleRunQuery = async () => {
- const currentTab = tabStore.currentTab;
- const statement = currentTab.statement;
- const selectedStatement = currentTab.selectedStatement;
- const query = selectedStatement || statement;
- await emit("execute", query, { databaseType: selectedInstanceEngine.value });
+const handleRunQuery = () => {
+ const tab = currentTab.value;
+ if (!tab) {
+ return;
+ }
+ const statement = tab.selectedStatement || tab.statement;
+ emit("execute", {
+ statement,
+ connection: { ...tab.connection },
+ engine: instance.value.engine,
+ explain: false,
+ });
uiStateStore.saveIntroStateByKey({
key: "data.query",
newState: true,
@@ -250,20 +260,21 @@ const handleRunQuery = async () => {
};
const handleExplainQuery = () => {
- const currentTab = tabStore.currentTab;
- const statement = currentTab.statement;
- const selectedStatement = currentTab.selectedStatement;
- const query = selectedStatement || statement;
- emit(
- "execute",
- query,
- { databaseType: selectedInstanceEngine.value },
- { explain: true }
- );
+ const tab = currentTab.value;
+ if (!tab) {
+ return;
+ }
+ const statement = tab.selectedStatement || tab.statement;
+ emit("execute", {
+ statement,
+ connection: { ...tab.connection },
+ engine: instance.value.engine,
+ explain: true,
+ });
};
const handleFormatSQL = () => {
- sqlEditorStore.setShouldFormatContent(true);
+ events.emit("format-content");
};
const handleClearScreen = () => {
@@ -271,8 +282,12 @@ const handleClearScreen = () => {
};
const handleClickSave = () => {
+ const tab = currentTab.value;
+ if (!tab) {
+ return;
+ }
events.emit("save-sheet", {
- tab: tabStore.currentTab,
+ tab,
});
};
diff --git a/frontend/src/views/sql-editor/EditorCommon/ExecuteHint.vue b/frontend/src/views/sql-editor/EditorCommon/ExecuteHint.vue
index 04069bff25..b6245eb776 100644
--- a/frontend/src/views/sql-editor/EditorCommon/ExecuteHint.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/ExecuteHint.vue
@@ -75,9 +75,8 @@ import {
pushNotification,
useActuatorV1Store,
useDatabaseV1Store,
- useTabStore,
+ useSQLEditorTabStore,
} from "@/store";
-import { UNKNOWN_ID } from "@/types";
import { extractProjectResourceName } from "@/utils";
import AdminModeButton from "./AdminModeButton.vue";
@@ -90,15 +89,16 @@ const DMLIssueTemplate = "bb.issue.database.data.update";
const router = useRouter();
const { t } = useI18n();
-const tabStore = useTabStore();
+const tabStore = useSQLEditorTabStore();
const { pageMode } = storeToRefs(useActuatorV1Store());
-const sqlStatement = computed(
- () => tabStore.currentTab.selectedStatement || tabStore.currentTab.statement
-);
+const statement = computed(() => {
+ const tab = tabStore.currentTab;
+ return tab?.selectedStatement || tab?.statement || "";
+});
const isDDL = computedAsync(async () => {
- const { data } = await parseSQL(sqlStatement.value);
+ const { data } = await parseSQL(statement.value);
return data !== null ? isDDLStatement(data, "some") : false;
}, false);
@@ -109,8 +109,8 @@ const handleClose = () => {
};
const gotoCreateIssue = () => {
- const { databaseId } = tabStore.currentTab.connection;
- if (databaseId === String(UNKNOWN_ID)) {
+ const database = tabStore.currentTab?.connection.database ?? "";
+ if (!database) {
pushNotification({
module: "bytebase",
style: "CRITICAL",
@@ -121,22 +121,22 @@ const gotoCreateIssue = () => {
emit("close");
- const database = useDatabaseV1Store().getDatabaseByUID(databaseId);
+ const db = useDatabaseV1Store().getDatabaseByName(database);
router.push({
name: PROJECT_V1_ROUTE_ISSUE_DETAIL,
params: {
- projectId: extractProjectResourceName(database.project),
+ projectId: extractProjectResourceName(db.project),
issueSlug: "create",
},
query: {
template: isDDL.value ? DDLIssueTemplate : DMLIssueTemplate,
- name: `[${database.databaseName}] ${
+ name: `[${db.databaseName}] ${
isDDL.value ? "Alter schema" : "Change Data"
}`,
- project: database.projectEntity.uid,
- databaseList: databaseId,
- sql: sqlStatement.value,
+ project: db.projectEntity.uid,
+ databaseList: db.uid,
+ sql: statement.value,
},
});
};
diff --git a/frontend/src/views/sql-editor/EditorCommon/ExecutingHintModal.vue b/frontend/src/views/sql-editor/EditorCommon/ExecutingHintModal.vue
index aee27449fd..0453ad549e 100644
--- a/frontend/src/views/sql-editor/EditorCommon/ExecutingHintModal.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/ExecutingHintModal.vue
@@ -15,8 +15,6 @@ import ExecuteHint from "./ExecuteHint.vue";
const sqlEditorStore = useSQLEditorStore();
const handleClose = () => {
- sqlEditorStore.setSQLEditorState({
- isShowExecutingHint: false,
- });
+ sqlEditorStore.isShowExecutingHint = false;
};
</script>
diff --git a/frontend/src/views/sql-editor/EditorCommon/QueryContextSettingPopover.vue b/frontend/src/views/sql-editor/EditorCommon/QueryContextSettingPopover.vue
index 6a74593623..b1ad580f30 100644
--- a/frontend/src/views/sql-editor/EditorCommon/QueryContextSettingPopover.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/QueryContextSettingPopover.vue
@@ -1,5 +1,5 @@
<template>
- <NPopover placement="bottom-center" trigger="click">
+ <NPopover placement="bottom" trigger="click">
<template #trigger>
<NButton type="primary" class="!px-1" size="small">
<template #icon>
@@ -33,7 +33,10 @@ import {
} from "naive-ui";
import { computed, h, watch } from "vue";
import { useI18n } from "vue-i18n";
-import { useInstanceV1ByUID, useTabStore } from "@/store";
+import {
+ useConnectionOfCurrentSQLEditorTab,
+ useSQLEditorTabStore,
+} from "@/store";
import { DataSource, DataSourceType } from "@/types/proto/v1/instance_service";
interface DataSourceSelectOption extends SelectOption {
@@ -42,16 +45,13 @@ interface DataSourceSelectOption extends SelectOption {
}
const { t } = useI18n();
-const tabStore = useTabStore();
-const connection = computed(() => tabStore.currentTab.connection);
+const tabStore = useSQLEditorTabStore();
+const { connection, instance: selectedInstance } =
+ useConnectionOfCurrentSQLEditorTab();
const selectedDataSourceId = computed(() => {
return connection.value.dataSourceId;
});
-const { instance: selectedInstance } = useInstanceV1ByUID(
- computed(() => connection.value.instanceId)
-);
-
const dataSources = computed(() => {
return orderBy(selectedInstance.value?.dataSources ?? [], "type");
});
diff --git a/frontend/src/views/sql-editor/EditorCommon/ReadonlyDatasourceHint.vue b/frontend/src/views/sql-editor/EditorCommon/ReadonlyDatasourceHint.vue
index c768b746a5..67b8cd3b60 100644
--- a/frontend/src/views/sql-editor/EditorCommon/ReadonlyDatasourceHint.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/ReadonlyDatasourceHint.vue
@@ -26,8 +26,8 @@
<script setup lang="ts">
import { computed } from "vue";
-import { useCurrentUserV1, useTabStore } from "@/store";
-import { ComposedInstance, TabMode, UNKNOWN_ID } from "@/types";
+import { useCurrentUserV1, useSQLEditorTabStore } from "@/store";
+import { ComposedInstance, UNKNOWN_ID } from "@/types";
import { DataSourceType } from "@/types/proto/v1/instance_service";
import { hasWorkspacePermissionV2 } from "@/utils";
@@ -35,11 +35,11 @@ const props = defineProps<{
instance: ComposedInstance;
}>();
-const tabStore = useTabStore();
+const tabStore = useSQLEditorTabStore();
const me = useCurrentUserV1();
const isAdminMode = computed(() => {
- return tabStore.currentTab.mode === TabMode.Admin;
+ return tabStore.currentTab?.mode === "ADMIN";
});
const allowManageInstance = computed(() => {
diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/TableCell.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/TableCell.vue
index 06daf4d727..b5c373649d 100644
--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/TableCell.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/TableCell.vue
@@ -27,7 +27,7 @@ import { useResizeObserver } from "@vueuse/core";
import { escape } from "lodash-es";
import { NButton } from "naive-ui";
import { computed, ref } from "vue";
-import { useDatabaseV1Store, useTabStore } from "@/store";
+import { useConnectionOfCurrentSQLEditorTab } from "@/store";
import { Engine } from "@/types/proto/v1/common";
import { getHighlightHTMLByRegExp } from "@/utils";
import { useSQLResultViewContext } from "../context";
@@ -55,11 +55,7 @@ useResizeObserver(wrapperRef, (entries) => {
truncated.value = false;
}
});
-
-const database = computed(() => {
- const conn = useTabStore().currentTab.connection;
- return useDatabaseV1Store().getDatabaseByUID(conn.databaseId);
-});
+const { database } = useConnectionOfCurrentSQLEditorTab();
const clickable = computed(() => {
if (truncated.value) return true;
diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/RequestQueryButton.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/RequestQueryButton.vue
index 562e4f80df..703f698a70 100644
--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/RequestQueryButton.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/RequestQueryButton.vue
@@ -16,22 +16,13 @@
<script setup lang="ts">
import { computed, ref } from "vue";
import RequestQueryPanel from "@/components/Issue/panel/RequestQueryPanel/index.vue";
-import { useCurrentUserV1, useDatabaseV1Store, useTabStore } from "@/store";
-import { UNKNOWN_ID, unknownDatabase } from "@/types";
+import { useConnectionOfCurrentSQLEditorTab, useCurrentUserV1 } from "@/store";
+import { UNKNOWN_ID } from "@/types";
import { hasPermissionToCreateRequestGrantIssue } from "@/utils";
-const tabStore = useTabStore();
const me = useCurrentUserV1();
-const connection = computed(() => tabStore.currentTab.connection);
const showPanel = ref(false);
-
-const database = computed(() => {
- const { databaseId } = connection.value;
- if (databaseId !== String(UNKNOWN_ID)) {
- return useDatabaseV1Store().getDatabaseByUID(databaseId);
- }
- return unknownDatabase();
-});
+const { database } = useConnectionOfCurrentSQLEditorTab();
const available = computed(() => {
if (database.value.uid === String(UNKNOWN_ID)) {
diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vue
index b532737be2..7b97a2b7e5 100644
--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vue
@@ -86,15 +86,13 @@ import { useI18n } from "vue-i18n";
import { darkThemeOverrides } from "@/../naive-ui.config";
import { Drawer } from "@/components/v2";
import {
+ useConnectionOfCurrentSQLEditorTab,
useCurrentUserV1,
- useInstanceV1Store,
usePolicyV1Store,
- useTabStore,
} from "@/store";
import {
ComposedDatabase,
- ExecuteConfig,
- ExecuteOption,
+ SQLEditorQueryParams,
SQLResultSetV1,
} from "@/types";
import { PolicyType } from "@/types/proto/v1/org_policy_service";
@@ -114,11 +112,7 @@ type ViewMode = "SINGLE-RESULT" | "MULTI-RESULT" | "EMPTY" | "ERROR";
const props = defineProps({
executeParams: {
- type: Object as PropType<{
- query: string;
- config: ExecuteConfig;
- option?: Partial<ExecuteOption> | undefined;
- }>,
+ type: Object as PropType<SQLEditorQueryParams>,
default: undefined,
},
database: {
@@ -142,7 +136,7 @@ const props = defineProps({
const { t } = useI18n();
const currentUser = useCurrentUserV1();
const policyStore = usePolicyV1Store();
-const connection = computed(() => useTabStore().currentTab.connection);
+const { instance } = useConnectionOfCurrentSQLEditorTab();
const keyword = ref("");
const detail: SQLResultViewContext["detail"] = ref({
show: false,
@@ -196,10 +190,7 @@ const disallowCopyingData = computed(() => {
return false;
}
- const instance = useInstanceV1Store().getInstanceByUID(
- connection.value.instanceId
- );
- const environment = instance.environment;
+ const environment = instance.value.environment;
const policy = policyStore.getPolicyByParentAndType({
parentPath: environment,
policyType: PolicyType.DISABLE_COPY_DATA,
diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultViewV1.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultViewV1.vue
index 03b84e9389..f8ee230563 100644
--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultViewV1.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultViewV1.vue
@@ -22,8 +22,7 @@
}}</span>
<span
v-if="
- currentTab.mode === TabMode.ReadOnly &&
- data.length === RESULT_ROWS_LIMIT
+ currentTab?.mode !== 'ADMIN' && data.length === RESULT_ROWS_LIMIT
"
class="ml-2 whitespace-nowrap text-sm text-gray-500"
>
@@ -142,8 +141,8 @@
</template>
<RequestExportPanel
- v-if="state.showRequestExportPanel"
- :database-id="currentTab.connection.databaseId"
+ v-if="database && state.showRequestExportPanel"
+ :database-id="database.uid"
:statement="result.statement"
:statement-only="true"
:redirect-to-issue-page="pageMode === 'BUNDLED'"
@@ -169,22 +168,19 @@ import { ExportOption } from "@/components/DataExportButton.vue";
import RequestExportPanel from "@/components/Issue/panel/RequestExportPanel/index.vue";
import { DISMISS_PLACEHOLDER } from "@/plugins/ai/components/state";
import {
- useInstanceV1Store,
- useTabStore,
+ useSQLEditorTabStore,
RESULT_ROWS_LIMIT,
featureToRef,
- useDatabaseV1Store,
useCurrentUserV1,
usePageMode,
useActuatorV1Store,
+ useConnectionOfCurrentSQLEditorTab,
} from "@/store";
import { useExportData } from "@/store/modules/export";
import {
ComposedDatabase,
- ExecuteConfig,
- ExecuteOption,
+ SQLEditorQueryParams,
SQLResultSetV1,
- TabMode,
UNKNOWN_ID,
} from "@/types";
import { ExportFormat } from "@/types/proto/v1/common";
@@ -214,11 +210,7 @@ const PAGE_SIZES = [20, 50, 100];
const DEFAULT_PAGE_SIZE = 50;
const props = defineProps<{
- params: {
- query: string;
- config: ExecuteConfig;
- option?: Partial<ExecuteOption> | undefined;
- };
+ params: SQLEditorQueryParams;
database?: ComposedDatabase;
sqlResultSet: SQLResultSetV1;
result: QueryResult;
@@ -235,13 +227,12 @@ const { dark, keyword } = useSQLResultViewContext();
const actuatorStore = useActuatorV1Store();
const { t } = useI18n();
-const tabStore = useTabStore();
-const instanceStore = useInstanceV1Store();
-const databaseStore = useDatabaseV1Store();
+const tabStore = useSQLEditorTabStore();
const currentUserV1 = useCurrentUserV1();
const { exportData } = useExportData();
const currentTab = computed(() => tabStore.currentTab);
const pageMode = usePageMode();
+const { instance: connectedInstance } = useConnectionOfCurrentSQLEditorTab();
const viewMode = computed((): ViewMode => {
const { result } = props;
@@ -259,10 +250,10 @@ const viewMode = computed((): ViewMode => {
});
const showSearchFeature = computed(() => {
- const instance = instanceStore.getInstanceByUID(
- tabStore.currentTab.connection.instanceId
- );
- return instanceV1HasStructuredQueryResult(instance);
+ if (connectedInstance.value.uid === String(UNKNOWN_ID)) {
+ return false;
+ }
+ return instanceV1HasStructuredQueryResult(connectedInstance.value);
});
const showExportButton = computed(() => {
@@ -284,14 +275,13 @@ const allowToExportData = computed(() => {
});
const allowToRequestExportData = computed(() => {
- const { databaseId } = tabStore.currentTab.connection;
- const database =
- databaseId === String(UNKNOWN_ID)
- ? undefined
- : databaseStore.getDatabaseByUID(databaseId);
+ const { database } = props;
if (!database) {
return false;
}
+ if (database.uid === String(UNKNOWN_ID)) {
+ return false;
+ }
return hasPermissionToCreateRequestGrantIssue(database, currentUserV1.value);
});
@@ -380,11 +370,9 @@ const handleExportBtnClick = async (
const instance =
props.database && props.database.uid !== String(UNKNOWN_ID)
? props.database.instance
- : instanceStore.getInstanceByUID(
- tabStore.currentTab.connection.instanceId
- ).name;
+ : connectedInstance.value.name;
const statement = props.result.statement;
- const admin = tabStore.currentTab.mode === TabMode.Admin;
+ const admin = tabStore.currentTab?.mode === "ADMIN";
const limit = options.limit ?? (admin ? 0 : RESULT_ROWS_LIMIT);
const content = await exportData({
@@ -401,23 +389,20 @@ const handleExportBtnClick = async (
};
const showVisualizeButton = computed((): boolean => {
- const instance = instanceStore.getInstanceByUID(
- tabStore.currentTab.connection.instanceId
+ return (
+ connectedInstance.value.engine === Engine.POSTGRES && props.params.explain
);
- const databaseType = instance.engine;
- const { executeParams } = tabStore.currentTab;
- return databaseType === Engine.POSTGRES && !!executeParams?.option?.explain;
});
const visualizeExplain = () => {
try {
- const { executeParams } = tabStore.currentTab;
- if (!executeParams || !props.sqlResultSet) return;
+ const { params, sqlResultSet } = props;
+ if (!sqlResultSet) return;
- const statement = executeParams.query || "";
+ const { statement } = params;
if (!statement) return;
- const explain = explainFromSQLResultSetV1(props.sqlResultSet);
+ const explain = explainFromSQLResultSetV1(sqlResultSet);
if (!explain) return;
const token = createExplainToken(statement, explain);
diff --git a/frontend/src/views/sql-editor/EditorCommon/SaveSheetForm.vue b/frontend/src/views/sql-editor/EditorCommon/SaveSheetForm.vue
index ff6ed61092..77723f1830 100644
--- a/frontend/src/views/sql-editor/EditorCommon/SaveSheetForm.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/SaveSheetForm.vue
@@ -1,44 +1,45 @@
<template>
<div class="save-sheet-modal w-80">
- <n-input
- ref="sheetNameInputRef"
+ <NInput
+ ref="sheetTitleInputRef"
v-model:value="sheetTitle"
:placeholder="$t('sql-editor.save-sheet-input-placeholder')"
@keyup.enter="handleSaveSheet"
/>
</div>
<div class="mt-4 flex justify-end space-x-2">
- <n-button @click="emit('close')">{{ $t("common.close") }}</n-button>
- <n-button type="primary" @click="handleSaveSheet">
+ <NButton @click="emit('close')">{{ $t("common.close") }}</NButton>
+ <NButton type="primary" @click="handleSaveSheet">
{{ $t("common.save") }}
- </n-button>
+ </NButton>
</div>
</template>
<script lang="ts" setup>
+import { NButton, NInput } from "naive-ui";
import { ref, nextTick } from "vue";
-import { TabInfo } from "@/types";
+import { SQLEditorTab } from "@/types";
const props = defineProps<{
- tab: TabInfo;
+ tab: SQLEditorTab;
}>();
const emit = defineEmits<{
(e: "close"): void;
- (e: "confirm", tab: TabInfo): void;
+ (e: "confirm", tab: SQLEditorTab): void;
}>();
-const sheetTitle = ref(props.tab.name);
-const sheetNameInputRef = ref();
+const sheetTitle = ref(props.tab.title);
+const sheetTitleInputRef = ref();
const handleSaveSheet = () => {
emit("confirm", {
...props.tab,
- name: sheetTitle.value,
+ title: sheetTitle.value,
});
};
nextTick(() => {
- sheetNameInputRef.value?.focus();
+ sheetTitleInputRef.value?.focus();
});
</script>
diff --git a/frontend/src/views/sql-editor/EditorCommon/SaveSheetModal.vue b/frontend/src/views/sql-editor/EditorCommon/SaveSheetModal.vue
index 624229f01e..8e2fa60a7c 100644
--- a/frontend/src/views/sql-editor/EditorCommon/SaveSheetModal.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/SaveSheetModal.vue
@@ -15,8 +15,12 @@
<script lang="ts" setup>
import { reactive } from "vue";
import { useEmitteryEventListener } from "@/composables/useEmitteryEventListener";
-import { useDatabaseV1Store, useWorkSheetStore, useTabStore } from "@/store";
-import { UNKNOWN_ID, TabInfo } from "@/types";
+import {
+ useDatabaseV1Store,
+ useWorkSheetStore,
+ useSQLEditorTabStore,
+} from "@/store";
+import { UNKNOWN_ID, SQLEditorTab } from "@/types";
import {
Worksheet,
Worksheet_Visibility,
@@ -27,10 +31,10 @@ import { useSQLEditorContext } from "../context";
import SaveSheetForm from "./SaveSheetForm.vue";
type LocalState = {
- pendingEditTab?: TabInfo;
+ pendingEditTab?: SQLEditorTab;
};
-const tabStore = useTabStore();
+const tabStore = useSQLEditorTabStore();
const databaseStore = useDatabaseV1Store();
const worksheetV1Store = useWorkSheetStore();
const { events: sheetEvents } = useSheetContext();
@@ -38,44 +42,44 @@ const { events: editorEvents } = useSQLEditorContext();
const state = reactive<LocalState>({});
-const doSaveSheet = async (tab: TabInfo) => {
- const { name, statement, sheetName } = tab;
+const doSaveSheet = async (tab: SQLEditorTab) => {
+ const { title, statement, sheet } = tab;
- if (name === "" || statement === "") {
+ if (title === "" || statement === "") {
return;
}
- const sheetId = Number(extractWorksheetUID(sheetName ?? ""));
+ const sheetId = Number(extractWorksheetUID(sheet ?? ""));
if (sheetId !== UNKNOWN_ID) {
- const sheet = await worksheetV1Store.patchSheet(
+ const updatedSheet = await worksheetV1Store.patchSheet(
{
- name: sheetName,
- title: name,
+ name: sheet,
+ title: title,
content: new TextEncoder().encode(statement),
},
["title", "content"]
);
- if (sheet) {
- const tab = tabStore.tabList.find((t) => t.sheetName === sheet.name);
+ if (updatedSheet) {
+ const tab = tabStore.tabList.find((t) => t.sheet === updatedSheet.name);
if (tab) {
tabStore.updateTab(tab.id, {
- isSaved: true,
- name,
+ title,
+ status: "CLEAN",
});
}
}
} else {
- if (tab.connection.databaseId === String(UNKNOWN_ID)) {
+ if (!tab.connection.database) {
return false;
}
- const database = await databaseStore.getOrFetchDatabaseByUID(
- tab.connection.databaseId,
+ const database = await databaseStore.getOrFetchDatabaseByName(
+ tab.connection.database,
true /* silent */
);
- const sheet = await worksheetV1Store.createSheet(
+ const createdSheet = await worksheetV1Store.createSheet(
Worksheet.fromPartial({
- title: name,
+ title,
project: database.project,
content: new TextEncoder().encode(statement),
database: database.name,
@@ -84,9 +88,9 @@ const doSaveSheet = async (tab: TabInfo) => {
);
if (tabStore.currentTabId === tab.id) {
tabStore.updateCurrentTab({
- sheetName: sheet.name,
- isSaved: true,
- name,
+ sheet: createdSheet.name,
+ title,
+ status: "CLEAN",
});
}
}
@@ -96,15 +100,15 @@ const doSaveSheet = async (tab: TabInfo) => {
state.pendingEditTab = undefined;
};
-const needSheetTitle = (tab: TabInfo) => {
- if (tab.sheetName) {
+const needSheetTitle = (tab: SQLEditorTab) => {
+ if (tab.sheet) {
// If the sheet is saved, we don't need to show the name popup.
return false;
}
return true;
};
-const trySaveSheet = (tab: TabInfo, editTitle?: boolean) => {
+const trySaveSheet = (tab: SQLEditorTab, editTitle?: boolean) => {
if (needSheetTitle(tab) || editTitle) {
state.pendingEditTab = tab;
return;
diff --git a/frontend/src/views/sql-editor/EditorCommon/SharePopover.vue b/frontend/src/views/sql-editor/EditorCommon/SharePopover.vue
index 0cbf3d8f8a..655ca9e5ba 100644
--- a/frontend/src/views/sql-editor/EditorCommon/SharePopover.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/SharePopover.vue
@@ -70,18 +70,18 @@
</NPopover>
</section>
<NInputGroup class="flex items-center justify-center">
- <n-input-group-label>
+ <NInputGroupLabel>
<div
class="w-full h-full flex flex-row items-center justify-center m-auto"
>
<heroicons-solid:link class="w-5 h-auto" />
</div>
- </n-input-group-label>
- <n-input v-model:value="sharedTabLink" disabled />
+ </NInputGroupLabel>
+ <NInput v-model:value="sharedTabLink" disabled />
<NButton
class="w-20"
:type="copied ? 'success' : 'primary'"
- :disabled="!tabStore.currentTab.isSaved"
+ :disabled="tabStore.currentTab?.status !== 'CLEAN'"
@click="handleCopy"
>
<heroicons-solid:check v-if="copied" class="h-4 w-4" />
@@ -93,13 +93,20 @@
<script lang="ts" setup>
import { useClipboard } from "@vueuse/core";
+import {
+ NButton,
+ NInput,
+ NInputGroup,
+ NInputGroupLabel,
+ NPopover,
+} from "naive-ui";
import { ref, computed, onMounted } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import { SQL_EDITOR_SHARE_MODULE } from "@/router/sqlEditor";
import {
pushNotification,
- useTabStore,
+ useSQLEditorTabStore,
useWorkSheetStore,
useWorkSheetAndTabStore,
} from "@/store";
@@ -110,7 +117,7 @@ import { worksheetSlugV1 } from "@/utils";
const { t } = useI18n();
const router = useRouter();
-const tabStore = useTabStore();
+const tabStore = useSQLEditorTabStore();
const worksheetV1Store = useWorkSheetStore();
const sheetAndTabStore = useWorkSheetAndTabStore();
diff --git a/frontend/src/views/sql-editor/EditorCommon/SheetConnectionIcon.vue b/frontend/src/views/sql-editor/EditorCommon/SheetConnectionIcon.vue
index e22cb1060a..bc7ecd0bd4 100644
--- a/frontend/src/views/sql-editor/EditorCommon/SheetConnectionIcon.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/SheetConnectionIcon.vue
@@ -9,13 +9,13 @@
import { computed } from "vue";
import { EngineIcon } from "@/components/Icon";
import { useDatabaseV1Store } from "@/store";
-import { TabInfo } from "@/types";
+import { SQLEditorTab } from "@/types";
import { Worksheet } from "@/types/proto/v1/worksheet_service";
-import { connectionForTab } from "@/utils";
+import { connectionForSQLEditorTab } from "@/utils";
const props = defineProps<{
sheet?: Worksheet;
- tab?: TabInfo;
+ tab?: SQLEditorTab;
}>();
const instance = computed(() => {
@@ -26,7 +26,7 @@ const instance = computed(() => {
.instanceEntity;
}
if (tab) {
- return connectionForTab(tab).instance;
+ return connectionForSQLEditorTab(tab).instance;
}
return undefined;
});
diff --git a/frontend/src/views/sql-editor/EditorPanel/EditorPanel.vue b/frontend/src/views/sql-editor/EditorPanel/EditorPanel.vue
index ffd30b30c9..d291238eba 100644
--- a/frontend/src/views/sql-editor/EditorPanel/EditorPanel.vue
+++ b/frontend/src/views/sql-editor/EditorPanel/EditorPanel.vue
@@ -1,11 +1,12 @@
<template>
<div class="flex h-full w-full flex-col justify-start items-start">
- <template v-if="tab.editMode === 'SQL-EDITOR'">
+ <template v-if="!tab || tab.editMode === 'SQL-EDITOR'">
<EditorAction @execute="handleExecute" />
- <ConnectionHolder v-if="tabStore.isDisconnected" />
+ <ConnectionHolder v-if="!tab" />
<template v-else>
<ConnectionPathBar />
+
<Suspense>
<SQLEditor @execute="handleExecute" />
<template #fallback>
@@ -17,34 +18,29 @@
</template>
</Suspense>
</template>
- </template>
- <Suspense>
- <AIChatToSQL
- v-if="!tabStore.isDisconnected && showAIChatBox"
- :allow-config="pageMode === 'BUNDLED'"
- @apply-statement="handleApplyStatement"
- />
- </Suspense>
+ <Suspense>
+ <AIChatToSQL
+ v-if="tab && !isDisconnected && showAIChatBox"
+ :allow-config="pageMode === 'BUNDLED'"
+ @apply-statement="handleApplyStatement"
+ />
+ </Suspense>
- <ExecutingHintModal />
+ <ExecutingHintModal />
- <SaveSheetModal />
+ <SaveSheetModal />
+ </template>
</div>
</template>
<script lang="ts" setup>
+import { storeToRefs } from "pinia";
import { defineAsyncComponent } from "vue";
import { useExecuteSQL } from "@/composables/useExecuteSQL";
import { AIChatToSQL } from "@/plugins/ai";
-import {
- useCurrentTab,
- useInstanceV1Store,
- useTabStore,
- usePageMode,
-} from "@/store";
-import type { Connection, ExecuteConfig, ExecuteOption } from "@/types";
-import { formatEngineV1 } from "@/utils";
+import { useInstanceV1Store, usePageMode, useSQLEditorTabStore } from "@/store";
+import type { SQLEditorConnection, SQLEditorQueryParams } from "@/types";
import {
EditorAction,
ConnectionPathBar,
@@ -56,38 +52,35 @@ import { useSQLEditorContext } from "../context";
const SQLEditor = defineAsyncComponent(() => import("./SQLEditor.vue"));
-const tabStore = useTabStore();
-const tab = useCurrentTab();
+const tabStore = useSQLEditorTabStore();
+const { currentTab: tab, isDisconnected } = storeToRefs(tabStore);
const { showAIChatBox } = useSQLEditorContext();
const pageMode = usePageMode();
const { executeReadonly } = useExecuteSQL();
-const handleExecute = (
- query: string,
- config: ExecuteConfig,
- option?: ExecuteOption
-) => {
- executeReadonly(query, config, option);
+const handleExecute = (params: SQLEditorQueryParams) => {
+ executeReadonly(params);
};
-// const trySaveSheet = (sheetName?: string) => {
-// saveSheetModal.value?.trySaveSheet(sheetName);
-// };
-
const handleApplyStatement = async (
statement: string,
- conn: Connection,
+ connection: SQLEditorConnection,
run: boolean
) => {
+ if (!tab.value) {
+ return;
+ }
tab.value.statement = statement;
if (run) {
- const instanceStore = useInstanceV1Store();
- const instance = await instanceStore.getOrFetchInstanceByUID(
- conn.instanceId
+ const instance = useInstanceV1Store().getInstanceByName(
+ connection.instance
);
- handleExecute(statement, {
- databaseType: formatEngineV1(instance),
+ handleExecute({
+ connection,
+ statement,
+ engine: instance.engine,
+ explain: false,
});
}
};
diff --git a/frontend/src/views/sql-editor/EditorPanel/SQLEditor.vue b/frontend/src/views/sql-editor/EditorPanel/SQLEditor.vue
index 600b3af84b..fa1062db61 100644
--- a/frontend/src/views/sql-editor/EditorPanel/SQLEditor.vue
+++ b/frontend/src/views/sql-editor/EditorPanel/SQLEditor.vue
@@ -22,6 +22,7 @@
</template>
<script lang="ts" setup>
+import { storeToRefs } from "pinia";
import { v1 as uuidv1 } from "uuid";
import { computed, nextTick, ref, watch } from "vue";
import type {
@@ -34,42 +35,36 @@ import {
extensionNameOfLanguage,
formatEditorContent,
} from "@/components/MonacoEditor/utils";
+import { useEmitteryEventListener } from "@/composables/useEmitteryEventListener";
import {
- useTabStore,
- useSQLEditorStore,
useUIStateStore,
- useInstanceV1ByUID,
useWorkSheetAndTabStore,
- useDatabaseV1ByUID,
+ useSQLEditorTabStore,
+ useConnectionOfCurrentSQLEditorTab,
} from "@/store";
-import {
- dialectOfEngineV1,
- ExecuteConfig,
- ExecuteOption,
- SQLDialect,
-} from "@/types";
-import { formatEngineV1, useInstanceV1EditorLanguage } from "@/utils";
+import { dialectOfEngineV1, SQLDialect, SQLEditorQueryParams } from "@/types";
+import { useInstanceV1EditorLanguage } from "@/utils";
import { useSQLEditorContext } from "../context";
const emit = defineEmits<{
- (
- e: "execute",
- sql: string,
- config: ExecuteConfig,
- option?: ExecuteOption
- ): void;
+ (e: "execute", params: SQLEditorQueryParams): void;
}>();
-const tabStore = useTabStore();
-const sqlEditorStore = useSQLEditorStore();
+const tabStore = useSQLEditorTabStore();
const sheetAndTabStore = useWorkSheetAndTabStore();
const uiStateStore = useUIStateStore();
const { events: editorEvents } = useSQLEditorContext();
+const { currentTab } = storeToRefs(tabStore);
+const pendingFormatContentCommand = ref(false);
-const content = computed(() => tabStore.currentTab.statement);
+const content = computed(() => currentTab.value?.statement ?? "");
const advices = computed((): AdviceOption[] => {
+ const tab = currentTab.value;
+ if (!tab) {
+ return [];
+ }
return (
- Array.from(tabStore.currentTab?.databaseQueryResultMap?.values() || [])
+ Array.from(tab.queryContext?.results.values() || [])
.map((result) => result?.advices || [])
.flat() ?? []
).map((advice) => ({
@@ -82,15 +77,7 @@ const advices = computed((): AdviceOption[] => {
source: advice.detail,
}));
});
-const { instance } = useInstanceV1ByUID(
- computed(() => tabStore.currentTab.connection.instanceId)
-);
-const { database } = useDatabaseV1ByUID(
- computed(() => tabStore.currentTab.connection.databaseId)
-);
-const instanceEngine = computed(() => {
- return formatEngineV1(instance.value);
-});
+const { instance, database } = useConnectionOfCurrentSQLEditorTab();
const language = useInstanceV1EditorLanguage(instance);
const dialect = computed((): SQLDialect => {
const engine = instance.value.engine;
@@ -101,7 +88,7 @@ const currentTabId = computed(() => tabStore.currentTabId);
const isSwitchingTab = ref(false);
const filename = computed(() => {
- const name = tabStore.currentTab.id || uuidv1();
+ const name = currentTab.value?.id || uuidv1();
const ext = extensionNameOfLanguage(language.value);
return `${name}.${ext}`;
});
@@ -119,16 +106,20 @@ const handleChange = (value: string) => {
if (isSwitchingTab.value) {
return;
}
- if (value === tabStore.currentTab.statement) {
+ const tab = currentTab.value;
+ if (!tab) {
+ return;
+ }
+ if (value === tab.statement) {
return;
}
// Clear old advices when the statement is changed.
- tabStore.currentTab.databaseQueryResultMap?.forEach((result) => {
+ tab.queryContext?.results.forEach((result) => {
result.advices = [];
});
tabStore.updateCurrentTab({
statement: value,
- isSaved: false,
+ status: "DIRTY",
});
};
@@ -139,13 +130,25 @@ const handleChangeSelection = (value: string) => {
};
const handleSaveSheet = () => {
- editorEvents.emit("save-sheet", { tab: tabStore.currentTab });
+ const tab = currentTab.value;
+ if (!tab) {
+ return;
+ }
+ editorEvents.emit("save-sheet", { tab });
};
const runQueryAction = (explain = false) => {
const tab = tabStore.currentTab;
- const query = tab.selectedStatement || tab.statement || "";
- emit("execute", query, { databaseType: instanceEngine.value }, { explain });
+ if (!tab) {
+ return;
+ }
+ const statement = tab.selectedStatement || tab.statement || "";
+ emit("execute", {
+ connection: { ...tab.connection },
+ statement,
+ engine: instance.value.engine,
+ explain,
+ });
uiStateStore.saveIntroStateByKey({
key: "data.query",
newState: true,
@@ -177,16 +180,19 @@ const handleEditorReady = (
});
watch(
- () => sqlEditorStore.shouldFormatContent,
- async (shouldFormat) => {
- if (shouldFormat) {
- await formatEditorContent(editor, dialect.value);
- sqlEditorStore.setShouldFormatContent(false);
+ pendingFormatContentCommand,
+ (pending) => {
+ if (pending) {
+ formatEditorContent(editor, dialect.value);
+ nextTick(() => {
+ pendingFormatContentCommand.value = false;
+ });
}
},
- {
- immediate: true,
- }
+ { immediate: true }
);
};
+useEmitteryEventListener(editorEvents, "format-content", () => {
+ pendingFormatContentCommand.value = true;
+});
</script>
diff --git a/frontend/src/views/sql-editor/GettingStarted.vue b/frontend/src/views/sql-editor/GettingStarted.vue
index 25999e5b0b..7507ad33e0 100644
--- a/frontend/src/views/sql-editor/GettingStarted.vue
+++ b/frontend/src/views/sql-editor/GettingStarted.vue
@@ -1 +1 @@
-<template>Empty Holder</template>
+<template>Select a database or create a worksheet to start</template>
diff --git a/frontend/src/views/sql-editor/ReadonlyModeNotSupported.vue b/frontend/src/views/sql-editor/ReadonlyModeNotSupported.vue
new file mode 100644
index 0000000000..857f15243a
--- /dev/null
+++ b/frontend/src/views/sql-editor/ReadonlyModeNotSupported.vue
@@ -0,0 +1,23 @@
+<template>
+ <div class="w-full h-full flex flex-col items-center justify-center gap-y-2">
+ <img src="@/assets/illustration/403.webp" class="max-h-[40%]" />
+ <i18n-t
+ class="textinfolabel flex items-center"
+ keypath="sql-editor.allow-admin-mode-only"
+ tag="div"
+ >
+ <template #instance>
+ <InstanceV1Name :instance="instance" :link="false" />
+ </template>
+ </i18n-t>
+ <AdminModeButton />
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { InstanceV1Name } from "@/components/v2";
+import { useConnectionOfCurrentSQLEditorTab } from "@/store";
+import AdminModeButton from "./EditorCommon/AdminModeButton.vue";
+
+const { instance } = useConnectionOfCurrentSQLEditorTab();
+</script>
diff --git a/frontend/src/views/sql-editor/ResultPanel/ResultPanel.vue b/frontend/src/views/sql-editor/ResultPanel/ResultPanel.vue
index f512d747ea..da6e04d3ca 100644
--- a/frontend/src/views/sql-editor/ResultPanel/ResultPanel.vue
+++ b/frontend/src/views/sql-editor/ResultPanel/ResultPanel.vue
@@ -83,19 +83,19 @@ import { head } from "lodash-es";
import { Info, X } from "lucide-vue-next";
import { NButton, NTooltip } from "naive-ui";
import { computed, ref, watch } from "vue";
-import { useDatabaseV1Store, useTabStore } from "@/store";
+import { useDatabaseV1Store, useSQLEditorTabStore } from "@/store";
import { ComposedDatabase } from "@/types";
import { ResultViewV1 } from "../EditorCommon/";
-const tabStore = useTabStore();
+const tabStore = useSQLEditorTabStore();
const databaseStore = useDatabaseV1Store();
const selectedDatabase = ref<ComposedDatabase>();
const batchQueryDatabases = computed(() => {
- return tabStore.currentTab.batchQueryContext?.selectedDatabaseNames || [];
+ return tabStore.currentTab?.batchQueryContext?.databases || [];
});
const queriedDatabaseNames = computed(() =>
- Array.from(tabStore.currentTab.databaseQueryResultMap?.keys() || [])
+ Array.from(tabStore.currentTab?.queryContext?.results.keys() || [])
);
const databases = computed(() => {
return queriedDatabaseNames.value.map((databaseName) => {
@@ -103,26 +103,28 @@ const databases = computed(() => {
});
});
const selectedResultSet = computed(() => {
- return tabStore.currentTab.databaseQueryResultMap?.get(
+ return tabStore.currentTab?.queryContext?.results.get(
selectedDatabase.value?.name || ""
);
});
-const executeParams = computed(() => tabStore.currentTab.executeParams);
-const loading = computed(() => tabStore.currentTab.isExecutingSQL);
+const executeParams = computed(() => tabStore.currentTab?.queryContext?.params);
+const loading = computed(
+ () => tabStore.currentTab?.queryContext?.status === "EXECUTING"
+);
const currentTimestampMS = useTimestamp();
const queryElapsedTime = computed(() => {
if (!loading.value) return "";
const tab = tabStore.currentTab;
- const { isExecutingSQL, queryContext } = tab;
- if (!isExecutingSQL) return "";
- if (!queryContext) return;
+ if (!tab) return "";
+ const { queryContext } = tab;
+ if (!queryContext) return "";
const beginMS = queryContext.beginTimestampMS;
const elapsedMS = currentTimestampMS.value - beginMS;
return `${(elapsedMS / 1000).toFixed(1)}s`;
});
const isDatabaseQueryFailed = (database: ComposedDatabase) => {
- const resultSet = tabStore.currentTab.databaseQueryResultMap?.get(
+ const resultSet = tabStore.currentTab?.queryContext?.results.get(
database.name || ""
);
// If there is any error in the result set, we consider the query failed.
@@ -130,14 +132,11 @@ const isDatabaseQueryFailed = (database: ComposedDatabase) => {
};
const cancelQuery = () => {
- const { queryContext } = tabStore.currentTab;
- if (!queryContext) return;
- const { abortController } = queryContext;
- abortController?.abort();
+ tabStore.currentTab?.queryContext?.abortController.abort();
};
const handleCloseSingleResultView = (database: ComposedDatabase) => {
- tabStore.currentTab.databaseQueryResultMap?.delete(database.name || "");
+ tabStore.currentTab?.queryContext?.results.delete(database.name || "");
};
// Auto select the first database when the databases are ready.
diff --git a/frontend/src/views/sql-editor/SQLEditorPage.vue b/frontend/src/views/sql-editor/SQLEditorPage.vue
index c5bcc05f8d..1f7845558f 100644
--- a/frontend/src/views/sql-editor/SQLEditorPage.vue
+++ b/frontend/src/views/sql-editor/SQLEditorPage.vue
@@ -39,77 +39,53 @@
</template>
<Pane class="relative flex flex-col">
<TabList />
-
<div class="w-full flex-1 overflow-hidden">
- <template v-if="tabStore.currentTab.mode === TabMode.ReadOnly">
- <Splitpanes
- v-if="allowReadOnlyMode"
- horizontal
- class="default-theme"
- :dbl-click-splitter="false"
- >
- <Pane class="flex flex-row overflow-hidden">
- <div class="h-full flex-1 overflow-hidden">
- <Splitpanes
- vertical
- class="default-theme"
- :dbl-click-splitter="false"
- >
- <Pane>
- <EditorPanel />
- </Pane>
- <Pane
- v-if="showSecondarySidebar && windowWidth >= 1024"
- :size="25"
- >
- <SecondarySidebar />
- </Pane>
- </Splitpanes>
- </div>
-
- <div
- v-if="windowWidth >= 1024"
- class="h-full border-l shrink-0"
+ <Splitpanes
+ v-if="
+ !currentTab ||
+ currentTab.mode === 'READONLY' ||
+ currentTab.mode === 'STANDARD'
+ "
+ horizontal
+ class="default-theme"
+ :dbl-click-splitter="false"
+ >
+ <Pane class="flex flex-row overflow-hidden">
+ <div class="h-full flex-1 overflow-hidden">
+ <Splitpanes
+ vertical
+ class="default-theme"
+ :dbl-click-splitter="false"
>
- <SecondaryGutterBar />
- </div>
- </Pane>
- <Pane v-if="!isDisconnected" class="relative" :size="40">
- <ResultPanel />
- </Pane>
- </Splitpanes>
+ <Pane>
+ <EditorPanel v-if="isDisconnected || allowReadonlyMode" />
+ <ReadonlyModeNotSupported v-else />
+ </Pane>
+ <Pane
+ v-if="showSecondarySidebar && windowWidth >= 1024"
+ :size="25"
+ >
+ <SecondarySidebar />
+ </Pane>
+ </Splitpanes>
+ </div>
- <div
- v-else
- class="w-full h-full flex flex-col items-center justify-center gap-y-2"
+ <div v-if="windowWidth >= 1024" class="h-full border-l shrink-0">
+ <SecondaryGutterBar />
+ </div>
+ </Pane>
+ <Pane
+ v-if="!isDisconnected && allowReadonlyMode"
+ class="relative"
+ :size="40"
>
- <img
- src="../../assets/illustration/403.webp"
- class="max-h-[40%]"
- />
- <i18n-t
- class="textinfolabel flex items-center"
- keypath="sql-editor.allow-admin-mode-only"
- tag="div"
- >
- <template #instance>
- <InstanceV1Name :instance="instance" :link="false" />
- </template>
- </i18n-t>
- <AdminModeButton />
- </div>
- </template>
+ <ResultPanel />
+ </Pane>
+ </Splitpanes>
- <TerminalPanelV1 v-if="tabStore.currentTab.mode === TabMode.Admin" />
- <div
- v-else
- class="w-full h-full flex flex-col items-center justify-center"
- >
- <img src="../../assets/illustration/403.webp" class="max-h-[40%]" />
- <div class="textinfolabel">
- {{ $t("database.access-denied") }}
- </div>
- </div>
+ <TerminalPanelV1 v-else-if="currentTab.mode === 'ADMIN'" />
+
+ <AccessDenied v-else />
</div>
<div
@@ -131,50 +107,56 @@
<SchemaEditorModal
v-if="alterSchemaState.showModal"
- :database-id-list="alterSchemaState.databaseIdList.map((id) => `${id}`)"
+ :database-id-list="alterSchemaState.databaseIdList"
:new-window="true"
alter-type="SINGLE_DB"
@close="alterSchemaState.showModal = false"
/>
+
+ <teleport to="#sql-editor-debug">
+ <li>[Page]isDisconnected: {{ isDisconnected }}</li>
+ <li>[Page]currentTab.id: {{ currentTab?.id }}</li>
+ <li>[Page]currentTab.connection: {{ currentTab?.connection }}</li>
+ </teleport>
</div>
</template>
<script lang="ts" setup>
import { useWindowSize } from "@vueuse/core";
+import { storeToRefs } from "pinia";
import { Splitpanes, Pane } from "splitpanes";
import { computed, reactive } from "vue";
import { useRouter } from "vue-router";
import SchemaEditorModal from "@/components/AlterSchemaPrepForm/SchemaEditorModal.vue";
-import { Drawer, DrawerContent, InstanceV1Name } from "@/components/v2";
+import { Drawer, DrawerContent } from "@/components/v2";
import { useEmitteryEventListener } from "@/composables/useEmitteryEventListener";
import { PROJECT_V1_ROUTE_ISSUE_DETAIL } from "@/router/dashboard/projectV1";
import {
useActuatorV1Store,
+ useConnectionOfCurrentSQLEditorTab,
useDatabaseV1Store,
- useInstanceV1ByUID,
- useSQLEditorStore,
- useTabStore,
+ useSQLEditorTabStore,
} from "@/store";
-import { DatabaseId, TabMode } from "@/types";
import {
allowUsingSchemaEditorV1,
extractProjectResourceName,
instanceV1HasReadonlyMode,
} from "@/utils";
+import AccessDenied from "./AccessDenied.vue";
import AsidePanel from "./AsidePanel/AsidePanel.vue";
-import AdminModeButton from "./EditorCommon/AdminModeButton.vue";
import EditorPanel from "./EditorPanel/EditorPanel.vue";
+import ReadonlyModeNotSupported from "./ReadonlyModeNotSupported.vue";
import ResultPanel from "./ResultPanel";
import {
- provideSecondarySidebarContext,
default as SecondarySidebar,
+ useSecondarySidebarContext,
} from "./SecondarySidebar";
import { SecondaryGutterBar } from "./SecondarySidebar";
-import { provideSheetContext } from "./Sheet";
+import { useSheetContext } from "./Sheet";
import SheetPanel from "./SheetPanel";
import TabList from "./TabList";
import TerminalPanelV1 from "./TerminalPanel/TerminalPanelV1.vue";
-import { provideSQLEditorContext } from "./context";
+import { useSQLEditorContext } from "./context";
type LocalState = {
sidebarExpanded: boolean;
@@ -182,7 +164,7 @@ type LocalState = {
type AlterSchemaState = {
showModal: boolean;
- databaseIdList: DatabaseId[];
+ databaseIdList: string[];
};
const state = reactive<LocalState>({
@@ -190,29 +172,23 @@ const state = reactive<LocalState>({
});
const router = useRouter();
-const tabStore = useTabStore();
const databaseStore = useDatabaseV1Store();
const actuatorStore = useActuatorV1Store();
-const sqlEditorStore = useSQLEditorStore();
-// provide context for SQL Editor
-const { events: editorEvents } = provideSQLEditorContext();
-// provide context for sheets
-const { showPanel: showSheetPanel } = provideSheetContext();
-const { show: showSecondarySidebar } = provideSecondarySidebarContext();
+const tabStore = useSQLEditorTabStore();
+const { events: editorEvents } = useSQLEditorContext();
+const { showPanel: showSheetPanel } = useSheetContext();
+const { show: showSecondarySidebar } = useSecondarySidebarContext();
+const { currentTab, isDisconnected } = storeToRefs(tabStore);
const showQuickstart = computed(() => actuatorStore.pageMode === "BUNDLED");
-
-const isDisconnected = computed(() => tabStore.isDisconnected);
-const isFetchingSheet = computed(() => sqlEditorStore.isFetchingSheet);
+const isFetchingSheet = computed(() => false /* editorStore.isFetchingSheet */);
const { width: windowWidth } = useWindowSize();
-const { instance } = useInstanceV1ByUID(
- computed(() => tabStore.currentTab.connection.instanceId)
-);
+const { instance } = useConnectionOfCurrentSQLEditorTab();
-const allowReadOnlyMode = computed(() => {
- if (isDisconnected.value) return true;
+const allowReadonlyMode = computed(() => {
+ if (isDisconnected.value) return false;
return instanceV1HasReadonlyMode(instance.value);
});
@@ -229,7 +205,7 @@ useEmitteryEventListener(
const database = databaseStore.getDatabaseByUID(databaseUID);
if (allowUsingSchemaEditorV1([database])) {
// TODO: support open selected database tab directly in Schema Editor.
- alterSchemaState.databaseIdList = [databaseUID].map((uid) => Number(uid));
+ alterSchemaState.databaseIdList = [databaseUID];
alterSchemaState.showModal = true;
} else {
const exampleSQL = ["ALTER TABLE"];
@@ -261,7 +237,7 @@ useEmitteryEventListener(
);
</script>
-<style>
+<style lang="postcss">
@import "splitpanes/dist/splitpanes.css";
/* splitpanes pane style */
diff --git a/frontend/src/views/sql-editor/SecondarySidebar/HistoryTabPane/HistoryConnectionIcon.vue b/frontend/src/views/sql-editor/SecondarySidebar/HistoryTabPane/HistoryConnectionIcon.vue
index b2bf951ed7..d630313593 100644
--- a/frontend/src/views/sql-editor/SecondarySidebar/HistoryTabPane/HistoryConnectionIcon.vue
+++ b/frontend/src/views/sql-editor/SecondarySidebar/HistoryTabPane/HistoryConnectionIcon.vue
@@ -10,15 +10,14 @@
<script setup lang="ts">
import { computed } from "vue";
import { InstanceV1EngineIcon } from "@/components/v2";
-import { useInstanceV1ByUID } from "@/store";
-import { QueryHistory, UNKNOWN_ID } from "@/types";
+import { useInstanceV1Store } from "@/store";
+import { SQLEditorQueryHistory, UNKNOWN_ID } from "@/types";
const props = defineProps<{
- queryHistory: QueryHistory;
+ queryHistory: SQLEditorQueryHistory;
}>();
-const instanceUID = computed(() => {
- return String(props.queryHistory.instanceId);
+const instance = computed(() => {
+ return useInstanceV1Store().getInstanceByName(props.queryHistory.instance);
});
-const { instance } = useInstanceV1ByUID(instanceUID);
</script>
diff --git a/frontend/src/views/sql-editor/SecondarySidebar/HistoryTabPane/HistoryTabPane.vue b/frontend/src/views/sql-editor/SecondarySidebar/HistoryTabPane/HistoryTabPane.vue
index 1949618510..9dfe8c6ebe 100644
--- a/frontend/src/views/sql-editor/SecondarySidebar/HistoryTabPane/HistoryTabPane.vue
+++ b/frontend/src/views/sql-editor/SecondarySidebar/HistoryTabPane/HistoryTabPane.vue
@@ -52,7 +52,7 @@
</div>
<div
- v-show="isLoading && sqlEditorStore.queryHistoryList.length === 0"
+ v-show="isFetching && queryHistoryList.length === 0"
class="absolute w-full h-full flex justify-center items-center"
>
<BBSpin :title="$t('common.loading')" />
@@ -64,26 +64,27 @@
import { useClipboard } from "@vueuse/core";
import dayjs from "dayjs";
import { escape } from "lodash-es";
+import { storeToRefs } from "pinia";
import { computed, onMounted, reactive } from "vue";
import { useI18n } from "vue-i18n";
import {
pushNotification,
- useTabStore,
- useSQLEditorStore,
- searchConnectionByName,
+ useSQLEditorQueryHistoryStore,
+ useSQLEditorTabStore,
} from "@/store";
-import { QueryHistory } from "@/types";
+import { SQLEditorQueryHistory } from "@/types";
import { getHighlightHTMLByKeyWords } from "@/utils";
import HistoryConnectionIcon from "./HistoryConnectionIcon.vue";
interface State {
search: string;
- currentActionHistory: QueryHistory | null;
+ currentActionHistory: SQLEditorQueryHistory | null;
}
const { t } = useI18n();
-const tabStore = useTabStore();
-const sqlEditorStore = useSQLEditorStore();
+const tabStore = useSQLEditorTabStore();
+const queryHistoryStore = useSQLEditorQueryHistoryStore();
+const { isFetching, queryHistoryList } = storeToRefs(queryHistoryStore);
const state = reactive<State>({
search: "",
@@ -94,15 +95,10 @@ const { copy: copyTextToClipboard, isSupported } = useClipboard({
legacy: true,
});
-const isLoading = computed(() => {
- return sqlEditorStore.isFetchingQueryHistory;
-});
-
const data = computed(() => {
const tempData =
- sqlEditorStore.queryHistoryList &&
- sqlEditorStore.queryHistoryList.length > 0
- ? sqlEditorStore.queryHistoryList.filter((history) => {
+ queryHistoryList.value.length > 0
+ ? queryHistoryList.value.filter((history) => {
let t = false;
if (history.statement.includes(state.search)) {
@@ -126,22 +122,22 @@ const data = computed(() => {
});
});
-const titleOfQueryHistory = (history: QueryHistory) => {
+const titleOfQueryHistory = (history: SQLEditorQueryHistory) => {
return dayjs(history.createTime).format("YYYY-MM-DD HH:mm:ss");
};
const notifyMessage = computed(() => {
- if (isLoading.value) {
+ if (isFetching.value) {
return "";
}
- if (sqlEditorStore.queryHistoryList.length === null) {
+ if (queryHistoryList.value.length === 0) {
return t("sql-editor.no-history-found");
}
return "";
});
-const handleCopy = (history: QueryHistory) => {
+const handleCopy = (history: SQLEditorQueryHistory) => {
if (!isSupported.value) {
pushNotification({
module: "bytebase",
@@ -160,27 +156,21 @@ const handleCopy = (history: QueryHistory) => {
});
};
-const handleQueryHistoryClick = async (queryHistory: QueryHistory) => {
- const { instanceId, databaseId, instanceName, databaseName, statement } =
- queryHistory;
- const connection = searchConnectionByName(
- String(instanceId),
- String(databaseId),
- instanceName,
- databaseName
- );
+const handleQueryHistoryClick = async (queryHistory: SQLEditorQueryHistory) => {
+ const { instance, database, statement } = queryHistory;
// Open a new tab with the connection and statement.
tabStore.addTab({
- name: `Query history at ${titleOfQueryHistory(queryHistory)}`,
- });
- tabStore.updateCurrentTab({
- connection,
+ title: `Query history at ${titleOfQueryHistory(queryHistory)}`,
+ connection: {
+ instance,
+ database,
+ },
statement,
});
};
onMounted(async () => {
- await sqlEditorStore.fetchQueryHistoryList();
+ await queryHistoryStore.fetchQueryHistoryList();
});
</script>
diff --git a/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/SchemaPanel.vue b/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/SchemaPanel.vue
index 48f003b6b0..f2ee910327 100644
--- a/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/SchemaPanel.vue
+++ b/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/SchemaPanel.vue
@@ -61,9 +61,11 @@
<script lang="ts" setup>
import { asyncComputed } from "@vueuse/core";
-import { storeToRefs } from "pinia";
import { computed, ref } from "vue";
-import { useDatabaseV1ByUID, useDBSchemaV1Store, useTabStore } from "@/store";
+import {
+ useConnectionOfCurrentSQLEditorTab,
+ useDBSchemaV1Store,
+} from "@/store";
import {
SchemaMetadata,
TableMetadata,
@@ -80,12 +82,10 @@ import { provideSchemaPanelContext } from "./context";
const { selectedDatabaseSchemaByDatabaseName } = useSQLEditorContext();
const dbSchemaStore = useDBSchemaV1Store();
-const { currentTab } = storeToRefs(useTabStore());
-const conn = computed(() => currentTab.value.connection);
+const { database } = useConnectionOfCurrentSQLEditorTab();
const { keyword } = provideSchemaPanelContext();
provideHoverStateContext();
-const { database } = useDatabaseV1ByUID(computed(() => conn.value.databaseId));
const isLoading = ref(false);
const databaseMetadata = asyncComputed(
async () => {
diff --git a/frontend/src/views/sql-editor/SecondarySidebar/SecondaryGutterBar/OpenAIButton.vue b/frontend/src/views/sql-editor/SecondarySidebar/SecondaryGutterBar/OpenAIButton.vue
index 33e8500846..bc1370c0ca 100644
--- a/frontend/src/views/sql-editor/SecondarySidebar/SecondaryGutterBar/OpenAIButton.vue
+++ b/frontend/src/views/sql-editor/SecondarySidebar/SecondaryGutterBar/OpenAIButton.vue
@@ -36,10 +36,10 @@
<script setup lang="ts">
import { ButtonProps, NButton, NTooltip } from "naive-ui";
import { computed } from "vue";
-import { useSettingV1Store, useTabStore } from "@/store";
+import { useSettingV1Store, useSQLEditorTabStore } from "@/store";
import { useSQLEditorContext } from "../../context";
-const tabStore = useTabStore();
+const tabStore = useSQLEditorTabStore();
const settingV1Store = useSettingV1Store();
const openAIKeySetting = computed(() =>
settingV1Store.getSettingByName("bb.plugin.openai.key")
diff --git a/frontend/src/views/sql-editor/SecondarySidebar/SecondaryGutterBar/SecondaryGutterBar.vue b/frontend/src/views/sql-editor/SecondarySidebar/SecondaryGutterBar/SecondaryGutterBar.vue
index 0b263fde50..363b5ee7bd 100644
--- a/frontend/src/views/sql-editor/SecondarySidebar/SecondaryGutterBar/SecondaryGutterBar.vue
+++ b/frontend/src/views/sql-editor/SecondarySidebar/SecondaryGutterBar/SecondaryGutterBar.vue
@@ -30,19 +30,15 @@
</template>
<script setup lang="ts">
+import { storeToRefs } from "pinia";
import { computed, watch } from "vue";
import {
+ useConnectionOfCurrentSQLEditorTab,
useCurrentUserV1,
- useDatabaseV1Store,
- useInstanceV1Store,
- useTabStore,
+ useSQLEditorTabStore,
} from "@/store";
import { UNKNOWN_ID } from "@/types";
-import {
- hasProjectPermissionV2,
- instanceV1HasAlterSchema,
- isDisconnectedTab,
-} from "@/utils";
+import { hasProjectPermissionV2, instanceV1HasAlterSchema } from "@/utils";
import { TabView, useSecondarySidebarContext } from "../context";
import OpenAIButton from "./OpenAIButton.vue";
@@ -56,44 +52,41 @@ const activeTab = computed(() => {
return tab.value;
});
-const tabStore = useTabStore();
-
-const isDisconnected = computed(() => {
- return isDisconnectedTab(tabStore.currentTab);
-});
+const tabStore = useSQLEditorTabStore();
+const { currentTab, isDisconnected } = storeToRefs(tabStore);
+const { instance, database } = useConnectionOfCurrentSQLEditorTab();
const isSchemalessInstance = computed(() => {
+ if (!currentTab.value) {
+ return false;
+ }
if (isDisconnected.value) {
return false;
}
- const { instanceId } = tabStore.currentTab.connection;
-
- if (instanceId === String(UNKNOWN_ID)) {
+ if (instance.value.uid === String(UNKNOWN_ID)) {
return false;
}
- const instance = useInstanceV1Store().getInstanceByUID(instanceId);
-
- return !instanceV1HasAlterSchema(instance);
+ return !instanceV1HasAlterSchema(instance.value);
});
const showInfoPane = computed(() => {
- if (isDisconnected.value) {
+ if (!currentTab.value) {
return false;
}
-
- const conn = tabStore.currentTab.connection;
- if (conn.databaseId === String(UNKNOWN_ID)) {
+ if (isDisconnected.value) {
return false;
}
if (isSchemalessInstance.value) {
return false;
}
+ if (database.value.uid === String(UNKNOWN_ID)) {
+ return false;
+ }
- const database = useDatabaseV1Store().getDatabaseByUID(conn.databaseId);
return hasProjectPermissionV2(
- database.projectEntity,
+ database.value.projectEntity,
me.value,
"bb.databases.getSchema"
);
diff --git a/frontend/src/views/sql-editor/SecondarySidebar/SheetTabPane/SheetList/SheetList.vue b/frontend/src/views/sql-editor/SecondarySidebar/SheetTabPane/SheetList/SheetList.vue
index f076cc1fd0..01e14fd645 100644
--- a/frontend/src/views/sql-editor/SecondarySidebar/SheetTabPane/SheetList/SheetList.vue
+++ b/frontend/src/views/sql-editor/SecondarySidebar/SheetTabPane/SheetList/SheetList.vue
@@ -80,17 +80,18 @@ import {
useProjectV1Store,
useWorkSheetAndTabStore,
useDatabaseV1Store,
- useTabStore,
+ useSQLEditorTabStore,
} from "@/store";
import { ComposedProject, ComposedDatabase, UNKNOWN_ID } from "@/types";
-import { connectionForTab } from "@/utils";
+import { connectionForSQLEditorTab } from "@/utils";
import {
SheetViewMode,
- openSheet,
+ openWorksheetByName,
useSheetContextByView,
Dropdown,
useSheetContext,
} from "@/views/sql-editor/Sheet";
+import { useSQLEditorContext } from "@/views/sql-editor/context";
import UnsavedPrefix from "./UnsavedPrefix.vue";
import {
DropdownState,
@@ -98,6 +99,7 @@ import {
domIDForItem,
isSheetItem,
isTabItem,
+ keyOfItem,
} from "./common";
interface TreeNode extends TreeOption {
@@ -127,8 +129,10 @@ const props = defineProps<{
const { t } = useI18n();
const databaseStore = useDatabaseV1Store();
const projectStore = useProjectV1Store();
-const tabStore = useTabStore();
-const { showPanel } = useSheetContext();
+const tabStore = useSQLEditorTabStore();
+const editorContext = useSQLEditorContext();
+const worksheetContext = useSheetContext();
+const { showPanel } = worksheetContext;
const { isInitialized, isLoading, sheetList, fetchSheetList } =
useSheetContextByView(props.view);
const keyword = ref("");
@@ -156,7 +160,7 @@ const mergedItemList = computed(() => {
// They are probably dirty data
(item) => (item.type === "SHEET" && !item.target.title ? 1 : 0),
// Alphabetically otherwise
- (item) => (item.type === "TAB" ? item.target.name : item.target.title),
+ (item) => item.target.title,
],
["asc", "asc"]
);
@@ -169,7 +173,7 @@ const treeData = computed((): TreeNode[] => {
let database: ComposedDatabase | undefined;
let project: ComposedProject | undefined;
if (isTabItem(item)) {
- database = connectionForTab(item.target).database;
+ database = connectionForSQLEditorTab(item.target).database;
project = database?.projectEntity;
} else {
database = databaseStore.getDatabaseByName(item.target.database);
@@ -186,6 +190,7 @@ const treeData = computed((): TreeNode[] => {
};
}
+ const key = keyOfItem(item);
if (database && database.uid !== `${UNKNOWN_ID}`) {
if (!map[project.name].children[database.name]) {
map[project.name].children[database.name] = {
@@ -195,16 +200,16 @@ const treeData = computed((): TreeNode[] => {
children: {},
};
}
- map[project.name].children[database.name].children[item.target.name] = {
- key: item.target.name,
- label: isTabItem(item) ? item.target.name : item.target.title,
+ map[project.name].children[database.name].children[key] = {
+ key,
+ label: item.target.title,
item,
children: {},
};
} else {
- map[project.name].children[item.target.name] = {
- key: item.target.name,
- label: isTabItem(item) ? item.target.name : item.target.title,
+ map[project.name].children[key] = {
+ key,
+ label: item.target.title,
item,
children: {},
};
@@ -256,16 +261,15 @@ const renderSuffix = ({ option }: { option: TreeOption }) => {
return null;
}
const child = [];
- if (isTabItem(treeNode.item)) {
+ const { item } = treeNode;
+ if (isTabItem(item)) {
child.push(h(UnsavedPrefix));
} else {
- const tab = tabStore.tabList.find(
- (tab) => tab.sheetName === treeNode.item?.target.name
- );
- if (tab?.isSaved ?? true) {
+ const tab = tabStore.tabList.find((tab) => tab.sheet === item.target.name);
+ if (tab?.status === "CLEAN") {
child.push(
h(Dropdown, {
- sheet: treeNode.item.target,
+ sheet: item.target,
view: props.view,
secondary: true,
})
@@ -314,9 +318,9 @@ const renderLabel = ({ option }: { option: TreeOption }) => {
};
const selectedKeys = computed(() => {
- return [currentSheet.value?.name, tabStore.currentTab.id].filter(
- (item) => !!item
- ) as string[];
+ return [currentSheet.value?.name, tabStore.currentTab?.id].filter(
+ (item): item is string => !!item
+ );
});
const nodeProps = ({ option }: { option: TreeOption }) => {
@@ -341,7 +345,12 @@ const handleItemClick = (item: MergedItem, e: MouseEvent) => {
if (isTabItem(item)) {
tabStore.setCurrentTabId(item.target.id);
} else {
- openSheet(item.target.name, e.metaKey || e.ctrlKey);
+ openWorksheetByName(
+ item.target.name,
+ editorContext,
+ worksheetContext,
+ e.metaKey || e.ctrlKey
+ );
}
};
@@ -374,6 +383,9 @@ const scrollToCurrentTabOrSheet = () => {
scrollToItem({ type: "SHEET", target: currentSheet.value });
} else {
const tab = tabStore.currentTab;
+ if (!tab) {
+ return;
+ }
scrollToItem({ type: "TAB", target: tab });
}
};
@@ -391,7 +403,7 @@ watch(
);
watch(
- [() => currentSheet.value?.name, () => tabStore.currentTab.id],
+ [() => currentSheet.value?.name, () => tabStore.currentTab?.id],
() => {
scrollToCurrentTabOrSheet();
},
diff --git a/frontend/src/views/sql-editor/SecondarySidebar/SheetTabPane/SheetList/common.ts b/frontend/src/views/sql-editor/SecondarySidebar/SheetTabPane/SheetList/common.ts
index e49ccf24b7..902c2b74c3 100644
--- a/frontend/src/views/sql-editor/SecondarySidebar/SheetTabPane/SheetList/common.ts
+++ b/frontend/src/views/sql-editor/SecondarySidebar/SheetTabPane/SheetList/common.ts
@@ -1,11 +1,11 @@
import { escape } from "lodash-es";
-import { TabInfo } from "@/types";
+import { SQLEditorTab } from "@/types";
import { Worksheet } from "@/types/proto/v1/worksheet_service";
import { extractWorksheetUID, getHighlightHTMLByRegExp } from "@/utils";
export type TabItem = {
type: "TAB";
- target: TabInfo;
+ target: SQLEditorTab;
};
export type SheetItem = {
type: "SHEET";
@@ -19,19 +19,24 @@ export const isSheetItem = (item: MergedItem): item is SheetItem => {
return item.type === "SHEET";
};
+export const keyOfItem = (item: MergedItem) => {
+ return isTabItem(item) ? item.target.id : item.target.name;
+};
+
export const domIDForItem = (item: MergedItem) => {
+ const key = keyOfItem(item);
if (isTabItem(item)) {
// tab
- return `bb-sheet-list-tab-${item.target.id}`;
+ return `bb-sheet-list-tab-${key}`;
}
// sheet
- return `bb-sheet-list-sheet-${extractWorksheetUID(item.target.name)}`;
+ return `bb-sheet-list-sheet-${extractWorksheetUID(key)}`;
};
export const titleHTML = (item: MergedItem, keyword: string) => {
const kw = keyword.toLowerCase().trim();
- const title = isTabItem(item) ? item.target.name : item.target.title;
+ const title = item.target.title;
if (!kw) {
return escape(title);
diff --git a/frontend/src/views/sql-editor/SecondarySidebar/SheetTabPane/SheetTabPane.vue b/frontend/src/views/sql-editor/SecondarySidebar/SheetTabPane/SheetTabPane.vue
index 57c30dac61..4c49346e7f 100644
--- a/frontend/src/views/sql-editor/SecondarySidebar/SheetTabPane/SheetTabPane.vue
+++ b/frontend/src/views/sql-editor/SecondarySidebar/SheetTabPane/SheetTabPane.vue
@@ -28,7 +28,7 @@ import { computed, ref, watch } from "vue";
import { useEmitteryEventListener } from "@/composables/useEmitteryEventListener";
import {
usePageMode,
- useTabStore,
+ useSQLEditorTabStore,
useWorkSheetStore,
useCurrentUserV1,
} from "@/store";
@@ -37,7 +37,7 @@ import SheetList from "./SheetList";
const { events: sheetEvents } = useSheetContext();
const pageMode = usePageMode();
-const tabStore = useTabStore();
+const tabStore = useSQLEditorTabStore();
const sheetStore = useWorkSheetStore();
const me = useCurrentUserV1();
@@ -52,10 +52,13 @@ useEmitteryEventListener(sheetEvents, "add-sheet", () => {
watch(
() => tabStore.currentTab,
(tab) => {
- if (!tab.isSaved || !tab.sheetName) {
+ if (!tab) {
return;
}
- const sheet = sheetStore.getSheetByName(tab.sheetName);
+ if (tab.sheet) {
+ return;
+ }
+ const sheet = sheetStore.getSheetByName(tab.sheet);
if (!sheet) {
return;
}
diff --git a/frontend/src/views/sql-editor/Sheet/common/Dropdown.vue b/frontend/src/views/sql-editor/Sheet/common/Dropdown.vue
index 8e8d92af34..461171b7ad 100644
--- a/frontend/src/views/sql-editor/Sheet/common/Dropdown.vue
+++ b/frontend/src/views/sql-editor/Sheet/common/Dropdown.vue
@@ -23,15 +23,19 @@ import {
} from "naive-ui";
import { computed } from "vue";
import { useI18n } from "vue-i18n";
-import { useWorkSheetStore, pushNotification, useTabStore } from "@/store";
+import {
+ useWorkSheetStore,
+ pushNotification,
+ useSQLEditorTabStore,
+} from "@/store";
import {
Worksheet,
Worksheet_Visibility,
} from "@/types/proto/v1/worksheet_service";
import {
isWorksheetWritableV1,
- getDefaultTab,
getSheetStatement,
+ defaultSQLEditorTab,
} from "@/utils";
import { useSheetContext, type SheetViewMode } from "../";
import { useSQLEditorContext } from "../../context";
@@ -158,9 +162,9 @@ const handleAction = async (key: string) => {
} else if (key === "rename") {
editorEvents.emit("save-sheet", {
tab: {
- ...getDefaultTab(),
- sheetName: sheet.name,
- name: sheet.title,
+ ...defaultSQLEditorTab(),
+ sheet: sheet.name,
+ title: sheet.title,
statement: getSheetStatement(sheet),
},
editTitle: true,
@@ -169,8 +173,8 @@ const handleAction = async (key: string) => {
};
const turnSheetToUnsavedTab = (sheet: Worksheet) => {
- const tabStore = useTabStore();
- const tab = tabStore.tabList.find((tab) => tab.sheetName === sheet.name);
+ const tabStore = useSQLEditorTabStore();
+ const tab = tabStore.tabList.find((tab) => tab.sheet === sheet.name);
if (tab) {
tabStore.removeTab(tab);
}
diff --git a/frontend/src/views/sql-editor/Sheet/context.ts b/frontend/src/views/sql-editor/Sheet/context.ts
index c8128d33aa..3ad3997a12 100644
--- a/frontend/src/views/sql-editor/Sheet/context.ts
+++ b/frontend/src/views/sql-editor/Sheet/context.ts
@@ -1,21 +1,21 @@
import Emittery from "emittery";
-import { storeToRefs } from "pinia";
import { InjectionKey, Ref, inject, provide, ref, computed } from "vue";
import { t } from "@/plugins/i18n";
import {
pushNotification,
useDatabaseV1Store,
+ useSQLEditorTabStore,
useWorkSheetStore,
- useTabStore,
- useSQLEditorStore,
} from "@/store";
-import { AnyTabInfo, UNKNOWN_ID } from "@/types";
+import { SQLEditorTab } from "@/types";
+import { Worksheet } from "@/types/proto/v1/worksheet_service";
import {
- emptyConnection,
+ emptySQLEditorConnection,
getSheetStatement,
- getSuggestedTabNameFromConnection,
isWorksheetReadableV1,
+ suggestedTabTitleForSQLEditorConnection,
} from "@/utils";
+import { SQLEditorContext } from "../context";
import { SheetViewMode } from "./types";
type SheetEvents = Emittery<{
@@ -72,6 +72,7 @@ const useSheetListByView = (viewMode: SheetViewMode) => {
export type SheetContext = {
showPanel: Ref<boolean>;
+ isFetching: Ref<boolean>;
view: Ref<SheetViewMode>;
views: Record<SheetViewMode, ReturnType<typeof useSheetListByView>>;
events: SheetEvents;
@@ -91,6 +92,7 @@ export const useSheetContextByView = (view: SheetViewMode) => {
export const provideSheetContext = () => {
const context: SheetContext = {
showPanel: ref(false),
+ isFetching: ref(false),
view: ref("my"),
views: {
my: useSheetListByView("my"),
@@ -109,24 +111,39 @@ export const provideSheetContext = () => {
return context;
};
-export const openSheet = async (name: string, forceNewTab = false) => {
- const { isFetchingSheet } = storeToRefs(useSQLEditorStore());
+export const extractWorksheetConnection = (worksheet: Worksheet) => {
+ const connection = emptySQLEditorConnection();
+ if (worksheet.database) {
+ try {
+ const database = useDatabaseV1Store().getDatabaseByName(
+ worksheet.database
+ );
+ connection.instance = database.instance;
+ connection.database = database.name;
+ } catch {
+ // Skip.
+ }
+ }
+ return connection;
+};
+
+export const openWorksheetByName = async (
+ name: string,
+ editorContext: SQLEditorContext,
+ worksheetContext: SheetContext,
+ forceNewTab = false
+) => {
const cleanup = () => {
- isFetchingSheet.value = false;
+ worksheetContext.isFetching.value = false;
};
- isFetchingSheet.value = true;
+ worksheetContext.isFetching.value = true;
const sheet = await useWorkSheetStore().getOrFetchSheetByName(name);
if (!sheet) {
cleanup();
return false;
}
- const tabStore = useTabStore();
- const openingSheetTab = tabStore.tabList.find(
- (tab) => tab.sheetName === sheet.name
- );
-
if (!isWorksheetReadableV1(sheet)) {
pushNotification({
module: "bytebase",
@@ -139,12 +156,22 @@ export const openSheet = async (name: string, forceNewTab = false) => {
cleanup();
+ await editorContext.maybeSwitchProject(sheet.project);
+ const tabStore = useSQLEditorTabStore();
+ const openingSheetTab = tabStore.tabList.find(
+ (tab) => tab.sheet === sheet.name
+ );
+
const statement = getSheetStatement(sheet);
- const newTab: AnyTabInfo = {
- sheetName: sheet.name,
- name: sheet.title,
+
+ const newTab: Partial<SQLEditorTab> = {
+ connection: extractWorksheetConnection(sheet),
+ sheet: sheet.name,
+ title: sheet.title,
statement,
+ status: "CLEAN",
};
+
if (openingSheetTab) {
// Switch to a sheet tab if it's open already.
tabStore.setCurrentTabId(openingSheetTab.id);
@@ -156,45 +183,17 @@ export const openSheet = async (name: string, forceNewTab = false) => {
tabStore.addTab(newTab);
}
- let insId = String(UNKNOWN_ID);
- let dbId = String(UNKNOWN_ID);
- if (sheet.database) {
- try {
- const database = await useDatabaseV1Store().getOrFetchDatabaseByName(
- sheet.database,
- true /* silent */
- );
- insId = database.instanceEntity.uid;
- dbId = database.uid;
- } catch {
- // Skip.
- }
- }
-
- tabStore.updateCurrentTab({
- sheetName: sheet.name,
- name: sheet.title,
- statement,
- isSaved: true,
- connection: {
- ...emptyConnection(),
- // TODO: legacy instance id.
- instanceId: insId,
- databaseId: dbId,
- },
- });
-
return true;
};
export const addNewSheet = () => {
- const tabStore = useTabStore();
- const connection = { ...tabStore.currentTab.connection };
- const name = getSuggestedTabNameFromConnection(connection);
+ const tabStore = useSQLEditorTabStore();
+ const curr = tabStore.currentTab;
+ const connection = curr ? { ...curr.connection } : emptySQLEditorConnection();
+ const title = suggestedTabTitleForSQLEditorConnection(connection);
tabStore.addTab({
- name,
+ title,
connection,
- // The newly created tab is "clean" so its connection can be changed
- isFreshNew: true,
+ status: "NEW",
});
};
diff --git a/frontend/src/views/sql-editor/SheetPanel/SheetPanel.vue b/frontend/src/views/sql-editor/SheetPanel/SheetPanel.vue
index 15ae748ee2..ec08c8b4e1 100644
--- a/frontend/src/views/sql-editor/SheetPanel/SheetPanel.vue
+++ b/frontend/src/views/sql-editor/SheetPanel/SheetPanel.vue
@@ -39,34 +39,35 @@
</div>
</template>
</NTabs>
- <MaskSpinner v-if="isFetchingSheet" />
+ <MaskSpinner v-if="isFetching" />
</div>
</template>
<script setup lang="ts">
import { NButton, NTabs, NTabPane } from "naive-ui";
-import { storeToRefs } from "pinia";
import { computed, ref } from "vue";
import MaskSpinner from "@/components/misc/MaskSpinner.vue";
import { SearchBox } from "@/components/v2";
-import { usePageMode, useSQLEditorStore } from "@/store";
+import { usePageMode } from "@/store";
import { Worksheet } from "@/types/proto/v1/worksheet_service";
-import { useSheetContext, openSheet, addNewSheet } from "../Sheet";
+import { useSheetContext, openWorksheetByName, addNewSheet } from "../Sheet";
+import { useSQLEditorContext } from "../context";
import SheetTable from "./SheetTable";
const emit = defineEmits<{
(event: "close"): void;
}>();
-const { view, events } = useSheetContext();
-const { isFetchingSheet } = storeToRefs(useSQLEditorStore());
+const editorContext = useSQLEditorContext();
+const worksheetContext = useSheetContext();
+const { view, isFetching, events } = worksheetContext;
const pageMode = usePageMode();
const keyword = ref("");
const isStandaloneMode = computed(() => pageMode.value === "STANDALONE");
const handleSelectSheet = async (sheet: Worksheet) => {
- if (await openSheet(sheet.name)) {
+ if (await openWorksheetByName(sheet.name, editorContext, worksheetContext)) {
emit("close");
}
};
diff --git a/frontend/src/views/sql-editor/TabList/ContextMenu.vue b/frontend/src/views/sql-editor/TabList/ContextMenu.vue
index 1228844b9c..abf0469830 100644
--- a/frontend/src/views/sql-editor/TabList/ContextMenu.vue
+++ b/frontend/src/views/sql-editor/TabList/ContextMenu.vue
@@ -17,7 +17,7 @@
import { NDropdown, DropdownOption } from "naive-ui";
import { computed, nextTick } from "vue";
import { useI18n } from "vue-i18n";
-import { TabInfo, TabMode } from "@/types";
+import { SQLEditorTab } from "@/types";
import { CloseTabAction, useTabListContext } from "./context";
const { t } = useI18n();
@@ -58,7 +58,7 @@ const options = computed((): DropdownOption[] => {
];
const { tab } = state.value;
- if (tab.mode === TabMode.ReadOnly) {
+ if (tab.mode === "READONLY" || tab.mode === "STANDARD") {
const DIVIDER: DropdownOption = {
type: "divider",
key: "DIVIDER",
@@ -74,7 +74,7 @@ const options = computed((): DropdownOption[] => {
return options;
});
-const show = (tab: TabInfo, index: number, e: MouseEvent) => {
+const show = (tab: SQLEditorTab, index: number, e: MouseEvent) => {
e.preventDefault();
e.stopPropagation();
state.value = undefined;
diff --git a/frontend/src/views/sql-editor/TabList/TabItem/AdminLabel.vue b/frontend/src/views/sql-editor/TabList/TabItem/AdminLabel.vue
index 267212c52d..03540ea608 100644
--- a/frontend/src/views/sql-editor/TabList/TabItem/AdminLabel.vue
+++ b/frontend/src/views/sql-editor/TabList/TabItem/AdminLabel.vue
@@ -9,9 +9,9 @@
<heroicons-solid:chevron-right class="flex-shrink-0 h-4 w-4 opacity-70" />
<span>{{ instance.title }}</span>
</template>
- <template v-if="databaseV1.uid !== String(UNKNOWN_ID)">
+ <template v-if="database.uid !== String(UNKNOWN_ID)">
<heroicons-solid:chevron-right class="flex-shrink-0 h-4 w-4 opacity-70" />
- <span>{{ databaseV1.databaseName }}</span>
+ <span>{{ database.databaseName }}</span>
</template>
</label>
</template>
@@ -19,13 +19,13 @@
<script lang="ts" setup>
import { computed, PropType } from "vue";
import { EnvironmentV1Name } from "@/components/v2";
-import { useDatabaseV1ByUID, useInstanceV1ByUID } from "@/store";
-import type { TabInfo } from "@/types";
+import { useDatabaseV1Store, useInstanceV1Store } from "@/store";
+import type { SQLEditorTab } from "@/types";
import { UNKNOWN_ID } from "@/types";
const props = defineProps({
tab: {
- type: Object as PropType<TabInfo>,
+ type: Object as PropType<SQLEditorTab>,
required: true,
},
index: {
@@ -36,11 +36,10 @@ const props = defineProps({
const connection = computed(() => props.tab.connection);
-const { instance } = useInstanceV1ByUID(
- computed(() => connection.value.instanceId)
-);
-
-const { database: databaseV1 } = useDatabaseV1ByUID(
- computed(() => String(connection.value.databaseId))
-);
+const instance = computed(() => {
+ return useInstanceV1Store().getInstanceByName(connection.value.instance);
+});
+const database = computed(() => {
+ return useDatabaseV1Store().getDatabaseByName(connection.value.database);
+});
</script>
diff --git a/frontend/src/views/sql-editor/TabList/TabItem/Label.vue b/frontend/src/views/sql-editor/TabList/TabItem/Label.vue
index 18247366af..dbdb61f70d 100644
--- a/frontend/src/views/sql-editor/TabList/TabItem/Label.vue
+++ b/frontend/src/views/sql-editor/TabList/TabItem/Label.vue
@@ -9,13 +9,13 @@
:class="state.editing && 'invisible'"
@dblclick="beginEdit"
>
- {{ state.name }}
+ {{ state.title }}
</NEllipsis>
<input
v-if="state.editing"
ref="inputRef"
- v-model="state.name"
+ v-model="state.title"
type="text"
class="edit"
@blur="confirmEdit"
@@ -28,18 +28,18 @@
import { NEllipsis } from "naive-ui";
import { computed, nextTick, PropType, reactive, ref, watch } from "vue";
import { useEmitteryEventListener } from "@/composables/useEmitteryEventListener";
-import { useWorkSheetStore, useTabStore } from "@/store";
-import type { TabInfo } from "@/types";
+import { useSQLEditorTabStore, useWorkSheetStore } from "@/store";
+import type { SQLEditorTab } from "@/types";
import { useTabListContext } from "../context";
type LocalState = {
editing: boolean;
- name: string;
+ title: string;
};
const props = defineProps({
tab: {
- type: Object as PropType<TabInfo>,
+ type: Object as PropType<SQLEditorTab>,
required: true,
},
index: {
@@ -50,10 +50,10 @@ const props = defineProps({
const state = reactive<LocalState>({
editing: false,
- name: props.tab.name,
+ title: props.tab.title,
});
-const tabStore = useTabStore();
+const tabStore = useSQLEditorTabStore();
const worksheetV1Store = useWorkSheetStore();
const inputRef = ref<HTMLInputElement>();
const { events } = useTabListContext();
@@ -69,7 +69,7 @@ useEmitteryEventListener(events, "rename-tab", ({ tab }) => {
const beginEdit = () => {
state.editing = true;
- state.name = props.tab.name;
+ state.title = props.tab.title;
nextTick(() => {
inputRef.value?.focus();
});
@@ -78,20 +78,25 @@ const beginEdit = () => {
const confirmEdit = () => {
const { tab } = props;
- const name = state.name.trim();
- if (name === "") {
+ const title = state.title.trim();
+ if (title === "") {
return cancelEdit();
}
- tab.name = name;
- if (tab.sheetName) {
- worksheetV1Store.patchSheet(
- {
- name: tab.sheetName,
- title: name,
- },
- ["title"]
- );
+ tab.title = title;
+ tab.status = "DIRTY";
+ if (tab.sheet) {
+ worksheetV1Store
+ .patchSheet(
+ {
+ name: tab.sheet,
+ title,
+ },
+ ["title"]
+ )
+ .then(() => {
+ tab.status = "CLEAN";
+ });
}
state.editing = false;
@@ -99,13 +104,13 @@ const confirmEdit = () => {
const cancelEdit = () => {
state.editing = false;
- state.name = props.tab.name;
+ state.title = props.tab.title;
};
watch(
- () => props.tab.name,
- (name) => {
- state.name = name;
+ () => props.tab.title,
+ (title) => {
+ state.title = title;
}
);
watch(isCurrentTab, (value) => {
diff --git a/frontend/src/views/sql-editor/TabList/TabItem/Prefix.vue b/frontend/src/views/sql-editor/TabList/TabItem/Prefix.vue
index 1f31f6ed97..a99d705ca3 100644
--- a/frontend/src/views/sql-editor/TabList/TabItem/Prefix.vue
+++ b/frontend/src/views/sql-editor/TabList/TabItem/Prefix.vue
@@ -11,7 +11,7 @@
class="w-4 h-4"
/>
</template>
- <template v-if="tab.mode === TabMode.Admin">
+ <template v-if="tab.mode === 'ADMIN'">
<heroicons-outline:wrench class="w-4 h-4" />
</template>
</template>
@@ -19,14 +19,13 @@
<script lang="ts" setup>
import { computed, PropType } from "vue";
import { useWorkSheetStore } from "@/store";
-import type { TabInfo } from "@/types";
-import { TabMode } from "@/types";
+import type { SQLEditorTab } from "@/types";
import { Worksheet_Visibility } from "@/types/proto/v1/worksheet_service";
import { SheetConnectionIcon } from "../../EditorCommon";
const props = defineProps({
tab: {
- type: Object as PropType<TabInfo>,
+ type: Object as PropType<SQLEditorTab>,
required: true,
},
index: {
@@ -38,7 +37,7 @@ const props = defineProps({
const sheetV1Store = useWorkSheetStore();
const sheet = computed(() => {
- const { sheetName } = props.tab;
+ const { sheet: sheetName } = props.tab;
if (sheetName) {
const sheet = sheetV1Store.getSheetByName(sheetName);
if (sheet) {
diff --git a/frontend/src/views/sql-editor/TabList/TabItem/Suffix.vue b/frontend/src/views/sql-editor/TabList/TabItem/Suffix.vue
index b7e3d87a81..7f31e25997 100644
--- a/frontend/src/views/sql-editor/TabList/TabItem/Suffix.vue
+++ b/frontend/src/views/sql-editor/TabList/TabItem/Suffix.vue
@@ -3,11 +3,10 @@
class="suffix"
:class="[
{
- admin: tab.mode === TabMode.Admin,
+ admin: tab.mode === 'ADMIN',
closable: true,
},
-
- [sheetTypeForTab(tab).toLowerCase()],
+ tab.status,
]"
@mouseenter="state.hovering = true"
@mouseleave="state.hovering = false"
@@ -24,9 +23,7 @@
<script lang="ts" setup>
import { computed, PropType, reactive } from "vue";
-import type { TabInfo } from "@/types";
-import { TabMode } from "@/types";
-import { sheetTypeForTab } from "@/utils";
+import type { SQLEditorTab } from "@/types";
type LocalState = {
hovering: boolean;
@@ -36,7 +33,7 @@ type IconType = "unsaved" | "close";
const props = defineProps({
tab: {
- type: Object as PropType<TabInfo>,
+ type: Object as PropType<SQLEditorTab>,
required: true,
},
index: {
@@ -50,14 +47,18 @@ const state = reactive<LocalState>({
});
defineEmits<{
- (e: "close", tab: TabInfo, index: number): void;
+ (e: "close", tab: SQLEditorTab, index: number): void;
}>();
const icon = computed((): IconType | undefined => {
if (state.hovering) {
return "close";
}
- if (props.tab.mode === TabMode.ReadOnly && !props.tab.isSaved) {
+ const { mode, status } = props.tab;
+ if (
+ (mode === "READONLY" || mode === "STANDARD") &&
+ (status === "DIRTY" || status === "NEW")
+ ) {
return "unsaved";
}
return "close";
@@ -71,12 +72,10 @@ const icon = computed((): IconType | undefined => {
.icon {
@apply block w-5 h-5 p-0.5 text-gray-500 rounded;
}
-
.suffix.closable {
cursor: pointer;
}
-
-.suffix.closable.temp .icon {
+.suffix.closable.dirty .icon {
@apply text-accent;
}
.suffix.closable .icon {
diff --git a/frontend/src/views/sql-editor/TabList/TabItem/TabItem.vue b/frontend/src/views/sql-editor/TabList/TabItem/TabItem.vue
index d93d7912d4..9ec924e407 100644
--- a/frontend/src/views/sql-editor/TabList/TabItem/TabItem.vue
+++ b/frontend/src/views/sql-editor/TabList/TabItem/TabItem.vue
@@ -5,21 +5,24 @@
{
current: isCurrentTab,
hovering: state.hovering,
- admin: tab.mode === TabMode.Admin,
+ admin: tab.mode === 'ADMIN',
},
- [sheetTypeForTab(tab).toLowerCase()],
+ tab.status,
]"
- :data-is-fresh-new="tab.isFreshNew"
- :data-is-saved="tab.isSaved"
- :data-is-disconnected="isDisconnectedTab(tab)"
- :data-sheet-type="sheetTypeForTab(tab)"
+ :data-status="tab.status"
+ :data-sheet="tab.sheet"
+ :data-connection="JSON.stringify(tab.connection)"
@mousedown.left="$emit('select', tab, index)"
@mouseenter="state.hovering = true"
@mouseleave="state.hovering = false"
>
<div class="body">
<Prefix :tab="tab" :index="index" />
- <Label v-if="tab.mode === TabMode.ReadOnly" :tab="tab" :index="index" />
+ <Label
+ v-if="tab.mode === 'READONLY' || tab.mode === 'STANDARD'"
+ :tab="tab"
+ :index="index"
+ />
<AdminLabel v-else :tab="tab" :index="index" />
<Suffix :tab="tab" :index="index" @close="$emit('close', tab, index)" />
</div>
@@ -27,12 +30,9 @@
</template>
<script lang="ts" setup>
-import { storeToRefs } from "pinia";
import { computed, PropType, reactive } from "vue";
-import { useTabStore } from "@/store";
-import type { TabInfo } from "@/types";
-import { TabMode } from "@/types";
-import { isDisconnectedTab, sheetTypeForTab } from "@/utils";
+import { useSQLEditorTabStore } from "@/store";
+import type { SQLEditorTab } from "@/types";
import AdminLabel from "./AdminLabel.vue";
import Label from "./Label.vue";
import Prefix from "./Prefix.vue";
@@ -44,7 +44,7 @@ type LocalState = {
const props = defineProps({
tab: {
- type: Object as PropType<TabInfo>,
+ type: Object as PropType<SQLEditorTab>,
required: true,
},
index: {
@@ -54,18 +54,17 @@ const props = defineProps({
});
defineEmits<{
- (e: "select", tab: TabInfo, index: number): void;
- (e: "close", tab: TabInfo, index: number): void;
+ (e: "select", tab: SQLEditorTab, index: number): void;
+ (e: "close", tab: SQLEditorTab, index: number): void;
}>();
const state = reactive<LocalState>({
hovering: false,
});
-const tabStore = useTabStore();
-const { currentTabId } = storeToRefs(tabStore);
+const tabStore = useSQLEditorTabStore();
-const isCurrentTab = computed(() => props.tab.id === currentTabId.value);
+const isCurrentTab = computed(() => props.tab.id === tabStore.currentTabId);
</script>
<style scoped lang="postcss">
diff --git a/frontend/src/views/sql-editor/TabList/TabList.vue b/frontend/src/views/sql-editor/TabList/TabList.vue
index c61f842a78..acef3851de 100644
--- a/frontend/src/views/sql-editor/TabList/TabList.vue
+++ b/frontend/src/views/sql-editor/TabList/TabList.vue
@@ -2,7 +2,7 @@
<div
class="flex justify-between items-center box-border text-gray-500 text-sm border-b pr-2 pt-1"
>
- <div class="relative flex flex-1 flex-nowrap overflow-hidden">
+ <div class="relative flex flex-1 flex-nowrap overflow-hidden h-[29px]">
<Draggable
id="tab-list"
ref="tabListRef"
@@ -23,13 +23,13 @@
#item="{ element: id, index }: { element: string, index: number }"
>
<TabItem
- :tab="tabStore.getTabById(id)"
+ :tab="tabStore.tabById(id)!"
:index="index"
:data-tab-id="id"
@select="(tab) => handleSelectTab(tab)"
@close="(tab, index) => handleRemoveTab(tab, index)"
@contextmenu.stop.prevent="
- contextMenuRef?.show(tabStore.getTabById(id), index, $event)
+ contextMenuRef?.show(tabStore.tabById(id)!, index, $event)
"
/>
</template>
@@ -61,17 +61,15 @@ import Draggable from "vuedraggable";
import ProfileDropdown from "@/components/ProfileDropdown.vue";
import { useEmitteryEventListener } from "@/composables/useEmitteryEventListener";
import {
- useTabStore,
useActuatorV1Store,
useFilterStore,
- useDatabaseV1Store,
+ useSQLEditorTabStore,
} from "@/store";
-import type { TabInfo } from "@/types";
-import { TabMode, UNKNOWN_ID } from "@/types";
+import type { SQLEditorTab } from "@/types";
import {
defer,
- getSuggestedTabNameFromConnection,
- sheetTypeForTab,
+ emptySQLEditorConnection,
+ suggestedTabTitleForSQLEditorConnection,
} from "@/utils";
import { useSheetContext } from "../Sheet";
import ContextMenu from "./ContextMenu.vue";
@@ -83,11 +81,10 @@ type LocalState = {
hoverTabId: string;
};
-const tabStore = useTabStore();
+const tabStore = useSQLEditorTabStore();
const { t } = useI18n();
const { filter } = useFilterStore();
-const databaseStore = useDatabaseV1Store();
const dialog = useDialog();
const state = reactive<LocalState>({
@@ -112,12 +109,11 @@ const showProfileDropdown = computed(() => {
const filteredTabIdList = computed(() => {
// If a database is selected, only show tabs that are associated with the database.
if (filter.database) {
- const database = databaseStore.getDatabaseByName(filter.database);
return tabStore.tabIdList.filter((id) => {
- const tab = tabStore.getTabById(id);
+ const tab = tabStore.tabById(id);
if (
- tab.connection.databaseId === String(UNKNOWN_ID) ||
- tab.connection.databaseId === database.uid
+ !tab?.connection.database ||
+ tab.connection.database === filter.database
) {
return true;
} else {
@@ -129,30 +125,36 @@ const filteredTabIdList = computed(() => {
return tabStore.tabIdList;
});
-const handleSelectTab = async (tab: TabInfo | undefined) => {
+const handleSelectTab = async (tab: SQLEditorTab | undefined) => {
tabStore.setCurrentTabId(tab?.id ?? "");
};
const handleAddTab = () => {
- const connection = { ...tabStore.currentTab.connection };
- const name = getSuggestedTabNameFromConnection(connection);
+ const currentTab = tabStore.currentTab;
+ const connection = currentTab?.connection
+ ? { ...currentTab.connection }
+ : emptySQLEditorConnection();
+ const title = suggestedTabTitleForSQLEditorConnection(connection);
tabStore.addTab({
- name,
+ title,
connection,
- // The newly created tab is "clean" so its connection can be changed
- isFreshNew: true,
+ // The newly created tab is "clean"
+ status: "CLEAN",
});
nextTick(recalculateScrollState);
sheetEvents.emit("add-sheet");
};
const handleRemoveTab = async (
- tab: TabInfo,
+ tab: SQLEditorTab,
index: number,
focusWhenConfirm = false
) => {
const _defer = defer<boolean>();
- if (tab.mode === TabMode.ReadOnly && !tab.isSaved) {
+ if (
+ (tab.mode === "READONLY" || tab.mode === "STANDARD") &&
+ tab.status === "DIRTY"
+ ) {
if (focusWhenConfirm) {
tabStore.setCurrentTabId(tab.id);
}
@@ -261,9 +263,9 @@ useEmitteryEventListener(
context.events,
"close-tab",
async ({ tab, index, action }) => {
- const tabList = tabStore.tabList;
+ const { tabList } = tabStore;
- const remove = async (tab: TabInfo, index: number) => {
+ const remove = async (tab: SQLEditorTab, index: number) => {
await handleRemoveTab(tab, index, true);
await new Promise((r) => requestAnimationFrame(r));
};
@@ -291,7 +293,7 @@ useEmitteryEventListener(
if (action === "CLOSE_SAVED") {
for (let i = max; i >= 0; i--) {
const tab = tabList[i];
- if (sheetTypeForTab(tab) === "CLEAN") {
+ if (tab.status === "CLEAN") {
await remove(tab, i);
}
}
diff --git a/frontend/src/views/sql-editor/TabList/context.ts b/frontend/src/views/sql-editor/TabList/context.ts
index a43108ab51..dc5c8900d9 100644
--- a/frontend/src/views/sql-editor/TabList/context.ts
+++ b/frontend/src/views/sql-editor/TabList/context.ts
@@ -1,6 +1,6 @@
import Emittery from "emittery";
import { InjectionKey, Ref, inject, provide, ref } from "vue";
-import { TabInfo } from "@/types";
+import { SQLEditorTab } from "@/types";
export type CloseTabAction =
| "CLOSE"
@@ -10,14 +10,14 @@ export type CloseTabAction =
| "CLOSE_ALL";
type TabListEvents = Emittery<{
- "close-tab": { tab: TabInfo; index: number; action: CloseTabAction };
- "rename-tab": { tab: TabInfo; index: number };
+ "close-tab": { tab: SQLEditorTab; index: number; action: CloseTabAction };
+ "rename-tab": { tab: SQLEditorTab; index: number };
}>;
export type TabListContextMenuState = {
x: number;
y: number;
- tab: TabInfo;
+ tab: SQLEditorTab;
index: number;
};
diff --git a/frontend/src/views/sql-editor/TerminalPanel/CompactSQLEditor.vue b/frontend/src/views/sql-editor/TerminalPanel/CompactSQLEditor.vue
index 3d5b17fca7..ffe737c237 100644
--- a/frontend/src/views/sql-editor/TerminalPanel/CompactSQLEditor.vue
+++ b/frontend/src/views/sql-editor/TerminalPanel/CompactSQLEditor.vue
@@ -34,14 +34,14 @@ import {
useEditorContextKey,
formatEditorContent,
} from "@/components/MonacoEditor/utils";
-import { useTabStore, useSQLEditorStore, useInstanceV1ByUID } from "@/store";
+import { useEmitteryEventListener } from "@/composables/useEmitteryEventListener";
import {
- dialectOfEngineV1,
- ExecuteConfig,
- ExecuteOption,
- SQLDialect,
-} from "@/types";
-import { formatEngineV1, useInstanceV1EditorLanguage } from "@/utils";
+ useSQLEditorTabStore,
+ useConnectionOfCurrentSQLEditorTab,
+} from "@/store";
+import { dialectOfEngineV1, SQLDialect, SQLEditorQueryParams } from "@/types";
+import { useInstanceV1EditorLanguage } from "@/utils";
+import { useSQLEditorContext } from "../context";
import {
checkCursorAtFirstLine,
checkCursorAtLast,
@@ -62,12 +62,7 @@ const props = defineProps({
const emit = defineEmits<{
(e: "update:sql", sql: string): void;
- (
- e: "execute",
- sql: string,
- config: ExecuteConfig,
- option?: ExecuteOption
- ): void;
+ (e: "execute", params: SQLEditorQueryParams): void;
(e: "history", direction: "up" | "down", editor: IStandaloneCodeEditor): void;
(e: "clear-screen"): void;
}>();
@@ -75,16 +70,12 @@ const emit = defineEmits<{
const MIN_EDITOR_HEIGHT = 40; // ~= 1 line
const MAX_EDITOR_HEIGHT = 360; // ~= 2 lines
-const tabStore = useTabStore();
-const sqlEditorStore = useSQLEditorStore();
+const tabStore = useSQLEditorTabStore();
-const { instance } = useInstanceV1ByUID(
- computed(() => tabStore.currentTab.connection.instanceId)
-);
-const instanceEngine = computed(() => {
- return formatEngineV1(instance.value);
-});
+const { events: editorEvents } = useSQLEditorContext();
+const { connection, instance } = useConnectionOfCurrentSQLEditorTab();
const language = useInstanceV1EditorLanguage(instance);
+const pendingFormatContentCommand = ref(false);
const dialect = computed((): SQLDialect => {
const engine = instance.value.engine;
return dialectOfEngineV1(engine);
@@ -127,7 +118,7 @@ const handleChange = (value: string) => {
}
tabStore.updateCurrentTab({
statement: value,
- isSaved: false,
+ status: "DIRTY",
});
emit("update:sql", value);
@@ -140,12 +131,12 @@ const handleChangeSelection = (value: string) => {
};
const execute = (explain = false) => {
- emit(
- "execute",
- props.sql,
- { databaseType: instanceEngine.value },
- { explain }
- );
+ emit("execute", {
+ connection: { ...connection.value },
+ statement: props.sql,
+ engine: instance.value.engine,
+ explain,
+ });
};
const handleEditorReady = (
@@ -264,19 +255,23 @@ const handleEditorReady = (
);
watch(
- () => sqlEditorStore.shouldFormatContent,
- async (shouldFormat) => {
- if (shouldFormat) {
- await formatEditorContent(editor, dialect.value);
- sqlEditorStore.setShouldFormatContent(false);
+ pendingFormatContentCommand,
+ (pending) => {
+ if (pending) {
+ formatEditorContent(editor, dialect.value);
+ nextTick(() => {
+ pendingFormatContentCommand.value = false;
+ });
}
},
- {
- immediate: true,
- }
+ { immediate: true }
);
};
+useEmitteryEventListener(editorEvents, "format-content", () => {
+ pendingFormatContentCommand.value = true;
+});
+
const EDITOR_OPTIONS = computed<Editor.IStandaloneEditorConstructionOptions>(
() => ({
theme: "bb-dark",
diff --git a/frontend/src/views/sql-editor/TerminalPanel/TerminalPanelV1.vue b/frontend/src/views/sql-editor/TerminalPanel/TerminalPanelV1.vue
index 4e029e442f..cf6d48fc7e 100644
--- a/frontend/src/views/sql-editor/TerminalPanel/TerminalPanelV1.vue
+++ b/frontend/src/views/sql-editor/TerminalPanel/TerminalPanelV1.vue
@@ -80,8 +80,8 @@ import { useElementSize } from "@vueuse/core";
import { computed, defineAsyncComponent, ref, unref, watch } from "vue";
import { BBSpin } from "@/bbkit";
import { IStandaloneCodeEditor } from "@/components/MonacoEditor";
-import { useTabStore, useWebTerminalV1Store } from "@/store";
-import { ExecuteConfig, ExecuteOption, WebTerminalQueryItemV1 } from "@/types";
+import { useSQLEditorTabStore, useWebTerminalStore } from "@/store";
+import { SQLEditorQueryParams, WebTerminalQueryItemV1 } from "@/types";
import {
EditorAction,
ConnectionPathBar,
@@ -95,11 +95,11 @@ const CompactSQLEditor = defineAsyncComponent(
() => import("./CompactSQLEditor.vue")
);
-const tabStore = useTabStore();
-const webTerminalStore = useWebTerminalV1Store();
+const tabStore = useSQLEditorTabStore();
+const webTerminalStore = useWebTerminalStore();
const queryState = computed(() => {
- return webTerminalStore.getQueryStateByTab(tabStore.currentTab);
+ return webTerminalStore.getQueryStateByTab(tabStore.currentTab!);
});
const queryList = computed(() => {
@@ -126,21 +126,17 @@ const isEditableQueryItem = (item: WebTerminalQueryItemV1): boolean => {
return item === currentQuery.value && item.status === "IDLE";
};
-const handleExecute = async (
- query: string,
- config: ExecuteConfig,
- option?: ExecuteOption
-) => {
+const handleExecute = async (params: SQLEditorQueryParams) => {
if (currentQuery.value.status !== "IDLE") {
return;
}
// Prevent executing empty query;
- if (!query) {
+ if (!params.statement) {
return;
}
- queryState.value.controller.events.emit("query", { query, config, option });
+ queryState.value.controller.events.emit("query", params);
};
const handleClearScreen = () => {
diff --git a/frontend/src/views/sql-editor/TerminalPanel/useHistory.ts b/frontend/src/views/sql-editor/TerminalPanel/useHistory.ts
index 10fd777fb8..7399d7e703 100644
--- a/frontend/src/views/sql-editor/TerminalPanel/useHistory.ts
+++ b/frontend/src/views/sql-editor/TerminalPanel/useHistory.ts
@@ -1,6 +1,6 @@
import { computed, unref, watch } from "vue";
-import { useTabStore, useWebTerminalV1Store } from "@/store";
-import { TabMode, WebTerminalQueryItemV1 } from "@/types";
+import { useSQLEditorTabStore, useWebTerminalStore } from "@/store";
+import { WebTerminalQueryItemV1 } from "@/types";
import { minmax } from "@/utils";
const MAX_HISTORY_ITEM_COUNT = 1000;
@@ -11,11 +11,11 @@ type HistoryState = {
};
export const useHistory = () => {
- const tabStore = useTabStore();
- const webTerminalStore = useWebTerminalV1Store();
+ const tabStore = useSQLEditorTabStore();
+ const webTerminalStore = useWebTerminalStore();
const historyByTabId = new Map<string, HistoryState>();
const queryState = computed(() => {
- return webTerminalStore.getQueryStateByTab(tabStore.currentTab);
+ return webTerminalStore.getQueryStateByTab(tabStore.currentTab!);
});
const currentQuery = computed(() => {
@@ -24,8 +24,8 @@ export const useHistory = () => {
});
const currentStack = () => {
- const tab = tabStore.currentTab;
- if (tab.mode === TabMode.ReadOnly) return undefined;
+ const tab = tabStore.currentTab!;
+ if (tab.mode !== "ADMIN") return undefined;
const existed = historyByTabId.get(tab.id);
if (existed) {
diff --git a/frontend/src/views/sql-editor/context.ts b/frontend/src/views/sql-editor/context.ts
index 6bd4d62017..34a9172305 100644
--- a/frontend/src/views/sql-editor/context.ts
+++ b/frontend/src/views/sql-editor/context.ts
@@ -1,6 +1,7 @@
import Emittery from "emittery";
import { InjectionKey, inject, provide, Ref, ref } from "vue";
-import { ComposedDatabase, TabInfo } from "@/types";
+import { useSQLEditorStore } from "@/store";
+import { ComposedDatabase, SQLEditorTab } from "@/types";
import {
DatabaseMetadata,
ExternalTableMetadata,
@@ -9,12 +10,17 @@ import {
} from "@/types/proto/v1/database_service";
type SQLEditorEvents = Emittery<{
- "save-sheet": { tab: TabInfo; editTitle?: boolean };
+ "save-sheet": { tab: SQLEditorTab; editTitle?: boolean };
"alter-schema": {
databaseUID: string;
schema: string;
table: string;
};
+ "format-content": undefined;
+ "tree-ready": undefined;
+ "project-context-ready": {
+ project: string;
+ };
}>;
export type SelectedDatabaseSchema = {
@@ -32,6 +38,8 @@ export type SQLEditorContext = {
>;
events: SQLEditorEvents;
+
+ maybeSwitchProject: (project: string) => Promise<string>;
};
export const KEY = Symbol(
@@ -43,10 +51,19 @@ export const useSQLEditorContext = () => {
};
export const provideSQLEditorContext = () => {
+ const editorStore = useSQLEditorStore();
const context: SQLEditorContext = {
showAIChatBox: ref(false),
selectedDatabaseSchemaByDatabaseName: ref(new Map()),
events: new Emittery(),
+
+ maybeSwitchProject: (project) => {
+ if (editorStore.project !== project) {
+ editorStore.project = project;
+ return context.events.once("project-context-ready").then(() => project);
+ }
+ return Promise.resolve(editorStore.project);
+ },
};
provide(KEY, context);