Skip to content

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

chore(sql-editor): update data table lite (#14924)

boojack89c5482cb89c
diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataBlock.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataBlock.vue
index 2b0ae4cbbd..f74d3ddc3e 100644
--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataBlock.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataBlock.vue
@@ -68,7 +68,7 @@ import {
} from "@/components/FeatureGuard";
import { useSubscriptionV1Store } from "@/store";
import type { QueryRow, RowValue } from "@/types/proto/v1/sql_service";
-import TableCell from "./DataTable/DataTable/TableCell.vue";
+import TableCell from "./DataTable/TableCell.vue";
import SensitiveDataIcon from "./DataTable/common/SensitiveDataIcon.vue";
import { useSQLResultViewContext } from "./context";
diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/DataTable/DataTable.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/DataTable.vue
similarity index 95%
rename from frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/DataTable/DataTable.vue
rename to frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/DataTable.vue
index 8932c370fb..fb852ca0bd 100644
--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/DataTable/DataTable.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/DataTable.vue
@@ -83,6 +83,7 @@
class="absolute w-[8px] right-0 top-0 bottom-0 cursor-col-resize"
@dblclick="tableResize.autoAdjustColumnWidth([header.index])"
@pointerdown="tableResize.startResizing(header.index)"
+ @click.stop.prevent
/>
</th>
</tr>
@@ -145,18 +146,13 @@ import {
import { useSubscriptionV1Store } from "@/store";
import type { QueryRow, RowValue } from "@/types/proto/v1/sql_service";
import { usePreventBackAndForward } from "@/utils";
-import { useSQLResultViewContext } from "../../context";
-import ColumnSortedIcon from "../common/ColumnSortedIcon.vue";
-import SensitiveDataIcon from "../common/SensitiveDataIcon.vue";
-import { useSelectionContext } from "../common/selection-logic";
+import { useSQLResultViewContext } from "../context";
import TableCell from "./TableCell.vue";
+import ColumnSortedIcon from "./common/ColumnSortedIcon.vue";
+import SensitiveDataIcon from "./common/SensitiveDataIcon.vue";
+import { useSelectionContext } from "./common/selection-logic";
import useTableColumnWidthLogic from "./useTableResize";
-export type DataTableColumn = {
- key: string;
- title: string;
-};
-
const props = defineProps<{
table: Table<QueryRow>;
setIndex: number;
diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/DataTable/index.ts b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/DataTable/index.ts
deleted file mode 100644
index 5e544303ab..0000000000
--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/DataTable/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import DataTable from "./DataTable.vue";
-
-export default DataTable;
diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/DataTableLite.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/DataTableLite.vue
new file mode 100644
index 0000000000..a0b7eebe1d
--- /dev/null
+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/DataTableLite.vue
@@ -0,0 +1,156 @@
+<template>
+ <div
+ ref="containerRef"
+ class="relative w-full flex-1 overflow-auto flex flex-col"
+ :style="{
+ maxHeight: maxHeight ? `${maxHeight}px` : undefined,
+ }"
+ >
+ <table class="relative border-collapse table-auto">
+ <thead
+ class="sticky top-0 z-[1] drop-shadow-sm bg-gray-50 dark:bg-gray-700"
+ >
+ <tr>
+ <th
+ v-for="header of table.getFlatHeaders()"
+ :key="header.index"
+ class="relative min-w-[2rem] max-w-[50vw] text-left text-xs font-medium text-gray-500 dark:text-gray-300 tracking-wider border-l first:border-l-0 border-block-border dark:border-zinc-500"
+ :class="{
+ 'cursor-pointer': !selectionDisabled,
+ 'bg-accent/10 dark:bg-accent/40': selectionState.columns.includes(
+ header.index
+ ),
+ }"
+ @click.stop="selectColumn(header.index)"
+ >
+ <div class="px-2 py-2 flex items-center overflow-hidden">
+ <span class="flex flex-row items-center select-none">
+ <template
+ v-if="String(header.column.columnDef.header).length > 0"
+ >
+ {{ header.column.columnDef.header }}
+ </template>
+ <br v-else class="min-h-[1rem] inline-flex" />
+ </span>
+
+ <SensitiveDataIcon
+ v-if="isSensitiveColumn(header.index)"
+ class="ml-0.5 shrink-0"
+ />
+ <template v-else-if="isColumnMissingSensitive(header.index)">
+ <FeatureBadgeForInstanceLicense
+ v-if="hasSensitiveFeature"
+ :show="true"
+ custom-class="ml-0.5 shrink-0"
+ feature="bb.feature.sensitive-data"
+ />
+ <FeatureBadge
+ v-else
+ feature="bb.feature.sensitive-data"
+ custom-class="ml-0.5 shrink-0"
+ />
+ </template>
+
+ <ColumnSortedIcon
+ :is-sorted="header.column.getIsSorted()"
+ @click="header.column.getToggleSortingHandler()?.($event)"
+ />
+ </div>
+ </th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr
+ v-for="(row, rowIndex) of rows"
+ :key="rowIndex"
+ class="group"
+ :data-row-index="offset + rowIndex"
+ >
+ <td
+ v-for="(cell, cellIndex) of row.getVisibleCells()"
+ :key="cellIndex"
+ class="relative min-w-8 max-w-[50vw] p-0 text-sm dark:text-gray-100 leading-5 whitespace-nowrap break-all border-l first:border-l-0 border-block-border dark:border-zinc-500 group-even:bg-gray-100/50 dark:group-even:bg-gray-700/50"
+ :data-col-index="cellIndex"
+ >
+ <TableCell
+ :table="table"
+ :value="cell.getValue() as RowValue"
+ :keyword="keyword"
+ :set-index="setIndex"
+ :row-index="offset + rowIndex"
+ :col-index="cellIndex"
+ />
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import type { Table } from "@tanstack/vue-table";
+import { computed, nextTick, ref, watch } from "vue";
+import {
+ FeatureBadge,
+ FeatureBadgeForInstanceLicense,
+} from "@/components/FeatureGuard";
+import { useSubscriptionV1Store } from "@/store";
+import type { QueryRow, RowValue } from "@/types/proto/v1/sql_service";
+import ColumnSortedIcon from "../DataTable/common/ColumnSortedIcon.vue";
+import SensitiveDataIcon from "../DataTable/common/SensitiveDataIcon.vue";
+import { useSQLResultViewContext } from "../context";
+import TableCell from "./TableCell.vue";
+import { useSelectionContext } from "./common/selection-logic";
+
+const props = defineProps<{
+ table: Table<QueryRow>;
+ setIndex: number;
+ offset: number;
+ isSensitiveColumn: (index: number) => boolean;
+ isColumnMissingSensitive: (index: number) => boolean;
+ maxHeight?: number;
+}>();
+
+const {
+ state: selectionState,
+ disabled: selectionDisabled,
+ selectColumn,
+} = useSelectionContext();
+const containerRef = ref<HTMLDivElement>();
+const subscriptionStore = useSubscriptionV1Store();
+
+const { keyword } = useSQLResultViewContext();
+
+const hasSensitiveFeature = computed(() => {
+ return subscriptionStore.hasFeature("bb.feature.sensitive-data");
+});
+
+const scrollTo = (x: number, y: number) => {
+ containerRef.value?.scroll(x, y);
+};
+
+const rows = computed(() => props.table.getRowModel().rows);
+
+watch(
+ () =>
+ props.table
+ .getFlatHeaders()
+ .map((header) => String(header.column.columnDef.header))
+ .join("|"),
+ () => {
+ nextTick(() => {
+ // Re-calculate the column widths once the column definition changed.
+ scrollTo(0, 0);
+ });
+ },
+ { immediate: true }
+);
+
+watch(
+ () => props.offset,
+ () => {
+ // When the offset changed, we need to reset the scroll position.
+ scrollTo(0, 0);
+ }
+);
+</script>
diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/DataTableLite/ColumnHeader.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/DataTableLite/ColumnHeader.vue
deleted file mode 100644
index 8a53706660..0000000000
--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/DataTableLite/ColumnHeader.vue
+++ /dev/null
@@ -1,86 +0,0 @@
-<template>
- <div
- class="group relative px-2 h-[32px] min-w-[2rem] whitespace-nowrap text-left bg-gray-50 dark:bg-gray-700 text-xs font-medium text-gray-500 dark:text-gray-300 tracking-wider"
- :class="{
- 'cursor-pointer': !selectionDisabled,
- }"
- @click.stop="selectColumn(header.index)"
- >
- <div
- v-if="!selectionDisabled"
- class="absolute inset-0 group-hover:bg-accent/10 pointer-events-none"
- :class="selectionState.columns.includes(header.index) && 'bg-accent/10'"
- />
- <div class="h-full flex items-center overflow-hidden">
- <span class="flex flex-row items-center select-none">
- <template v-if="String(header.column.columnDef.header).length > 0">
- {{ header.column.columnDef.header }}
- </template>
- <br v-else class="min-h-[1rem] inline-flex" />
- </span>
-
- <SensitiveDataIcon
- v-if="isSensitiveColumn(header.index)"
- class="ml-0.5 shrink-0"
- />
- <template v-else-if="isColumnMissingSensitive(header.index)">
- <FeatureBadgeForInstanceLicense
- v-if="hasSensitiveFeature"
- :show="true"
- custom-class="ml-0.5 shrink-0"
- feature="bb.feature.sensitive-data"
- />
- <FeatureBadge
- v-else
- feature="bb.feature.sensitive-data"
- custom-class="ml-0.5 shrink-0"
- />
- </template>
-
- <ColumnSortedIcon
- :is-sorted="header.column.getIsSorted()"
- @click="header.column.getToggleSortingHandler()?.($event)"
- />
- </div>
-
- <!-- The drag-to-resize handler -->
- <div
- class="group absolute w-[8px] right-0 top-0 bottom-0 cursor-col-resize"
- @pointerdown="$emit('start-resizing')"
- @dblclick="$emit('auto-resize')"
- >
- <div
- class="absolute w-[3px] right-0 top-0 bottom-0 group-hover:bg-accent/30"
- />
- </div>
- </div>
-</template>
-
-<script setup lang="ts">
-import type { Header } from "@tanstack/vue-table";
-import FeatureBadge from "@/components/FeatureGuard/FeatureBadge.vue";
-import FeatureBadgeForInstanceLicense from "@/components/FeatureGuard/FeatureBadgeForInstanceLicense.vue";
-import { featureToRef } from "@/store";
-import type { QueryRow } from "@/types/proto/v1/sql_service";
-import ColumnSortedIcon from "../common/ColumnSortedIcon.vue";
-import SensitiveDataIcon from "../common/SensitiveDataIcon.vue";
-import { useSelectionContext } from "../common/selection-logic";
-
-defineProps<{
- header: Header<QueryRow, any>;
- isSensitiveColumn: (index: number) => boolean;
- isColumnMissingSensitive: (index: number) => boolean;
-}>();
-
-defineEmits<{
- (event: "start-resizing"): void;
- (event: "auto-resize"): void;
-}>();
-
-const {
- state: selectionState,
- disabled: selectionDisabled,
- selectColumn,
-} = useSelectionContext();
-const hasSensitiveFeature = featureToRef("bb.feature.sensitive-data");
-</script>
diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/DataTableLite/DataTableLite.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/DataTableLite/DataTableLite.vue
deleted file mode 100644
index 158d7b19bc..0000000000
--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/DataTableLite/DataTableLite.vue
+++ /dev/null
@@ -1,264 +0,0 @@
-<template>
- <div
- ref="containerRef"
- class="relative w-full flex-1 overflow-hidden flex flex-col"
- :data-width="containerWidth"
- :data-height="containerHeight"
- >
- <div
- class="header-track absolute z-[1] left-0 top-0 right-0 h-[34px] border border-block-border bg-gray-50 dark:bg-gray-700"
- />
- <div
- class="absolute z-[0] left-0 right-0 border-b border-r border-block-border"
- :style="padStyle"
- :data-container-width="containerWidth"
- :data-container-height="containerHeight"
- :data-table-body-height="tableBodyHeight"
- :data-rendered-table-body-height="renderedTableBodyHeight"
- />
-
- <NDataTable
- ref="dataTableRef"
- :columns="columns"
- :data="rows"
- :row-props="rowProps"
- :virtual-scroll="true"
- :virtual-scroll-x="true"
- :virtual-scroll-header="true"
- :header-height="HEADER_HEIGHT"
- :max-height="tableBodyHeight"
- :min-row-height="ROW_HEIGHT"
- :height-for-row="() => ROW_HEIGHT"
- :scroll-x="tableResize.getTableScrollWidth()"
- :scrollbar-props="{
- trigger: 'none',
- }"
- table-layout="fixed"
- size="small"
- class="relative z-[1] -mr-px"
- style="
- --n-th-padding: 0;
- --n-td-padding: 0;
- --n-border-radius: 0;
- --n-border-color: rgb(var(--color-block-border));
- "
- :style="{
- width: `${tableResize.getTableRenderWidth()}px`,
- }"
- />
- </div>
-</template>
-
-<script lang="ts" setup>
-import type { Header, Row, Table } from "@tanstack/vue-table";
-import { pausableWatch, useElementSize } from "@vueuse/core";
-import { type DataTableColumn, type DataTableInst, NDataTable } from "naive-ui";
-import { computed, h, nextTick, ref, toRef, watch, type StyleValue } from "vue";
-import { QueryRow, type RowValue } from "@/types/proto/v1/sql_service";
-import { nextAnimationFrame, usePreventBackAndForward } from "@/utils";
-import { useSQLResultViewContext } from "../../context";
-import ColumnHeader from "./ColumnHeader.vue";
-import TableCell from "./TableCell.vue";
-import useTableColumnWidthLogic from "./useTableResize";
-
-const COLUMN_WIDTH = {
- DEFAULT: 128, // 8rem
- MIN: 64, // 4rem
- MAX: 640, // 40rem
-};
-const HEADER_HEIGHT = 33;
-const GAP_AND_BORDER_HEIGHT = 2;
-const ROW_HEIGHT = 28;
-
-const props = defineProps<{
- table: Table<QueryRow>;
- setIndex: number;
- offset: number;
- isSensitiveColumn: (index: number) => boolean;
- isColumnMissingSensitive: (index: number) => boolean;
- maxHeight?: number;
-}>();
-
-const { keyword } = useSQLResultViewContext();
-
-const headers = computed(() => {
- return props.table.getFlatHeaders() as Header<QueryRow, RowValue>[];
-});
-const rows = computed(() => {
- return props.table.getRowModel().rows;
-});
-const dataTableRef = ref<DataTableInst>();
-const containerRef = ref<HTMLElement>();
-const scrollerRef = computed(() => {
- const getter = (dataTableRef.value as any)?.$refs.mainTableInstRef.$refs
- .bodyInstRef.virtualListContainer;
- if (typeof getter === "function") {
- return getter() as HTMLElement | undefined;
- }
- return undefined;
-});
-const { height: containerHeight, width: containerWidth } =
- useElementSize(containerRef);
-usePreventBackAndForward(scrollerRef);
-
-const tableBodyHeight = ref(0);
-const { pause: pauseWatch, resume: resumeWatch } = pausableWatch(
- [() => props.table.getRowCount(), containerHeight],
- async () => {
- if (containerHeight.value === 0) return;
- if (!props.maxHeight) {
- // The table height is always limited by the container height
- // and need not to be adjusted automatically
- const experimentalMaxBodyHeight =
- containerHeight.value - HEADER_HEIGHT - GAP_AND_BORDER_HEIGHT;
-
- tableBodyHeight.value = Math.max(0, experimentalMaxBodyHeight);
- return;
- }
-
- pauseWatch();
- const experimentalMaxBodyHeight =
- props.maxHeight - HEADER_HEIGHT - GAP_AND_BORDER_HEIGHT;
- tableBodyHeight.value = Math.max(0, experimentalMaxBodyHeight);
- await nextAnimationFrame();
- resumeWatch();
- },
- { immediate: true }
-);
-
-const queryTableHeaderElement = () => {
- return containerRef.value?.querySelector(
- ".n-data-table-base-table-header table.n-data-table-table"
- ) as HTMLElement | undefined;
-};
-const queryTableBodyElement = () => {
- return containerRef.value?.querySelector(
- ".n-data-table-base-table-body table.n-data-table-table"
- ) as HTMLElement | undefined;
-};
-
-const tableResize = useTableColumnWidthLogic({
- table: toRef(props, "table"),
- containerWidth,
- scrollerRef,
- queryTableHeaderElement,
- queryTableBodyElement,
- columnCount: computed(() => headers.value.length),
- defaultWidth: COLUMN_WIDTH.DEFAULT,
- minWidth: COLUMN_WIDTH.MIN,
- maxWidth: COLUMN_WIDTH.MAX,
-});
-
-const tableBodyElemRef = computed(() => {
- return queryTableBodyElement();
-});
-const { height: renderedTableBodyHeight } = useElementSize(tableBodyElemRef);
-const padStyle = computed(() => {
- const style: StyleValue = {
- top: `${HEADER_HEIGHT}px`,
- };
- const height = Math.min(renderedTableBodyHeight.value, tableBodyHeight.value);
- style.height = `${height + GAP_AND_BORDER_HEIGHT}px`;
- return style;
-});
-
-const columns = computed(() => {
- return headers.value.map<DataTableColumn<Row<QueryRow>>>(
- (header, colIndex) => {
- return {
- key: colIndex,
- cellProps: (row) => {
- return {
- class: "truncate",
- "data-row-index": row.index,
- "data-col-index": colIndex,
- };
- },
- title: () => {
- return h(ColumnHeader, {
- header,
- isSensitiveColumn: props.isSensitiveColumn,
- isColumnMissingSensitive: props.isColumnMissingSensitive,
- onStartResizing: () => {
- tableResize.startResizing(colIndex);
- },
- onAutoResize: () => {
- tableResize.autoAdjustColumnWidth([colIndex]);
- },
- });
- },
- render: (row, rowIndex) => {
- const cell = row.getVisibleCells()[colIndex];
- const value = cell.getValue() as RowValue;
- return h(TableCell, {
- table: props.table,
- value,
- width: tableResize.getColumnWidth(colIndex),
- keyword: keyword.value,
- offset: props.offset,
- setIndex: props.setIndex,
- rowIndex: props.offset + rowIndex,
- colIndex,
- class: row.index % 2 === 1 && "bg-gray-100/50 dark:bg-gray-700/50",
- });
- },
- width: tableResize.state.autoAdjusting.has(colIndex)
- ? COLUMN_WIDTH.DEFAULT
- : tableResize.getColumnWidth(colIndex),
- };
- }
- );
-});
-
-const rowProps = (row: Row<QueryRow>) => {
- return {
- class: "group",
- "data-row-index": row.index,
- };
-};
-
-const scrollTo = async (x: number, y: number) => {
- await nextAnimationFrame();
- const table = dataTableRef.value;
- table?.scrollTo(x, y);
-};
-
-watch(
- () =>
- props.table
- .getFlatHeaders()
- .map((header) => String(header.column.columnDef.header))
- .join("|"),
- () => {
- nextTick(() => {
- // Re-calculate the column widths once the column definition changed.
- scrollTo(0, 0);
- tableResize.reset();
- });
- },
- { immediate: true }
-);
-
-watch(
- () => props.offset,
- () => {
- // When the offset changed, we need to reset the scroll position.
- scrollTo(0, 0);
- }
-);
-</script>
-
-<style lang="postcss" scoped>
-:deep(.n-data-table-base-table-body) {
- height: auto;
-}
-:deep(.n-data-table-th .n-data-table-resize-button::after) {
- @apply bg-control-bg h-2/3;
-}
-:deep(.n-data-table-th:not(.n-data-table-th--last)) {
- border-right: 1px solid var(--n-merged-border-color);
-}
-:deep(.n-data-table-td:not(.n-data-table-td--last-col)) {
- border-right: 1px solid var(--n-merged-border-color);
-}
-</style>
diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/DataTableLite/TableCell.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/DataTableLite/TableCell.vue
deleted file mode 100644
index 2017f7d9ad..0000000000
--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/DataTableLite/TableCell.vue
+++ /dev/null
@@ -1,154 +0,0 @@
-<!-- eslint-disable vue/no-v-html -->
-<template>
- <div
- class="relative px-2 py-1 text-sm dark:text-gray-100 leading-5 whitespace-nowrap break-all"
- :class="classes"
- @click="handleClick"
- >
- <div
- ref="wrapperRef"
- class="whitespace-nowrap font-mono text-start line-clamp-1"
- v-html="html"
- ></div>
- <div v-if="clickable" class="absolute right-1 top-1/2 translate-y-[-45%]">
- <NButton
- size="tiny"
- circle
- class="dark:!bg-dark-bg"
- @click.stop="showDetail"
- >
- <template #icon>
- <heroicons:arrows-pointing-out class="w-3 h-3" />
- </template>
- </NButton>
- </div>
- </div>
-</template>
-
-<script setup lang="ts">
-import { type Table } from "@tanstack/vue-table";
-import { escape, uniq } from "lodash-es";
-import { NButton } from "naive-ui";
-import stringWidth from "string-width";
-import { computed, ref } from "vue";
-import { useConnectionOfCurrentSQLEditorTab } from "@/store";
-import { Engine } from "@/types/proto/v1/common";
-import type { QueryRow, RowValue } from "@/types/proto/v1/sql_service";
-import { extractSQLRowValue, getHighlightHTMLByRegExp } from "@/utils";
-import { useSQLResultViewContext } from "../../context";
-import { useSelectionContext } from "../common/selection-logic";
-
-const props = defineProps<{
- table: Table<QueryRow>;
- value: RowValue;
- width: number;
- setIndex: number;
- rowIndex: number;
- colIndex: number;
-}>();
-
-const {
- state: selectionState,
- disabled: selectionDisabled,
- selectRow,
-} = useSelectionContext();
-const { dark, disallowCopyingData, detail, keyword } =
- useSQLResultViewContext();
-const wrapperRef = ref<HTMLDivElement>();
-const plainValue = computed(() => {
- return extractSQLRowValue(props.value).plain;
-});
-const truncated = computed(() => {
- // not that accurate
- const content = String(plainValue.value);
- const em = 8;
- const padding = 8;
- const guessedContentWidth = stringWidth(content) * em + padding * 2;
-
- return guessedContentWidth > props.width;
-});
-
-const { database } = useConnectionOfCurrentSQLEditorTab();
-
-const clickable = computed(() => {
- if (truncated.value) return true;
- if (database.value.instanceResource.engine === Engine.MONGODB) {
- // A cheap way to check JSON string without paying the parsing cost.
- const maybeJSON = String(props.value).trim();
- return (
- (maybeJSON.startsWith("{") && maybeJSON.endsWith("}")) ||
- (maybeJSON.startsWith("[") && maybeJSON.endsWith("]"))
- );
- }
- return false;
-});
-
-const classes = computed(() => {
- const classes: string[] = [];
- if (disallowCopyingData.value) {
- classes.push("select-none");
- }
- if (!selectionDisabled.value) {
- if (props.colIndex === 0) {
- classes.push("cursor-pointer");
- classes.push("hover:bg-accent/10");
- }
- if (
- selectionState.value.columns.includes(props.colIndex) ||
- selectionState.value.rows.includes(props.rowIndex)
- ) {
- classes.push("bg-accent/10");
- }
- }
- if (clickable.value) {
- classes.push("cursor-pointer");
- classes.push(dark.value ? "hover:!bg-white/20" : "hover:!bg-black/5");
- }
- return uniq(classes);
-});
-
-const html = computed(() => {
- const value = plainValue.value;
- if (value === undefined) {
- return `<span class="text-gray-400 italic">UNSET</span>`;
- }
- if (value === null) {
- return `<span class="text-gray-400 italic">NULL</span>`;
- }
- const str = String(value);
- if (str.length === 0) {
- return `<br style="min-width: 1rem; display: inline-flex;" />`;
- }
-
- const kw = keyword.value.trim();
- if (!kw) {
- return escape(str);
- }
-
- return getHighlightHTMLByRegExp(
- escape(str),
- escape(kw),
- false /* !caseSensitive */
- );
-});
-
-const handleClick = (e: MouseEvent) => {
- if (props.colIndex === 0 && !selectionDisabled.value) {
- selectRow(props.rowIndex);
- e.stopPropagation();
- }
-
- if (!clickable.value) return;
- showDetail();
-};
-
-const showDetail = () => {
- detail.value = {
- show: true,
- set: props.setIndex,
- row: props.rowIndex,
- col: props.colIndex,
- table: props.table,
- };
-};
-</script>
diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/DataTableLite/index.ts b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/DataTableLite/index.ts
deleted file mode 100644
index df93d7811d..0000000000
--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/DataTableLite/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import DataTableLite from "./DataTableLite.vue";
-
-export default DataTableLite;
diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/DataTableLite/useTableResize.ts b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/DataTableLite/useTableResize.ts
deleted file mode 100644
index e845fdceb1..0000000000
--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/DataTableLite/useTableResize.ts
+++ /dev/null
@@ -1,427 +0,0 @@
-import type { Header, Table } from "@tanstack/vue-table";
-import { useEventListener, usePointer } from "@vueuse/core";
-import { reject } from "lodash-es";
-import stringWidth from "string-width";
-import type { MaybeRef, Ref } from "vue";
-import { computed, onBeforeUnmount, reactive, unref, watch } from "vue";
-import type { QueryRow, RowValue } from "@/types/proto/v1/sql_service";
-import { extractSQLRowValue, minmax, wrapRefAsPromise } from "@/utils";
-
-const MAX_AUTO_ADJUST_ROW_COUNT = 20;
-const MAX_AUTO_ADJUST_COL_COUNT = 50;
-const MAX_SCAN_RETRIES = 60;
-
-export type TableResizeOptions = {
- table: MaybeRef<Table<QueryRow>>;
- containerWidth: Ref<number>;
- scrollerRef: Ref<HTMLElement | undefined>;
- queryTableHeaderElement: () => HTMLElement | undefined;
- queryTableBodyElement: () => HTMLElement | undefined;
- columnCount: Ref<number>;
- defaultWidth: number;
- minWidth: number;
- maxWidth: number;
-};
-
-type ColumnProps = {
- width: number;
-};
-
-type DragState = {
- start: number;
- index: number;
- initialWidth: number;
-};
-
-type LocalState = {
- columns: ColumnProps[];
- autoAdjusting: Set<number>;
- drag?: DragState;
-};
-
-const useTableResize = (options: TableResizeOptions) => {
- const state = reactive<LocalState>({
- columns: [],
- autoAdjusting: new Set(),
- drag: undefined,
- });
- const pointer = usePointer();
- const scroller = options.scrollerRef;
- const layoutReady = wrapRefAsPromise(
- computed(() => options.containerWidth.value > 0),
- true
- );
-
- const normalizeWidth = (width: number) => {
- if (state.columns.length === 1) {
- // When there is only one column, display it with full width.
- // minus 2px to avoid unexpected horizontal scrollbar.
- return options.containerWidth.value - 2;
- }
- return minmax(width, options.minWidth, options.maxWidth);
- };
-
- const maxAutoAdjustColCount = computed(() => {
- return Math.min(
- options.columnCount.value,
- Math.ceil(options.containerWidth.value / options.minWidth),
- MAX_AUTO_ADJUST_COL_COUNT
- );
- });
- const maxAutoAdjustRowCount = computed(() => {
- return Math.min(
- unref(options.table).getRowCount(),
- MAX_AUTO_ADJUST_ROW_COUNT
- );
- });
-
- const reset = () => {
- layoutReady.then(() => {
- // reset state
- state.drag = undefined;
- state.autoAdjusting.clear();
- state.columns = new Array(options.columnCount.value);
-
- // set initial column widths
- const indexList: number[] = [];
- for (let index = 0; index < options.columnCount.value; index++) {
- if (index < maxAutoAdjustColCount.value) {
- // for columns that will be rendered in the first screen
- // set their widths to minWidth for further render-based auto-width
- state.columns[index] = {
- width: options.minWidth,
- };
- indexList.push(index);
- } else {
- // for columns that won't be rendered in the first screen
- // guess their widths by characters
- state.columns[index] = {
- width: guessColumnWidth(index),
- };
- }
- }
-
- // Calculate a friendly width for every column when the first render happened.
- const scanner = async (n = 0) => {
- if (n > MAX_SCAN_RETRIES) {
- console.warn(
- "[useTableResize] MAX_SCAN_RETRIES exceeded",
- MAX_SCAN_RETRIES
- );
- return;
- }
- // Wait for several frames for the initial render of the table
- requestAnimationFrame(() => {
- const headerTable = options.queryTableHeaderElement();
- const bodyTable = options.queryTableBodyElement();
- const trList = [
- ...Array.from(headerTable?.querySelectorAll("tr") || []),
- ...Array.from(
- bodyTable?.querySelectorAll("tr.n-data-table-tr") || []
- ),
- ] as HTMLElement[];
- if (trList.length === 0) {
- return scanner(n + 1);
- }
- autoAdjustColumnWidth(indexList).catch(() => {
- // auto adjust failed, fallback to guessing column width.
- for (let index = 0; index < state.columns.length; index++) {
- state.columns[index].width = guessColumnWidth(index);
- }
- });
- });
- };
- scanner();
- });
- };
-
- // 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<Map<number, number>> => {
- return new Promise((resolve) => {
- if (indexList.length === 0) {
- return resolve(new Map());
- }
-
- const headerTable = options.queryTableHeaderElement();
- const bodyTable = options.queryTableBodyElement();
- const trList = [
- ...Array.from(headerTable?.querySelectorAll("tr") || []),
- ...Array.from(
- bodyTable?.querySelectorAll("tr.n-data-table-tr") || []
- ).slice(0, maxAutoAdjustRowCount.value), // Do not adjust too many rows
- ] as HTMLElement[];
- console.debug(
- "[autoAdjustColumnWidth]",
- indexList.join("|"),
- `(${trList.length} rows)`
- );
- if (trList.length === 0) {
- return reject(undefined);
- }
-
- const cellsMapByColumn = new Map<number, Array<HTMLElement>>();
- indexList.forEach((index) => {
- const cells: Array<HTMLElement> = [];
- for (let row = 0; row < trList.length; row++) {
- const tr = trList[row];
- const children = Array.from(tr.children).filter((child) => {
- return isNDataTableCell(child);
- });
- if (children.length === 0) {
- return;
- }
- // When the table is scrolled horizontally, some left columns will not
- // be actually rendered.
- // So we need to find out the col index of the first rendered column
- // to get the column with offset.
- const first = children[0];
- const offset = parseInt(
- first.getAttribute("data-col-key") || "0",
- 10
- );
- const cell = children[index - offset];
- if (cell) {
- cells.push(cell);
- }
- }
- if (cells.length > 0) {
- cellsMapByColumn.set(index, cells);
- }
- });
- console.debug(
- "[autoAdjustColumnWidth] found cells",
- Array.from(cellsMapByColumn.entries())
- .map(([index, cells]) => `${index}(${cells.length})`)
- .join("|")
- );
-
- // Update the cells' and table's style to estimate the width.
- for (const index of cellsMapByColumn.keys()) {
- state.autoAdjusting.add(index);
- }
-
- for (const [_index, cells] of cellsMapByColumn.entries()) {
- cells.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 headerTableWidthBackup = headerTable?.style.width ?? "";
- const bodyTableWidthBackup = bodyTable?.style.width ?? "";
- if (headerTable) headerTable.style.width = "auto";
- if (bodyTable) bodyTable.style.width = "auto";
-
- // Read the rendered widths.
- const widthMapByColumn = new Map<number, number>();
- indexList.forEach((index) => {
- const cells = cellsMapByColumn.get(index);
- if (!cells) {
- return;
- }
-
- const stretchedWidths = cells.map((cell) => getElementWidth(cell));
- const finalWidth = normalizeWidth(Math.max(...stretchedWidths));
- console.debug(`col#${index}`, stretchedWidths.join("|"), finalWidth);
-
- widthMapByColumn.set(index, finalWidth);
- });
-
- console.debug(
- Array.from(widthMapByColumn.entries())
- .map(([index, width]) => `${index}:${width}`)
- .join("|")
- );
-
- indexList.forEach((index) => {
- const width = widthMapByColumn.get(index) ?? guessColumnWidth(index);
-
- 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.
- return;
- }
- column.width = width;
- });
-
- // Reset the cells' and table's style.
- for (const [_index, cells] of cellsMapByColumn.entries()) {
- cells.forEach((cell) => {
- if (!cell) return;
- cell.style.whiteSpace = "";
- cell.style.overflow = "";
- cell.style.width = "";
- cell.style.maxWidth = "";
- cell.style.minWidth = "";
- });
- }
- if (headerTable) {
- headerTable.style.width = headerTableWidthBackup;
- }
- if (bodyTable) {
- bodyTable.style.width = bodyTableWidthBackup;
- }
- state.autoAdjusting.clear();
-
- resolve(widthMapByColumn);
- // 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(scroller, 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(scroller.value);
- }
- });
-
- // Reset dragging state when mouse button released.
- useEventListener("pointerup", () => {
- if (state.drag) {
- state.drag = undefined;
- toggleDragStyle(scroller, false);
- }
- });
-
- const getColumnWidth = (index: number) => {
- return state.columns[index]?.width ?? options.defaultWidth;
- };
-
- const totalWidth = computed(() => {
- let totalWidth = 0;
- for (let index = 0; index < options.columnCount.value; index++) {
- const columnWidth = state.autoAdjusting.has(index)
- ? options.maxWidth
- : getColumnWidth(index);
- totalWidth += columnWidth;
- }
- return totalWidth;
- });
-
- const getTableRenderWidth = () => {
- return Math.min(options.containerWidth.value, totalWidth.value + 2);
- };
-
- const getTableScrollWidth = () => {
- return totalWidth.value;
- };
-
- const guessColumnWidth = (
- index: number,
- opts = {
- em: 8,
- padding: 8,
- }
- ) => {
- const table = unref(options.table);
- const maxAutoAdjustRowCount = Math.min(
- table.getRowCount(),
- MAX_AUTO_ADJUST_ROW_COUNT
- );
-
- const charsWidth = (content: string) => {
- return stringWidth(content) * opts.em + opts.padding * 2;
- };
-
- const widths: number[] = [];
-
- const header = table.getFlatHeaders()[index] as Header<QueryRow, RowValue>;
- if (header) {
- const content = String(header.column.columnDef.header);
- const width = charsWidth(content) + 4 + 16; // plus sort icon and gap
- widths.push(width);
- }
-
- for (let r = 0; r < maxAutoAdjustRowCount; r++) {
- const row = table.getRowModel().rows[r];
- const cell = row?.getVisibleCells()[index];
- if (!cell) continue;
- const value = cell.getValue() as RowValue;
- const content = String(extractSQLRowValue(value).plain);
- widths.push(charsWidth(content));
- }
-
- const guessed = Math.max(...widths);
- return normalizeWidth(guessed);
- };
-
- onBeforeUnmount(() => {
- toggleDragStyle(scroller, false);
- });
-
- return {
- state,
- layoutReady,
- reset,
- getColumnWidth,
- getTableRenderWidth,
- getTableScrollWidth,
- startResizing,
- autoAdjustColumnWidth,
- };
-};
-
-export default useTableResize;
-
-const scrollMaxX = (elem: HTMLElement | undefined) => {
- if (!elem) return;
- const max = elem.scrollWidth;
- elem.scrollTo(max, elem.scrollTop);
-};
-
-const getElementWidth = (elem: HTMLElement | undefined) => {
- if (!elem) return 0;
- const rect = elem.getBoundingClientRect();
- return rect.width;
-};
-
-const toggleDragStyle = (
- element: Ref<HTMLElement | undefined>,
- on: boolean
-) => {
- if (on) {
- // Prevent text selection while dragging.
- document.body.classList.add("select-none");
- // Set the cursor style.
- document.body.classList.add("cursor-col-resize");
- } else {
- requestAnimationFrame(() => {
- document.body.classList.remove("select-none");
- document.body.classList.remove("cursor-col-resize");
- });
- }
-};
-
-const isNDataTableCell = (elem: Element): elem is HTMLElement => {
- return (
- elem.classList.contains("n-data-table-th") ||
- elem.classList.contains("n-data-table-td")
- );
-};
diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/DataTable/TableCell.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/TableCell.vue
similarity index 91%
rename from frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/DataTable/TableCell.vue
rename to frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/TableCell.vue
index d48635258f..5208b6176a 100644
--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/DataTable/TableCell.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/TableCell.vue
@@ -1,6 +1,11 @@
<!-- eslint-disable vue/no-v-html -->
<template>
- <div class="relative px-2 py-1" :class="classes" @click="handleClick">
+ <div
+ class="relative px-2 py-1"
+ :class="classes"
+ @click="handleClick"
+ @dblclick="showDetail"
+ >
<div
ref="wrapperRef"
class="whitespace-nowrap font-mono text-start line-clamp-1"
@@ -31,8 +36,8 @@ import { useConnectionOfCurrentSQLEditorTab } from "@/store";
import { Engine } from "@/types/proto/v1/common";
import type { QueryRow, RowValue } from "@/types/proto/v1/sql_service";
import { extractSQLRowValue, getHighlightHTMLByRegExp } from "@/utils";
-import { useSQLResultViewContext } from "../../context";
-import { useSelectionContext } from "../common/selection-logic";
+import { useSQLResultViewContext } from "../context";
+import { useSelectionContext } from "./common/selection-logic";
const props = defineProps<{
table: Table<QueryRow>;
@@ -86,13 +91,13 @@ const classes = computed(() => {
if (!selectionDisabled.value) {
if (props.colIndex === 0) {
classes.push("cursor-pointer");
- classes.push("hover:bg-accent/10");
+ classes.push("hover:bg-accent/10 hover:dark:bg-accent/40");
}
if (
selectionState.value.columns.includes(props.colIndex) ||
selectionState.value.rows.includes(props.rowIndex)
) {
- classes.push("bg-accent/10");
+ classes.push("bg-accent/10 dark:bg-accent/40");
}
}
if (clickable.value) {
diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/index.ts b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/index.ts
index ab54e4f8eb..94a54fa8eb 100644
--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/index.ts
+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/index.ts
@@ -1,4 +1,4 @@
-import DataTable from "./DataTable";
-import DataTableLite from "./DataTableLite";
+import DataTable from "./DataTable.vue";
+import DataTableLite from "./DataTableLite.vue";
export { DataTable, DataTableLite };
diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/DataTable/useTableResize.ts b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/useTableResize.ts
similarity index 100%
rename from frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/DataTable/useTableResize.ts
rename to frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/useTableResize.ts
diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultViewV1.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultViewV1.vue
index 21104adb0e..bea4af470a 100644
--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultViewV1.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultViewV1.vue
@@ -64,14 +64,6 @@
/>
</template>
</NPagination>
- <NButton
- v-if="showVisualizeButton"
- text
- type="primary"
- @click="visualizeExplain"
- >
- {{ $t("sql-editor.visualize-explain") }}
- </NButton>
<NTooltip v-if="DISMISS_PLACEHOLDER">
<template #trigger>
<NButton
@@ -153,8 +145,17 @@
<div class="flex-1 truncate">
{{ result.statement }}
</div>
- <div class="shrink-0">
- {{ $t("sql-editor.query-time") }}: {{ queryTime }}
+ <div class="shrink-0 space-x-2">
+ <NButton
+ v-if="showVisualizeButton"
+ text
+ type="primary"
+ @click="visualizeExplain"
+ size="tiny"
+ >
+ {{ $t("sql-editor.visualize-explain") }}
+ </NButton>
+ <span>{{ $t("sql-editor.query-time") }}: {{ queryTime }}</span>
</div>
</div>
</template>