Skip to content

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

feat(sql-editor): schema chooser (#13675)

Liu Ji3b4e7911addc
diff --git a/frontend/src/components/ProvideSQLEditorContext.vue b/frontend/src/components/ProvideSQLEditorContext.vue
index fbe141a23b..f092641b60 100644
--- a/frontend/src/components/ProvideSQLEditorContext.vue
+++ b/frontend/src/components/ProvideSQLEditorContext.vue
@@ -465,6 +465,9 @@ const syncURLWithConnection = () => {
if (databaseName) {
const database = databaseStore.getDatabaseByName(databaseName);
if (isValidDatabaseName(database.name)) {
+ if (schema) {
+ query.schema = schema;
+ }
if (table) {
query.table = table;
query.schema = schema ?? "";
diff --git a/frontend/src/composables/useExecuteSQL.ts b/frontend/src/composables/useExecuteSQL.ts
index 6af2e64bae..d80e26dcc5 100644
--- a/frontend/src/composables/useExecuteSQL.ts
+++ b/frontend/src/composables/useExecuteSQL.ts
@@ -320,6 +320,7 @@ const useExecuteSQL = () => {
statement: params.statement,
limit: sqlEditorStore.resultRowsLimit,
explain: params.explain,
+ schema: params.connection.schema,
timeout: undefined, // TODO: make this param configurable
},
abortController.signal
@@ -330,6 +331,7 @@ const useExecuteSQL = () => {
name: database.name,
statement: params.statement,
limit: sqlEditorStore.resultRowsLimit,
+ schema: params.connection.schema,
timeout: undefined, // TODO: make this param configurable
},
abortController.signal
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 0bac7bd044..3da8623abd 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -1832,7 +1832,8 @@
"sensitive": "Sensitive",
"access-denied": "You don't have the permission to access this database.",
"schema": {
- "select": "Select schema"
+ "select": "Select schema",
+ "unspecified": "Unspecified"
},
"show-missing-databases": "Show missing databases",
"n-selected-m-in-total": "({selected} selected, {total} in total)",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 2d13fa6080..b2f7978ec2 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -1832,7 +1832,8 @@
"sensitive": "Sensible",
"access-denied": "No tiene permiso para acceder a esta base de datos.",
"schema": {
- "select": "Seleccionar esquema"
+ "select": "Seleccionar esquema",
+ "unspecified": "No especificado"
},
"show-missing-databases": "Mostrar bases de datos faltantes",
"n-selected-m-in-total": "({selected} seleccionados, {total} en total)",
@@ -3697,4 +3698,4 @@
"worksheet": {
"self": "Hoja de trabajo"
}
-}
\ No newline at end of file
+}
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index 1747a07f2d..e5f47e1b28 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -1832,7 +1832,8 @@
"sensitive": "センシティブ",
"access-denied": "データベースにアクセスする権限がありません",
"schema": {
- "select": "スキーマの選択"
+ "select": "スキーマの選択",
+ "unspecified": "不特定"
},
"show-missing-databases": "データベースが見つからないことを表示",
"n-selected-m-in-total": "({selected} 個が選択され、合計 {total} 個)",
@@ -3697,4 +3698,4 @@
"worksheet": {
"self": "ワークシート"
}
-}
\ No newline at end of file
+}
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 68355860a6..b25eb693af 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -1830,9 +1830,10 @@
"generated-ddl-statement": "生成的 DDL 语句"
},
"sensitive": "敏感",
- "access-denied": "您没有访问该数据库的权限",
+ "access-denied": "您无权访问该数据库",
"schema": {
- "select": "选择 schema"
+ "select": "选择 schema",
+ "unspecified": "未指定"
},
"show-missing-databases": "显示未找到的数据库",
"n-selected-m-in-total": "(已选择 {selected},共计 {total})",
@@ -3697,4 +3698,4 @@
"worksheet": {
"self": "工作表"
}
-}
\ No newline at end of file
+}
diff --git a/frontend/src/store/modules/sqlEditor/webTerminal.ts b/frontend/src/store/modules/sqlEditor/webTerminal.ts
index c1a2e13093..375c0129b9 100644
--- a/frontend/src/store/modules/sqlEditor/webTerminal.ts
+++ b/frontend/src/store/modules/sqlEditor/webTerminal.ts
@@ -293,9 +293,10 @@ const mapRequest = (
const { connection, statement, explain } = params;
const database = useDatabaseV1Store().getDatabaseByName(connection.database);
- const request = AdminExecuteRequest.fromJSON({
+ const request = AdminExecuteRequest.fromPartial({
name: database.name,
statement: explain ? `EXPLAIN ${statement}` : statement,
+ schema: connection.schema,
});
return request;
};
diff --git a/frontend/src/utils/v1/instance.ts b/frontend/src/utils/v1/instance.ts
index 717be4cb92..2474cdb6c8 100644
--- a/frontend/src/utils/v1/instance.ts
+++ b/frontend/src/utils/v1/instance.ts
@@ -335,6 +335,13 @@ export const hasSchemaProperty = (databaseEngine: Engine) => {
);
};
+export const instanceAllowsSchemaScopedQuery = (
+ instanceOrEngine: Instance | InstanceResource | Engine
+) => {
+ const engine = engineOfInstanceV1(instanceOrEngine);
+ return engine !== Engine.MSSQL && hasSchemaProperty(engine);
+};
+
export const hasTableEngineProperty = (
instanceOrEngine: Instance | InstanceResource | Engine
) => {
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/SchemaPane.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/SchemaPane.vue
index 033e74b337..5fdc55012c 100644
--- a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/SchemaPane.vue
+++ b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/SchemaPane.vue
@@ -250,7 +250,14 @@ const renderLabel = ({ option }: { option: TreeOption }) => {
const selectedKeys = computed(() => {
const db = database.value;
if (!isValidDatabaseName(db.name)) return [];
- if (!panelViewState.value) return [];
+ const keys: string[] = [];
+ const tab = currentTab.value;
+ if (tab && tab.connection.schema) {
+ keys.push(`${db.name}/schemas/${tab.connection.schema}`);
+ }
+ if (!panelViewState.value || panelViewState.value.view === "CODE") {
+ return keys;
+ }
const {
schema,
detail: {
@@ -293,10 +300,6 @@ const selectedKeys = computed(() => {
} else if (externalTable) {
parts.push(`externalTables/${externalTable}`);
}
- if (parts.length <= 2) {
- // don't highlight if only the root (schema) node is picked
- return [];
- }
return [parts.join("/")];
});
@@ -323,6 +326,15 @@ const expandNode = (node: TreeNode) => {
useEmitteryEventListener(nodeClickEvents, "single-click", ({ node }) => {
expandNode(node);
+ if (node.meta.type === "schema") {
+ const tab = currentTab.value;
+ if (tab) {
+ tab.connection.schema = (
+ node.meta.target as NodeTarget<"schema">
+ ).schema.name;
+ return;
+ }
+ }
viewDetail(node);
});
useEmitteryEventListener(nodeClickEvents, "double-click", ({ node }) => {
diff --git a/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue b/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue
index 9f9ffb13fa..af07439da6 100644
--- a/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue
@@ -121,7 +121,10 @@
class="action-right gap-x-2 flex overflow-x-auto sm:overflow-x-hidden sm:justify-end items-center"
>
<BatchQueryDatabasesSelector />
- <DatabaseChooser />
+ <NButtonGroup>
+ <DatabaseChooser />
+ <SchemaChooser />
+ </NButtonGroup>
</div>
</div>
@@ -164,6 +167,7 @@ import BatchQueryDatabasesSelector from "./BatchQueryDatabasesSelector.vue";
import DatabaseChooser from "./DatabaseChooser.vue";
import OpenAIButton from "./OpenAIButton.vue";
import QueryContextSettingPopover from "./QueryContextSettingPopover.vue";
+import SchemaChooser from "./SchemaChooser.vue";
import SharePopover from "./SharePopover.vue";
interface LocalState {
diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/ErrorView/ErrorView.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/ErrorView/ErrorView.vue
index ed8829ee30..b362fbf627 100644
--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/ErrorView/ErrorView.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/ErrorView/ErrorView.vue
@@ -1,6 +1,6 @@
<template>
<div
- class="text-md font-normal flex flex-col gap-2"
+ class="text-md font-normal flex flex-col gap-2 text-sm"
:class="[dark ? 'text-matrix-green-hover' : 'text-control-light']"
>
<template v-if="resultSet && resultSet.advices.length > 0">
@@ -12,7 +12,7 @@
/>
</template>
<template v-else>
- <div class="flex items-start gap-2">
+ <div class="flex items-center gap-2">
<div class="shrink-0 flex items-center h-6">
<CircleAlertIcon class="w-6 h-6 text-error" />
</div>
diff --git a/frontend/src/views/sql-editor/EditorCommon/SchemaChooser.vue b/frontend/src/views/sql-editor/EditorCommon/SchemaChooser.vue
new file mode 100644
index 0000000000..3286f16bce
--- /dev/null
+++ b/frontend/src/views/sql-editor/EditorCommon/SchemaChooser.vue
@@ -0,0 +1,163 @@
+<template>
+ <NPopselect
+ v-if="show"
+ :value="chosenSchema"
+ :options="options"
+ :show-checkmark="true"
+ :virtual-scroll="true"
+ :style="overridePopoverPaneStyle"
+ placement="bottom-end"
+ trigger="click"
+ class="schema-chooser-pane"
+ @update:show="handleToggleShow"
+ @update:value="handleSelect"
+ >
+ <template #header>
+ <div class="font-medium">
+ {{ $t("database.schema.select") }}
+ </div>
+ </template>
+ <NButton
+ ref="buttonRef"
+ size="small"
+ ghost
+ type="primary"
+ style="
+ display: inline-flex;
+ justify-content: end;
+ overflow-x: hidden;
+ --n-padding: 0 7px 0 5px;
+ --n-icon-margin: 6px 2px 6px 0;
+ --n-color-hover: rgb(var(--color-accent) / 0.05);
+ --n-color-pressed: rgb(var(--color-accent) / 0.05);
+ --n-color-focus: rgb(var(--color-accent) / 0.05);
+ "
+ :style="{
+ maxWidth: chosenSchema ? '12rem' : 'unset',
+ }"
+ >
+ <template #icon>
+ <SchemaIcon
+ class="w-4 h-4"
+ :class="chosenSchema ? 'text-main' : 'text-control-placeholder'"
+ />
+ </template>
+ <span v-if="chosenSchema" class="truncate text-main">
+ {{ chosenSchema }}
+ </span>
+ <span v-else class="text-control-placeholder whitespace-nowrap">
+ {{ $t("database.schema.select") }}
+ </span>
+ </NButton>
+ </NPopselect>
+</template>
+
+<script setup lang="ts">
+import { useElementBounding } from "@vueuse/core";
+import { NButton, NPopselect, type SelectOption } from "naive-ui";
+import { storeToRefs } from "pinia";
+import { computed, nextTick, ref, watch } from "vue";
+import { useI18n } from "vue-i18n";
+import { SchemaIcon } from "@/components/Icon";
+import {
+ useConnectionOfCurrentSQLEditorTab,
+ useDBSchemaV1Store,
+ useSQLEditorTabStore,
+} from "@/store";
+import { DatabaseMetadataView } from "@/types/proto/v1/database_service";
+import { instanceAllowsSchemaScopedQuery } from "@/utils";
+
+const { t } = useI18n();
+const { currentTab: tab } = storeToRefs(useSQLEditorTabStore());
+const { database, instance } = useConnectionOfCurrentSQLEditorTab();
+const show = computed(() => {
+ return instanceAllowsSchemaScopedQuery(instance.value.engine);
+});
+
+const popoverPaneRef = ref<HTMLDivElement>();
+const popoverPaneBounding = useElementBounding(popoverPaneRef);
+const popoverPaneDimensions = ref({
+ minWidth: 0,
+ maxHeight: 0,
+});
+
+const overridePopoverPaneStyle = computed(() => {
+ const style: Record<string, any> = {};
+ const { maxHeight, minWidth } = popoverPaneDimensions.value;
+ if (maxHeight > 0) {
+ style["--n-height"] = `${maxHeight}px`;
+ }
+ if (minWidth > 0) {
+ style["min-width"] = `${minWidth}px`;
+ }
+ style["maxWidth"] = "20rem";
+ return style;
+});
+
+const databaseMetadata = computed(() => {
+ return useDBSchemaV1Store().getDatabaseMetadata(
+ database.value.name,
+ DatabaseMetadataView.DATABASE_METADATA_VIEW_FULL
+ );
+});
+const options = computed(() => {
+ const options = databaseMetadata.value.schemas.map<SelectOption>(
+ (schema) => ({
+ value: schema.name,
+ label: schema.name,
+ })
+ );
+ options.unshift({
+ value: "",
+ label: t("database.schema.unspecified"),
+ });
+ return options;
+});
+
+const chosenSchema = computed<string | undefined>({
+ get() {
+ return tab.value?.connection.schema ?? "";
+ },
+ set(value) {
+ if (!tab.value) return;
+ tab.value.connection.schema = value;
+ },
+});
+
+const handleSelect = async (value: string) => {
+ chosenSchema.value = value === "" ? undefined : value;
+};
+
+const handleToggleShow = async (show: boolean) => {
+ if (!show) return;
+ await nextTick();
+
+ const pane = document.querySelector(".schema-chooser-pane") as HTMLDivElement;
+ popoverPaneRef.value = pane;
+};
+
+// Calculate the max-height of the pane
+// to prevent it to be too long to overflow the bottom of the screen
+watch(popoverPaneBounding.top, (top) => {
+ if (!top) {
+ // Cannot calculate max-height
+ popoverPaneDimensions.value.maxHeight = 0;
+ return;
+ }
+ const safeZone = 20;
+ const MAX_HEIGHT = 320;
+ popoverPaneDimensions.value.maxHeight = Math.min(
+ window.innerHeight - top - safeZone,
+ MAX_HEIGHT
+ );
+});
+
+// Calculate the width of the pane
+// to prevent its height varies when scrolling
+watch(popoverPaneBounding.width, (width) => {
+ if (!width) return;
+ if (width > popoverPaneDimensions.value.minWidth) {
+ popoverPaneDimensions.value.minWidth = width;
+ }
+});
+</script>
diff --git a/frontend/src/views/sql-editor/EditorPanel/StandardPanel/SQLEditor.vue b/frontend/src/views/sql-editor/EditorPanel/StandardPanel/SQLEditor.vue
index a819390e30..47ed3cf4f4 100644
--- a/frontend/src/views/sql-editor/EditorPanel/StandardPanel/SQLEditor.vue
+++ b/frontend/src/views/sql-editor/EditorPanel/StandardPanel/SQLEditor.vue
@@ -13,6 +13,7 @@
:auto-complete-context="{
instance: instance.name,
database: database.name,
+ schema: chosenSchema,
scene: 'query',
}"
@update:content="handleUpdateStatement"
@@ -91,6 +92,12 @@ const filename = computed(() => {
return `${name}.${ext}`;
});
+const chosenSchema = computed(() => {
+ const tab = currentTab.value;
+ if (!tab || tab.connection.schema === "") return undefined;
+ return tab.connection.schema;
+});
+
const handleUpdateStatement = (value: string) => {
// When we are switching between tabs, the MonacoEditor emits a 'change'
// event, but we shouldn't update the current tab;
diff --git a/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/CompactSQLEditor.vue b/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/CompactSQLEditor.vue
index 342b00f836..94f20c2622 100644
--- a/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/CompactSQLEditor.vue
+++ b/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/CompactSQLEditor.vue
@@ -15,6 +15,12 @@
min: MIN_EDITOR_HEIGHT,
max: MAX_EDITOR_HEIGHT,
}"
+ :auto-complete-context="{
+ instance: instance.name,
+ database: database.name,
+ schema: chosenSchema,
+ scene: 'query',
+ }"
@update:content="handleChange"
@ready="handleEditorReady"
/>
@@ -74,15 +80,21 @@ const MAX_EDITOR_HEIGHT = 360; // ~= 2 lines
const tabStore = useSQLEditorTabStore();
const { events: editorEvents } = useSQLEditorContext();
-const { connection, instance } = useConnectionOfCurrentSQLEditorTab();
+const { connection, instance, database } = useConnectionOfCurrentSQLEditorTab();
const language = useInstanceV1EditorLanguage(instance);
-const { isSwitchingTab } = storeToRefs(tabStore);
+const { currentTab, isSwitchingTab } = storeToRefs(tabStore);
const pendingFormatContentCommand = ref(false);
const dialect = computed((): SQLDialect => {
const engine = instance.value.engine;
return dialectOfEngineV1(engine);
});
+const chosenSchema = computed(() => {
+ const tab = currentTab.value;
+ if (!tab || tab.connection.schema === "") return undefined;
+ return tab.connection.schema;
+});
+
const firstLinePrompt = computed(() => {
const lang = language.value;
if (lang === "javascript") return "MONGO>";
diff --git a/frontend/src/views/sql-editor/EditorPanel/context/index.ts b/frontend/src/views/sql-editor/EditorPanel/context/index.ts
index 88b9efb1b4..0c1863ec58 100644
--- a/frontend/src/views/sql-editor/EditorPanel/context/index.ts
+++ b/frontend/src/views/sql-editor/EditorPanel/context/index.ts
@@ -83,6 +83,28 @@ export const provideEditorPanelContext = (base: {
{ immediate: true }
);
+ watch(
+ () => tab.value?.connection.schema,
+ (schema) => {
+ if (!schema) return;
+ if (!viewState.value) return;
+ if (viewState.value.schema === schema) return;
+ viewState.value.schema = schema;
+ },
+ { immediate: true }
+ );
+ watch(
+ () => viewState.value?.schema,
+ (schema) => {
+ if (!schema) return;
+ if (!tab.value) return;
+ if (!tab.value.connection.schema) return; // if schema chooser is "ALL", don't sync
+ if (tab.value.connection.schema === schema) return;
+ tab.value.connection.schema = schema;
+ },
+ { immediate: true }
+ );
+
const context = {
...base,
viewState,