Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(sql-editor): support multiple query results for admin mode (#5025)
Liu Jie96887066a89
diff --git a/frontend/naive-ui.config.ts b/frontend/naive-ui.config.tsindex d6430e35a3..accab2a0b9 100644--- a/frontend/naive-ui.config.ts+++ b/frontend/naive-ui.config.ts@@ -64,6 +64,9 @@ export const darkThemeOverrides = computed((): GlobalThemeOverrides => {borderHoverInfo: callVar("--color-matrix-green-hover"),borderFocusInfo: callVar("--color-matrix-green"),},+ Tabs: {+ tabTextColorCard: callVar("--color-control-placeholder"),+ },};});diff --git a/frontend/src/store/modules/sql.ts b/frontend/src/store/modules/sql.tsindex 514e4265bb..cd21ce41af 100644--- a/frontend/src/store/modules/sql.ts+++ b/frontend/src/store/modules/sql.ts@@ -14,7 +14,6 @@ import {} from "@/types";import { useDatabaseStore } from "./database";import { useInstanceStore } from "./instance";-import { last } from "lodash-es";export function convertSingleSQLResult(attributes: Attributes@@ -42,16 +41,9 @@ export function convert(resultSet: ResourceObject): SQLResultSet {});}- // Our UI doesn't support multiple results by now.- // So we use the last result as the final result.- const lastResult = last(resultList) ?? {- data: null as any,- error: "",- };-return {- ...lastResult,- error: lastResult?.error || (resultSet.attributes.error as string) || "",+ error: (resultSet.attributes.error as string) || "",+ resultList,adviceList: resultSet.attributes.adviceList as Advice[],};}diff --git a/frontend/src/types/sql.ts b/frontend/src/types/sql.tsindex 5a478e44b7..8d2a779935 100644--- a/frontend/src/types/sql.ts+++ b/frontend/src/types/sql.ts@@ -42,7 +42,6 @@ export type SingleSQLResult = {export type SQLResultSet = {error: string;- // resultList: SingleSQLResult[];- data: SingleSQLResult["data"];+ resultList: SingleSQLResult[];adviceList: Advice[];};diff --git a/frontend/src/types/tab.ts b/frontend/src/types/tab.tsindex 3ee802e485..8a592ad807 100644--- a/frontend/src/types/tab.ts+++ b/frontend/src/types/tab.ts@@ -3,7 +3,7 @@ import {DatabaseId,InstanceId,SheetId,- SingleSQLResult,+ SQLResultSet,} from "../types";export type ExecuteConfig = {@@ -39,7 +39,7 @@ export interface TabInfo {option?: Partial<ExecuteOption>;};isExecutingSQL: boolean;- queryResult?: SingleSQLResult;+ queryResult?: SQLResultSet;sheetId?: SheetId;adviceList?: Advice[];}diff --git a/frontend/src/utils/instance.ts b/frontend/src/utils/instance.tsindex 44cd55f3eb..f7087fe95f 100644--- a/frontend/src/utils/instance.ts+++ b/frontend/src/utils/instance.ts@@ -83,6 +83,15 @@ export const instanceHasCreateDatabase = (instance: Instance): boolean => {return true;};+export const instanceHasStructuredQueryResult = (+ instance: Instance+): boolean => {+ const { engine } = instance;+ if (engine === "MONGODB") return false;+ if (engine === "REDIS") return false;+ return true;+};+export const instanceHasSSL = (instanceOrEngine: Instance | EngineType): boolean => {diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/DataTable.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/DataTable.vuenew file mode 100644index 0000000000..6228295fe6--- /dev/null+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/DataTable.vue@@ -0,0 +1,138 @@+<template>+ <div+ class="bb-data-table relative w-full flex-1 overflow-hidden flex flex-col"+ >+ <div class="w-full flex-1 flex flex-col overflow-hidden">+ <div+ class="header-track absolute z-0 left-0 top-0 right-0 h-[34px] border border-block-border bg-gray-50 dark:bg-gray-700"+ />++ <div+ ref="scrollerRef"+ class="inner-wrapper max-h-full w-full overflow-auto border-y border-r border-block-border fix-scrollbar-z-index"+ :class="data.length === 0 && 'border-b-0 border-r-0'"+ >+ <table+ ref="tableRef"+ class="relative border-collapse table-fixed z-[1]"+ v-bind="tableResize.getTableProps()"+ >+ <thead class="sticky top-0 z-[1] shadow">+ <tr>+ <th+ v-for="header of table.getFlatHeaders()"+ :key="header.index"+ class="relative px-2 py-2 min-w-[2rem] text-left bg-gray-50 dark:bg-gray-700 text-xs font-medium text-gray-500 dark:text-gray-300 tracking-wider border border-t-0 border-block-border border-b-0"+ v-bind="tableResize.getColumnProps(header.index)"+ >+ <div class="flex items-center overflow-hidden">+ <span> {{ header.column.columnDef.header }}</span>+ <SensitiveDataIcon+ v-if="isSensitiveColumn(header.index)"+ class="ml-0.5 shrink-0"+ />+ </div>++ <!-- The drag-to-resize handler -->+ <div+ class="absolute w-[8px] right-0 top-0 bottom-0 cursor-col-resize"+ @dblclick="tableResize.autoAdjustColumnWidth([header.index])"+ @pointerdown="tableResize.startResizing(header.index)"+ />+ </th>+ </tr>+ </thead>+ <tbody>+ <tr+ v-for="(row, rowIndex) of table.getRowModel().rows"+ :key="rowIndex"+ class="group"+ >+ <td+ v-for="(cell, cellIndex) of row.getVisibleCells()"+ :key="cellIndex"+ class="px-2 py-1 text-sm dark:text-gray-100 leading-5 whitespace-pre-wrap break-all border border-block-border group-last:border-b-0 group-even:bg-gray-50/50 dark:group-even:bg-gray-700/50"+ >+ <template v-if="cell.getValue()">{{+ cell.getValue()+ }}</template>+ <br v-else class="min-h-[1rem] inline-flex" />+ </td>+ </tr>+ </tbody>+ </table>+ <div+ v-if="data.length === 0"+ class="text-center w-full my-12 textinfolabel"+ >+ {{ $t("sql-editor.no-rows-found") }}+ </div>+ </div>+ </div>+ </div>+</template>++<script lang="ts" setup>+import { computed, nextTick, PropType, ref, watch } from "vue";+import { ColumnDef, Table } from "@tanstack/vue-table";+import useTableColumnWidthLogic from "./useTableResize";+import SensitiveDataIcon from "./SensitiveDataIcon.vue";++export type DataTableColumn = {+ key: string;+ title: string;+};++const props = defineProps({+ data: {+ type: Array as PropType<string[][]>,+ default: () => [],+ },+ columns: {+ type: Array as PropType<ColumnDef<string[]>[]>,+ default: () => [],+ },+ sensitive: {+ type: Array as PropType<boolean[]>,+ default: () => [],+ },+ table: {+ type: Object as PropType<Table<string[]>>,+ required: true,+ },+});++const scrollerRef = ref<HTMLDivElement>();+const tableRef = ref<HTMLTableElement>();++const tableResize = useTableColumnWidthLogic({+ tableRef,+ scrollerRef,+ minWidth: 64, // 4rem+ maxWidth: 640, // 40rem+});++const data = computed(() => props.data);++const isSensitiveColumn = (index: number): boolean => {+ return props.sensitive[index] ?? false;+};++const scrollTo = (x: number, y: number) => {+ scrollerRef.value?.scroll(x, y);+};++watch(+ () => props.columns.map((col) => col.header).join("|"),+ () => {+ nextTick(() => {+ // Re-calculate the column widths once the column definition changed.+ scrollTo(0, 0);+ tableResize.reset();+ });+ },+ { immediate: true }+);++defineExpose({ scrollTo });+</script>diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/SensitiveDataIcon.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/SensitiveDataIcon.vuenew file mode 100644index 0000000000..5b17128082--- /dev/null+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/SensitiveDataIcon.vue@@ -0,0 +1,43 @@+<template>+ <NTooltip :animated="false" :delay="250">+ <template #trigger>+ <heroicons-outline:eye-slash+ class="w-[12px] h-[12px] -mb-[2px]"+ :class="[clickable && 'cursor-pointer']"+ v-bind="$attrs"+ @click="handleClick"+ />+ </template>++ <span class="whitespace-nowrap">+ {{ $t("sensitive-data.self") }}+ </span>+ </NTooltip>+</template>++<script lang="ts" setup>+import { NTooltip } from "naive-ui";+import { computed } from "vue";+import { useRouter } from "vue-router";++import { useCurrentUser } from "@/store";+import { hasWorkspacePermission } from "@/utils";++const user = useCurrentUser();+const router = useRouter();++const clickable = computed(() => {+ return hasWorkspacePermission(+ "bb.permission.workspace.manage-sensitive-data",+ user.value.role+ );+});++const handleClick = () => {+ if (!clickable.value) {+ return;+ }+ const url = router.resolve({ name: "setting.workspace.sensitive-data" });+ window.open(url.href, "_BLANK");+};+</script>diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/index.ts b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/index.tsnew file mode 100644index 0000000000..5e544303ab--- /dev/null+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/index.ts@@ -0,0 +1,3 @@+import DataTable from "./DataTable.vue";++export default DataTable;diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/useTableResize.ts b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/useTableResize.tsnew file mode 100644index 0000000000..87b3913bfc--- /dev/null+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/useTableResize.ts@@ -0,0 +1,232 @@+import { computed, onBeforeUnmount, reactive, Ref, watch } from "vue";+import { useEventListener, usePointer } from "@vueuse/core";+import { sumBy } from "lodash-es";++export type TableResizeOptions = {+ tableRef: Ref<HTMLTableElement | undefined>;+ scrollerRef: Ref<HTMLElement | undefined>;+ minWidth: number;+ maxWidth: number;+};++type ColumnProps = {+ width: number;+};++type DragState = {+ start: number;+ index: number;+ initialWidth: number;+};++type LocalState = {+ columns: ColumnProps[];+ drag?: DragState;+ isAutoAdjusting: boolean;+};++const useTableResize = (options: TableResizeOptions) => {+ const state = reactive<LocalState>({+ columns: [],+ drag: undefined,+ isAutoAdjusting: false,+ });+ const pointer = usePointer();++ const table = computed(() => options.tableRef.value!);++ const normalizeWidth = (width: number) => {+ const { maxWidth, minWidth } = options;+ if (width > maxWidth) return maxWidth;+ if (width < minWidth) return minWidth;+ return width;+ };++ const reset = () => {+ if (!table.value) return;++ state.drag = undefined;+ state.isAutoAdjusting = false;++ const thList = Array.from(table.value.querySelectorAll("th"));+ const columnCount = thList.length;+ state.columns = new Array(columnCount);++ const indexList: number[] = [];+ for (let i = 0; i < columnCount; i++) {+ indexList.push(i);+ state.columns[i] = {+ width: 0, // For auto adjust below+ };+ }++ // Calculate a friendly width for every column when the first render happened.+ requestAnimationFrame(() => {+ autoAdjustColumnWidth(indexList);+ });+ };++ // Automatically estimate the width of a column.+ // Like double-clicking a cell border of Excel.+ // Able to estimate multiple columns in a time.+ const autoAdjustColumnWidth = (indexList: number[]): Promise<number[]> => {+ return new Promise((resolve) => {+ const cellListOfEachColumn = indexList.map((index, i) => {+ const pseudo = `:nth-child(${index + 1})`;+ // Find all cells in this column+ const cellList = Array.from(+ table.value.querySelectorAll(`th${pseudo}, td${pseudo}`)+ ) as HTMLElement[];+ return cellList;+ });++ // Update the cells' and table's style to estimate the width.+ state.isAutoAdjusting = true;+ cellListOfEachColumn.forEach((cellList) => {+ cellList.forEach((cell) => {+ cell.style.whiteSpace = "nowrap";+ cell.style.overflow = "visible";+ cell.style.width = "auto";+ cell.style.maxWidth = `${options.maxWidth}px`;+ cell.style.minWidth = `${options.minWidth}px`;+ });+ });+ const tableWidthBackup = table.value.style.width;+ table.value.style.width = "auto";++ // Wait for the next render frame.+ requestAnimationFrame(() => {+ // Read the rendered widths.++ const widthList = indexList.map((index, i) => {+ const cellList = cellListOfEachColumn[i];+ const th = cellList[0];+ const stretchedWidth = getElementWidth(th);+ const finalWidth = normalizeWidth(stretchedWidth);++ const column = state.columns[index];+ if (column) {+ // Sometimes the `columns` is out-of-sync with the `indexList`+ // so we need to detect and suppress errors here.+ // Only occurs in dev hot reload mode.+ column.width = finalWidth;+ }++ return finalWidth;+ });++ // Reset the cells' and table's style.+ cellListOfEachColumn.forEach((cellList) => {+ cellList.forEach((cell) => {+ cell.style.whiteSpace = "";+ cell.style.overflow = "";+ cell.style.width = "";+ cell.style.maxWidth = "";+ cell.style.minWidth = "";+ });+ });+ table.value.style.width = tableWidthBackup;+ state.isAutoAdjusting = false;++ resolve(widthList);+ // Style bindings will be automatically updated next frame.+ });+ });+ };++ // Record the initial state of dragging.+ const startResizing = (index: number) => {+ state.drag = {+ start: pointer.x.value,+ index,+ initialWidth: state.columns[index].width,+ };+ toggleDragStyle(table, true);+ };++ // Watch the drag moving.+ watch(pointer.x, () => {+ const { drag } = state;+ if (!drag) return;+ const { start, index, initialWidth } = drag;++ // Calculate the expectedWidth according to the pointer's position.+ const offset = pointer.x.value - start;+ const expectedWidth = initialWidth + offset;+ state.columns[index].width = normalizeWidth(expectedWidth);+ if (index === state.columns.length - 1) {+ // When resizing the last column, Keep the horizontal scroll at the end of the container.+ scrollMaxX(options.scrollerRef.value);+ }+ });++ // Reset dragging state when mouse button released.+ useEventListener("pointerup", () => {+ if (state.drag) {+ state.drag = undefined;+ toggleDragStyle(table, false);+ }+ });++ const getColumnProps = (index: number) => {+ const column = state.columns[index];+ if (!column) return {};+ return {+ style: {+ width: state.isAutoAdjusting ? "auto" : `${column.width}px`,+ },+ class: state.isAutoAdjusting ? "" : "truncate",+ "data-index": index,+ };+ };++ const getTableProps = () => {+ const totalWidth = sumBy(state.columns, (col) => col.width);+ return {+ style: {+ width: state.isAutoAdjusting ? "auto" : `${totalWidth}px`,+ },+ };+ };++ onBeforeUnmount(() => {+ toggleDragStyle(table, false);+ });++ return {+ reset,+ getColumnProps,+ getTableProps,+ autoAdjustColumnWidth,+ startResizing,+ };+};++export default useTableResize;++const getElementWidth = (elem: HTMLElement) => {+ if (!elem) return 0;+ const rect = elem.getBoundingClientRect();+ return rect.width;+};++const scrollMaxX = (elem: HTMLElement | undefined) => {+ if (!elem) return;+ const max = elem.scrollWidth;+ elem.scrollTo(max, elem.scrollTop);+};++const toggleDragStyle = (+ table: Ref<HTMLTableElement | undefined>,+ on: boolean+) => {+ if (on) {+ // Prevent text selection while dragging.+ table.value?.classList.add("select-none");+ // Set the cursor style.+ document.body.classList.add("cursor-col-resize");+ } else {+ table.value?.classList.remove("select-none");+ document.body.classList.remove("cursor-col-resize");+ }+};diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/EmptyView.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/EmptyView.vuenew file mode 100644index 0000000000..145dfce7fa--- /dev/null+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/EmptyView.vue@@ -0,0 +1,16 @@+<template>+ <div+ class="text-md font-normal"+ :class="[+ dark ? 'text-[var(--color-matrix-green-hover)]' : 'text-control-light',+ ]"+ >+ {{ $t("sql-editor.no-rows-found") }}+ </div>+</template>++<script lang="ts" setup>+import { useSQLResultViewContext } from "./context";++const { dark } = useSQLResultViewContext();+</script>diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/ErrorView.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/ErrorView.vuenew file mode 100644index 0000000000..5a30bd8f3f--- /dev/null+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/ErrorView.vue@@ -0,0 +1,20 @@+<template>+ <div+ class="text-md font-normal"+ :class="[+ dark ? 'text-[var(--color-matrix-green-hover)]' : 'text-control-light',+ ]"+ >+ {{ error }}+ </div>+</template>++<script lang="ts" setup>+import { useSQLResultViewContext } from "./context";++defineProps<{+ error: string | undefined;+}>();++const { dark } = useSQLResultViewContext();+</script>diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultView.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultView.vuenew file mode 100644index 0000000000..421821e52b--- /dev/null+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultView.vue@@ -0,0 +1,121 @@+<template>+ <NConfigProvider+ v-bind="naiveUIConfig"+ class="relative flex flex-col justify-start items-start p-2"+ :class="dark && 'dark bg-dark-bg'"+ >+ <template v-if="resultSet && !showPlaceholder">+ <template v-if="viewMode === 'SINGLE-RESULT'">+ <SingleResultView :result="resultSet.resultList[0]" />+ </template>+ <template v-else-if="viewMode === 'MULTI-RESULT'">+ <NTabs+ type="card"+ size="small"+ class="flex-1 flex flex-col overflow-hidden"+ >+ <NTabPane+ v-for="(result, i) in resultSet.resultList"+ :key="i"+ :name="tabName(result, i)"+ class="flex-1 flex flex-col overflow-hidden"+ >+ <SingleResultView :result="result" />+ </NTabPane>+ </NTabs>+ </template>+ <template v-else-if="viewMode === 'EMPTY'">+ <EmptyView />+ </template>+ <template v-else-if="viewMode === 'ERROR'">+ <ErrorView :error="resultSet.error" />+ </template>+ </template>++ <div+ v-if="showPlaceholder"+ class="absolute inset-0 flex flex-col justify-center items-center z-10"+ :class="loading && 'bg-white/80 dark:bg-black/80'"+ >+ <template v-if="loading">+ <BBSpin />+ {{ $t("sql-editor.loading-data") }}+ </template>+ <template v-else-if="!resultSet">+ {{ $t("sql-editor.table-empty-placeholder") }}+ </template>+ </div>+ </NConfigProvider>+</template>++<script lang="ts" setup>+import { computed, PropType, toRef } from "vue";+import { useI18n } from "vue-i18n";+import { darkTheme, NConfigProvider, NTabs, NTabPane } from "naive-ui";++import { darkThemeOverrides } from "@/../naive-ui.config";+import SingleResultView from "./SingleResultView.vue";+import EmptyView from "./EmptyView.vue";+import { SingleSQLResult, SQLResultSet } from "@/types";+import { provideSQLResultViewContext } from "./context";+import ErrorView from "./ErrorView.vue";++type ViewMode = "SINGLE-RESULT" | "MULTI-RESULT" | "EMPTY" | "ERROR";++const props = defineProps({+ resultSet: {+ type: Object as PropType<SQLResultSet>,+ default: undefined,+ },+ loading: {+ type: Boolean,+ default: false,+ },+ dark: {+ type: Boolean,+ default: false,+ },+});++const { t } = useI18n();++const viewMode = computed((): ViewMode => {+ const { resultSet } = props;+ if (!resultSet) {+ return "EMPTY";+ }+ const { resultList, error } = resultSet;+ if (error) {+ return "ERROR";+ }+ if (resultList.length === 0) {+ return "EMPTY";+ }+ if (resultList.length === 1) {+ return "SINGLE-RESULT";+ }+ return "MULTI-RESULT";+});++const naiveUIConfig = computed(() => {+ if (props.dark) {+ return { theme: darkTheme, themeOverrides: darkThemeOverrides.value };+ }+ return {};+});++const showPlaceholder = computed(() => {+ if (viewMode.value === "ERROR") return false;+ if (!props.resultSet) return true;+ if (props.loading) return true;+ return false;+});++const tabName = (result: SingleSQLResult, index: number) => {+ return `${t("common.query")} #${index + 1}`;+};++provideSQLResultViewContext({+ dark: toRef(props, "dark"),+});+</script>diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultView.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultView.vuenew file mode 100644index 0000000000..37ed526cab--- /dev/null+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultView.vue@@ -0,0 +1,295 @@+<template>+ <template v-if="viewMode === 'RESULT'">+ <div+ class="w-full shrink-0 flex flex-row justify-between items-center mb-2 overflow-x-auto"+ >+ <div class="flex flex-row justify-start items-center mr-2 shrink-0">+ <NInput+ v-if="showSearchFeature"+ v-model:value="state.search"+ class="!max-w-[8rem] sm:!max-w-xs"+ type="text"+ :placeholder="t('sql-editor.search-results')"+ >+ <template #prefix>+ <heroicons-outline:search class="h-5 w-5 text-gray-300" />+ </template>+ </NInput>+ <span class="ml-2 whitespace-nowrap text-sm text-gray-500">{{+ `${data.length} ${t("sql-editor.rows", data.length)}`+ }}</span>+ <span+ v-if="data.length === RESULT_ROWS_LIMIT"+ class="ml-2 whitespace-nowrap text-sm text-gray-500"+ >+ <span>-</span>+ <span class="ml-2">{{ $t("sql-editor.rows-upper-limit") }}</span>+ </span>+ </div>+ <div class="flex justify-between items-center gap-x-3">+ <NPagination+ v-if="showPagination"+ :item-count="table.getCoreRowModel().rows.length"+ :page="table.getState().pagination.pageIndex + 1"+ :page-size="table.getState().pagination.pageSize"+ :show-quick-jumper="true"+ :show-size-picker="true"+ :page-sizes="[20, 50, 100]"+ @update-page="handleChangePage"+ @update-page-size="(ps) => table.setPageSize(ps)"+ />+ <NButton+ v-if="showVisualizeButton"+ text+ type="primary"+ @click="visualizeExplain"+ >+ {{ $t("sql-editor.visualize-explain") }}+ </NButton>+ <NDropdown+ trigger="hover"+ :options="exportDropdownOptions"+ @select="handleExportBtnClick"+ >+ <NButton>+ <template #icon>+ <heroicons-outline:download class="h-5 w-5" />+ </template>+ {{ t("common.export") }}+ </NButton>+ </NDropdown>+ </div>+ </div>++ <div class="flex-1 w-full flex flex-col overflow-y-auto">+ <DataTable+ ref="dataTable"+ :table="table"+ :columns="columns"+ :data="data"+ :sensitive="sensitive"+ />+ </div>+ </template>+ <template v-else-if="viewMode === 'AFFECTED-ROWS'">+ <div+ class="text-md font-normal flex items-center gap-x-1"+ :class="[+ dark ? 'text-[var(--color-matrix-green-hover)]' : 'text-control-light',+ ]"+ >+ <span>{{ result.data[2][0][0] }}</span>+ <span>rows affected</span>+ </div>+ </template>+ <template v-else-if="viewMode === 'EMPTY'">+ <EmptyView />+ </template>+ <template v-else-if="viewMode === 'ERROR'">+ <ErrorView :error="result.error" />+ </template>+</template>++<script lang="ts" setup>+import { computed, reactive, ref } from "vue";+import { NPagination } from "naive-ui";+import { useI18n } from "vue-i18n";+import { debouncedRef } from "@vueuse/core";+import {+ ColumnDef,+ getCoreRowModel,+ getPaginationRowModel,+ useVueTable,+} from "@tanstack/vue-table";+import { isEmpty } from "lodash-es";+import { unparse } from "papaparse";+import dayjs from "dayjs";++import type { SingleSQLResult } from "@/types";+import { createExplainToken, instanceHasStructuredQueryResult } from "@/utils";+import { useInstanceStore, useTabStore, RESULT_ROWS_LIMIT } from "@/store";+import DataTable from "./DataTable";+import EmptyView from "./EmptyView.vue";+import ErrorView from "./ErrorView.vue";+import { useSQLResultViewContext } from "./context";++type LocalState = {+ search: string;+};+type ViewMode = "RESULT" | "EMPTY" | "AFFECTED-ROWS" | "ERROR";++const PAGE_SIZES = [20, 50, 100];+const DEFAULT_PAGE_SIZE = 50;++const props = defineProps<{+ result: SingleSQLResult;+}>();++const state = reactive<LocalState>({+ search: "",+});++const { dark } = useSQLResultViewContext();++const { t } = useI18n();+const tabStore = useTabStore();+const instanceStore = useInstanceStore();+const dataTable = ref<InstanceType<typeof DataTable>>();++const viewMode = computed((): ViewMode => {+ const { result } = props;+ if (result.error) {+ return "ERROR";+ }+ const columnNames = result.data?.[0];+ if (columnNames?.length === 0) {+ return "EMPTY";+ }+ if (columnNames?.length === 1 && columnNames[0] === "Affected Rows") {+ return "AFFECTED-ROWS";+ }+ return "RESULT";+});++const showSearchFeature = computed(() => {+ const instance = instanceStore.getInstanceById(+ tabStore.currentTab.connection.instanceId+ );+ return instanceHasStructuredQueryResult(instance);+});++// use a debounced value to improve performance when typing rapidly+const keyword = debouncedRef(+ computed(() => state.search),+ 200+);++const columns = computed(() => {+ if (!props.result.data) {+ return [];+ }+ const columns = props.result.data[0];+ return columns.map<ColumnDef<string[]>>((col, index) => ({+ id: `${col}@${index}`,+ accessorFn: (item) => item[index],+ header: col,+ }));+});++const data = computed(() => {+ if (!props.result.data) {+ return [];+ }++ const data = props.result.data[2];+ const search = keyword.value;+ let temp = data;+ if (search) {+ temp = data.filter((item) => {+ return item.some((col) => String(col).includes(search));+ });+ }+ return temp;+});++const sensitive = computed(() => {+ if (!props.result.data) {+ return [];+ }+ return props.result.data[3] ?? [];+});++const table = useVueTable<string[]>({+ get data() {+ return data.value;+ },+ get columns() {+ return columns.value;+ },+ getCoreRowModel: getCoreRowModel(),+ getPaginationRowModel: getPaginationRowModel(),+});++table.setPageSize(DEFAULT_PAGE_SIZE);++const exportDropdownOptions = computed(() => [+ {+ label: t("sql-editor.download-as-csv"),+ key: "csv",+ disabled: props.result === null || isEmpty(props.result),+ },+ {+ label: t("sql-editor.download-as-json"),+ key: "json",+ disabled: props.result === null || isEmpty(props.result),+ },+]);++const handleExportBtnClick = (format: "csv" | "json") => {+ let rawText = "";++ if (format === "csv") {+ const csvFields = columns.value.map((col) => col.header as string);+ const csvData = data.value.map((d) => {+ const temp: any[] = [];+ for (const k in d) {+ temp.push(d[k]);+ }+ return temp;+ });++ rawText = unparse({+ fields: csvFields,+ data: csvData,+ });+ } else {+ rawText = JSON.stringify(data.value);+ }++ const encodedUri = encodeURI(`data:text/${format};charset=utf-8,${rawText}`);+ const formattedDateString = dayjs(new Date()).format("YYYY-MM-DDTHH-mm-ss");+ // Example filename: `mysheet-2022-03-23T09-54-21.json`+ const filename = `${tabStore.currentTab.name}-${formattedDateString}`;+ const link = document.createElement("a");++ link.download = `${filename}.${format}`;+ link.href = encodedUri;+ link.click();+};++const showVisualizeButton = computed((): boolean => {+ const instance = instanceStore.getInstanceById(+ tabStore.currentTab.connection.instanceId+ );+ const databaseType = instance.engine;+ const { executeParams } = tabStore.currentTab;+ return databaseType === "POSTGRES" && !!executeParams?.option?.explain;+});++const visualizeExplain = () => {+ try {+ const { executeParams, queryResult } = tabStore.currentTab;+ if (!executeParams || !queryResult) return;++ const statement = executeParams.query || "";+ if (!statement) return;++ const lines: string[][] = queryResult.data[2];+ const explain = lines.map((line) => line[0]).join("\n");+ if (!explain) return;++ const token = createExplainToken(statement, explain);++ window.open(`/explain-visualizer.html?token=${token}`, "_blank");+ } catch {+ // nothing+ }+};++const showPagination = computed(() => data.value.length > PAGE_SIZES[0]);++const handleChangePage = (page: number) => {+ table.setPageIndex(page - 1);+ dataTable.value?.scrollTo(0, 0);+};+</script>diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/context.ts b/frontend/src/views/sql-editor/EditorCommon/ResultView/context.tsnew file mode 100644index 0000000000..5df9ab00d4--- /dev/null+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/context.ts@@ -0,0 +1,17 @@+import { type Ref, type InjectionKey, provide, inject } from "vue";++export type SQLResultViewContext = {+ dark: Ref<boolean>;+};++export const KEY = Symbol(+ "bb.sql-editor.result-view"+) as InjectionKey<SQLResultViewContext>;++export const provideSQLResultViewContext = (context: SQLResultViewContext) => {+ provide(KEY, context);+};++export const useSQLResultViewContext = () => {+ return inject(KEY)!;+};diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/index.ts b/frontend/src/views/sql-editor/EditorCommon/ResultView/index.tsnew file mode 100644index 0000000000..55dd2e66af--- /dev/null+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/index.ts@@ -0,0 +1,3 @@+import ResultView from "./ResultView.vue";++export default ResultView;diff --git a/frontend/src/views/sql-editor/EditorCommon/TableView.vue b/frontend/src/views/sql-editor/EditorCommon/TableView.vuedeleted file mode 100644index 5146f1a655..0000000000--- a/frontend/src/views/sql-editor/EditorCommon/TableView.vue+++ /dev/null@@ -1,362 +0,0 @@-<template>- <NConfigProvider- v-bind="naiveUIConfig"- class="relative flex flex-col justify-start items-start p-2"- :class="dark && 'dark bg-dark-bg'"- >- <template v-if="viewMode === 'result'">- <div- class="w-full shrink-0 flex flex-row justify-between items-center mb-2 overflow-x-auto"- >- <div class="flex flex-row justify-start items-center mr-2 shrink-0">- <NInput- v-if="showSearchFeature"- v-model:value="state.search"- class="!max-w-[8rem] sm:!max-w-xs"- type="text"- :placeholder="t('sql-editor.search-results')"- >- <template #prefix>- <heroicons-outline:search class="h-5 w-5 text-gray-300" />- </template>- </NInput>- <span class="ml-2 whitespace-nowrap text-sm text-gray-500">{{- `${data.length} ${t("sql-editor.rows", data.length)}`- }}</span>- <span- v-if="data.length === RESULT_ROWS_LIMIT"- class="ml-2 whitespace-nowrap text-sm text-gray-500"- >- <span>-</span>- <span class="ml-2">{{ $t("sql-editor.rows-upper-limit") }}</span>- </span>- </div>- <div class="flex justify-between items-center gap-x-3">- <NPagination- v-if="showPagination"- :item-count="table.getCoreRowModel().rows.length"- :page="table.getState().pagination.pageIndex + 1"- :page-size="table.getState().pagination.pageSize"- :show-quick-jumper="true"- :show-size-picker="true"- :page-sizes="[20, 50, 100]"- @update-page="handleChangePage"- @update-page-size="(ps) => table.setPageSize(ps)"- />- <NButton- v-if="showVisualizeButton"- text- type="primary"- @click="visualizeExplain"- >- {{ $t("sql-editor.visualize-explain") }}- </NButton>- <NDropdown- trigger="hover"- :options="exportDropdownOptions"- @select="handleExportBtnClick"- >- <NButton>- <template #icon>- <heroicons-outline:download class="h-5 w-5" />- </template>- {{ t("common.export") }}- </NButton>- </NDropdown>- </div>- </div>-- <div class="flex-1 w-full flex flex-col overflow-y-auto">- <DataTable- v-show="!showPlaceholder"- ref="dataTable"- :table="table"- :columns="columns"- :data="data"- :sensitive="sensitive"- />- </div>- </template>- <template v-else-if="viewMode === 'affected-rows'">- <div- class="text-md font-normal flex items-center gap-x-1"- :class="[- dark- ? 'text-[var(--color-matrix-green-hover)]'- : 'text-control-light',- ]"- >- <span>{{ queryResult?.data[2][0][0] }}</span>- <span>rows affected</span>- </div>- </template>- <template v-else-if="viewMode === 'empty'">- <div- class="text-md font-normal"- :class="[- dark- ? 'text-[var(--color-matrix-green-hover)]'- : 'text-control-light',- ]"- >- {{ $t("sql-editor.no-rows-found") }}- </div>- </template>- <template v-else-if="viewMode === 'error'">- <div- class="text-md font-normal"- :class="[- dark- ? 'text-[var(--color-matrix-green-hover)]'- : 'text-control-light',- ]"- >- {{ queryResult?.error }}- </div>- </template>-- <div- v-if="showPlaceholder"- class="absolute inset-0 flex flex-col justify-center items-center z-10"- :class="loading && 'bg-white/80 dark:bg-black/80'"- >- <template v-if="loading">- <BBSpin />- {{ $t("sql-editor.loading-data") }}- </template>- <template v-else-if="!queryResult">- {{ $t("sql-editor.table-empty-placeholder") }}- </template>- </div>- </NConfigProvider>-</template>--<script lang="ts" setup>-import { computed, PropType, reactive, ref } from "vue";-import { useI18n } from "vue-i18n";-import { debouncedRef } from "@vueuse/core";-import { unparse } from "papaparse";-import { isEmpty } from "lodash-es";-import dayjs from "dayjs";-import { darkTheme, NConfigProvider, NPagination } from "naive-ui";--import { darkThemeOverrides } from "@/../naive-ui.config";-import { useTabStore, useInstanceStore } from "@/store";-import { createExplainToken } from "@/utils";-import DataTable from "./DataTable.vue";-import { RESULT_ROWS_LIMIT } from "@/store";-import {- ColumnDef,- getCoreRowModel,- getPaginationRowModel,- useVueTable,-} from "@tanstack/vue-table";-import { SingleSQLResult } from "@/types";--type ViewMode = "result" | "empty" | "affected-rows" | "error";--interface State {- search: string;-}--const props = defineProps({- queryResult: {- type: Object as PropType<SingleSQLResult>,- default: undefined,- },- loading: {- type: Boolean,- default: false,- },- dark: {- type: Boolean,- default: false,- },-});--const PAGE_SIZES = [20, 50, 100];-const DEFAULT_PAGE_SIZE = 50;--const { t } = useI18n();-const tabStore = useTabStore();-const instanceStore = useInstanceStore();--const state = reactive<State>({- search: "",-});--const viewMode = computed((): ViewMode => {- const { queryResult } = props;- if (!queryResult) {- return "empty";- }- if (queryResult.error) {- return "error";- }- if (- queryResult.data?.[0].length === 1 &&- queryResult.data[0][0] === "Affected Rows"- ) {- return "affected-rows";- }- return "result";-});--const dataTable = ref<InstanceType<typeof DataTable>>();--const showSearchFeature = computed(() => {- const instance = instanceStore.getInstanceById(- tabStore.currentTab.connection.instanceId- );- return instance.engine !== "MONGODB";-});--const naiveUIConfig = computed(() => {- if (props.dark) {- return { theme: darkTheme, themeOverrides: darkThemeOverrides.value };- }- return {};-});--// use a debounced value to improve performance when typing rapidly-const keyword = debouncedRef(- computed(() => state.search),- 200-);--const columns = computed(() => {- if (!props.queryResult?.data) {- return [];- }- const columns = props.queryResult.data[0];- return columns.map<ColumnDef<string[]>>((col, index) => ({- id: `${col}@${index}`,- accessorFn: (item) => item[index],- header: col,- }));-});--const data = computed(() => {- if (!props.queryResult?.data) {- return [];- }-- const data = props.queryResult.data[2];- const search = keyword.value;- let temp = data;- if (search) {- temp = data.filter((item) => {- return item.some((col) => String(col).includes(search));- });- }- return temp;-});--const sensitive = computed(() => {- if (!props.queryResult?.data) {- return [];- }- return props.queryResult.data[3] ?? [];-});--const table = useVueTable<string[]>({- get data() {- return data.value;- },- get columns() {- return columns.value;- },- getCoreRowModel: getCoreRowModel(),- getPaginationRowModel: getPaginationRowModel(),-});--table.setPageSize(DEFAULT_PAGE_SIZE);--const showPlaceholder = computed(() => {- if (props.queryResult?.error) return false;- if (!props.queryResult?.data) return true;- if (props.loading) return true;- return false;-});--const exportDropdownOptions = computed(() => [- {- label: t("sql-editor.download-as-csv"),- key: "csv",- disabled: props.queryResult === null || isEmpty(props.queryResult),- },- {- label: t("sql-editor.download-as-json"),- key: "json",- disabled: props.queryResult === null || isEmpty(props.queryResult),- },-]);--const handleExportBtnClick = (format: "csv" | "json") => {- let rawText = "";-- if (format === "csv") {- const csvFields = columns.value.map((col) => col.header as string);- const csvData = data.value.map((d) => {- const temp: any[] = [];- for (const k in d) {- temp.push(d[k]);- }- return temp;- });-- rawText = unparse({- fields: csvFields,- data: csvData,- });- } else {- rawText = JSON.stringify(data.value);- }-- const encodedUri = encodeURI(`data:text/${format};charset=utf-8,${rawText}`);- const formattedDateString = dayjs(new Date()).format("YYYY-MM-DDTHH-mm-ss");- // Example filename: `mysheet-2022-03-23T09-54-21.json`- const filename = `${tabStore.currentTab.name}-${formattedDateString}`;- const link = document.createElement("a");-- link.download = `${filename}.${format}`;- link.href = encodedUri;- link.click();-};--const showVisualizeButton = computed((): boolean => {- const instance = instanceStore.getInstanceById(- tabStore.currentTab.connection.instanceId- );- const databaseType = instance.engine;- const { executeParams } = tabStore.currentTab;- return databaseType === "POSTGRES" && !!executeParams?.option?.explain;-});--const visualizeExplain = () => {- try {- const { executeParams, queryResult } = tabStore.currentTab;- if (!executeParams || !queryResult) return;-- const statement = executeParams.query || "";- if (!statement) return;-- const lines: string[][] = queryResult.data[2];- const explain = lines.map((line) => line[0]).join("\n");- if (!explain) return;-- const token = createExplainToken(statement, explain);-- window.open(`/explain-visualizer.html?token=${token}`, "_blank");- } catch {- // nothing- }-};--const showPagination = computed(() => data.value.length > PAGE_SIZES[0]);--const handleChangePage = (page: number) => {- table.setPageIndex(page - 1);- dataTable.value?.scrollTo(0, 0);-};-</script>diff --git a/frontend/src/views/sql-editor/EditorCommon/index.ts b/frontend/src/views/sql-editor/EditorCommon/index.tsindex 6f565beaff..49a23ac3b5 100644--- a/frontend/src/views/sql-editor/EditorCommon/index.ts+++ b/frontend/src/views/sql-editor/EditorCommon/index.ts@@ -4,7 +4,7 @@ import EditorAction from "./EditorAction.vue";import ExecutingHintModal from "./ExecutingHintModal.vue";import SaveSheetModal from "./SaveSheetModal.vue";import SharePopover from "./SharePopover.vue";-import TableView from "./TableView.vue";+import ResultView from "./ResultView";export {ConnectionHolder,@@ -13,5 +13,5 @@ export {ExecutingHintModal,SaveSheetModal,SharePopover,- TableView,+ ResultView,};diff --git a/frontend/src/views/sql-editor/TablePanel/TablePanel.vue b/frontend/src/views/sql-editor/ResultPanel/ResultPanel.vuesimilarity index 79%rename from frontend/src/views/sql-editor/TablePanel/TablePanel.vuerename to frontend/src/views/sql-editor/ResultPanel/ResultPanel.vueindex cda02d0631..87c1768f77 100644--- a/frontend/src/views/sql-editor/TablePanel/TablePanel.vue+++ b/frontend/src/views/sql-editor/ResultPanel/ResultPanel.vue@@ -1,7 +1,7 @@<template>- <TableView+ <ResultViewclass="w-full h-full"- :query-result="queryResult"+ :result-set="queryResult":loading="loading"/></template>@@ -9,7 +9,7 @@<script lang="ts" setup>import { computed } from "vue";-import { TableView } from "../EditorCommon/";+import { ResultView } from "../EditorCommon/";import { useTabStore } from "@/store";const tabStore = useTabStore();diff --git a/frontend/src/views/sql-editor/ResultPanel/index.ts b/frontend/src/views/sql-editor/ResultPanel/index.tsnew file mode 100644index 0000000000..4dbff35866--- /dev/null+++ b/frontend/src/views/sql-editor/ResultPanel/index.ts@@ -0,0 +1,3 @@+import ResultPanel from "./ResultPanel.vue";++export default ResultPanel;diff --git a/frontend/src/views/sql-editor/SQLEditorPage.vue b/frontend/src/views/sql-editor/SQLEditorPage.vueindex f82c7407c5..e572683c80 100644--- a/frontend/src/views/sql-editor/SQLEditorPage.vue+++ b/frontend/src/views/sql-editor/SQLEditorPage.vue@@ -47,7 +47,7 @@<EditorPanel /></Pane><Pane :size="isDisconnected ? 0 : 40">- <TablePanel />+ <ResultPanel /></Pane></Splitpanes>@@ -126,7 +126,7 @@ import AsidePanel from "./AsidePanel/AsidePanel.vue";import EditorPanel from "./EditorPanel/EditorPanel.vue";import TerminalPanel from "./TerminalPanel/TerminalPanel.vue";import TabList from "./TabList";-import TablePanel from "./TablePanel/TablePanel.vue";+import ResultPanel from "./ResultPanel";import {allowUsingSchemaEditor,instanceHasReadonlyMode,diff --git a/frontend/src/views/sql-editor/TerminalPanel/TerminalPanel.vue b/frontend/src/views/sql-editor/TerminalPanel/TerminalPanel.vueindex ff62fe5c7d..502b9a46ae 100644--- a/frontend/src/views/sql-editor/TerminalPanel/TerminalPanel.vue+++ b/frontend/src/views/sql-editor/TerminalPanel/TerminalPanel.vue@@ -28,14 +28,13 @@@history="handleHistory"@clear-screen="handleClearScreen"/>- <div v-if="query.queryResult" class="max-h-[20rem] flex flex-col">- <TableView- class="flex-1 overflow-hidden"- :query-result="query.queryResult"- :loading="query.status === 'RUNNING'"- :dark="true"- />- </div>+ <ResultView+ v-if="query.queryResult"+ class="max-h-[20rem] flex-1 flex flex-col overflow-hidden"+ :result-set="query.queryResult"+ :loading="query.status === 'RUNNING'"+ :dark="true"+ /><divv-else-if="query.status === 'CANCELLED'"class="text-control-light pl-2"@@ -83,7 +82,7 @@ import {EditorAction,ConnectionPathBar,ConnectionHolder,- TableView,+ ResultView,} from "../EditorCommon";import { useExecuteSQL } from "@/composables/useExecuteSQL";import { useCancelableTimeout } from "@/composables/useCancelableTimeout";@@ -152,9 +151,17 @@ const handleExecute = async (// If the queryItem is still the currentQuery// which means it hasn't been cancelled.if (queryItem === currentQuery.value) {- if (sqlResultSet?.data?.[0].length === 0) {- sqlResultSet.data = mockAffectedRows0().data;- }+ // If the result is empty, mock it as "Affected rows: 0"+ const resultList = sqlResultSet?.resultList ?? [];+ resultList.forEach((result) => {+ if (+ !Array.isArray(result.data) ||+ !Array.isArray(result.data[0]) ||+ result.data[0].length === 0+ ) {+ result.data = mockAffectedRows0().data;+ }+ });queryItem.queryResult = sqlResultSet;pushQueryItem();// Clear the tab's statement and keep it sync with the latest query