Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
fix(frontend): restore React table detail parity (#19935)
p0ny9aca0f966357
diff --git a/frontend/src/react/components/ui/table.tsx b/frontend/src/react/components/ui/table.tsxnew file mode 100644index 0000000000..cc74900e5f--- /dev/null+++ b/frontend/src/react/components/ui/table.tsx@@ -0,0 +1,59 @@+import type { ComponentPropsWithoutRef } from "react";+import { cn } from "@/react/lib/utils";++function Table({ className, ...props }: ComponentPropsWithoutRef<"table">) {+ return (+ <table+ className={cn("w-full caption-bottom text-sm", className)}+ {...props}+ />+ );+}++function TableHeader({+ className,+ ...props+}: ComponentPropsWithoutRef<"thead">) {+ return <thead className={cn("[&_tr]:border-b", className)} {...props} />;+}++function TableBody({ className, ...props }: ComponentPropsWithoutRef<"tbody">) {+ return (+ <tbody className={cn("[&_tr:last-child]:border-0", className)} {...props} />+ );+}++function TableRow({ className, ...props }: ComponentPropsWithoutRef<"tr">) {+ return (+ <tr+ className={cn(+ "border-b border-block-border transition-colors hover:bg-control-bg/60 data-[state=selected]:bg-control-bg",+ className+ )}+ {...props}+ />+ );+}++function TableHead({ className, ...props }: ComponentPropsWithoutRef<"th">) {+ return (+ <th+ className={cn(+ "h-10 px-4 py-2 text-left align-middle font-medium text-control-light",+ className+ )}+ {...props}+ />+ );+}++function TableCell({ className, ...props }: ComponentPropsWithoutRef<"td">) {+ return (+ <td+ className={cn("px-4 py-3 align-middle text-sm text-control", className)}+ {...props}+ />+ );+}++export { Table, TableBody, TableCell, TableHead, TableHeader, TableRow };diff --git a/frontend/src/react/locales/en-US.json b/frontend/src/react/locales/en-US.jsonindex 863fb85230..8cc04bc8dc 100644--- a/frontend/src/react/locales/en-US.json+++ b/frontend/src/react/locales/en-US.json@@ -347,6 +347,8 @@"common.password": "Password","common.project": "Project","common.read-only": "Read-only",+ "common.remove": "Remove",+ "common.removed": "Removed","common.restore": "Restore","common.rollout": "Rollout","common.sensitive-placeholder": "Sensitive - write only",@@ -518,11 +520,15 @@"expression": "Expression","filter-database": "Filter database","index-size": "Index size",+ "indexes": "Indexes","last-sync": "Last sync","mixed-label-values": "mixed values","mixed-label-values-warning": "Some of the selected resources have mixed values for the same key. Only edit these key-value pairs if you intend to change them.",+ "nullable": "Nullable",+ "partition-tables": "Partition tables","partitioned": "Partitioned","row-count-est": "Row count est.",+ "row-count-estimate": "Row count estimate","select": "Select database","selected-n-databases": "{{n}} database(s) selected","successfully-transferred-databases": "Successfully transferred databases",@@ -555,7 +561,9 @@"transfer-project": "Transfer Project","unassign": "Unassign","unassign-alert-description": "The selected databases will be removed from the project",- "unassign-alert-title": "Unassign databases"+ "unassign-alert-title": "Unassign databases",+ "unique": "Unique",+ "visible": "Visible"},"database-group": {"condition": {@@ -606,6 +614,12 @@"syncing-databases-for-instance": "Syncing databases for {{0}}...","tables": "Tables","tasks": "Tasks",+ "trigger": {+ "body": "Body",+ "event": "Event",+ "timing": "Timing"+ },+ "triggers": "Triggers","views": "Views"},"db.failed-to-sync-schema": "Failed to sync schema",@@ -1372,7 +1386,8 @@},"schema-template": {"classification": {- "search": "Search classification"+ "search": "Search classification",+ "select": "Select classification"}},"setting": {diff --git a/frontend/src/react/locales/es-ES.json b/frontend/src/react/locales/es-ES.jsonindex 703c21f21a..5205612105 100644--- a/frontend/src/react/locales/es-ES.json+++ b/frontend/src/react/locales/es-ES.json@@ -347,6 +347,8 @@"common.password": "Contraseña","common.project": "Proyecto","common.read-only": "Solo lectura",+ "common.remove": "Eliminar",+ "common.removed": "Eliminado","common.restore": "Restaurar","common.rollout": "Implementar","common.sensitive-placeholder": "Sensible - solo escritura",@@ -518,11 +520,15 @@"expression": "Expression","filter-database": "Filtrar base de datos","index-size": "Tamaño del índice",+ "indexes": "Índices","last-sync": "Última sincronización","mixed-label-values": "valores mixtos","mixed-label-values-warning": "Algunos de los recursos seleccionados tienen valores mixtos para la misma clave. Solo edite estos pares clave-valor si tiene la intención de cambiarlos.",+ "nullable": "Anulable",+ "partition-tables": "Tablas de particiones","partitioned": "Particionado","row-count-est": "Conteo estimado de filas",+ "row-count-estimate": "Estimación de la cantidad de filas","select": "Seleccionar base de datos","selected-n-databases": "{{n}} base(s) de datos seleccionada(s)","successfully-transferred-databases": "Bases de datos transferidas exitosamente",@@ -555,7 +561,9 @@"transfer-project": "Transferir proyecto","unassign": "Desasignar","unassign-alert-description": "Las bases de datos seleccionadas serán eliminadas del proyecto",- "unassign-alert-title": "Desasignar bases de datos"+ "unassign-alert-title": "Desasignar bases de datos",+ "unique": "Único",+ "visible": "Visible"},"database-group": {"condition": {@@ -606,6 +614,12 @@"syncing-databases-for-instance": "Sincronizando bases de datos para {{0}}...","tables": "Tablas","tasks": "Tareas",+ "trigger": {+ "body": "Cuerpo",+ "event": "Evento",+ "timing": "Momento"+ },+ "triggers": "Desencadenantes","views": "Vistas"},"db.failed-to-sync-schema": "No se pudo sincronizar el esquema",@@ -1372,7 +1386,8 @@},"schema-template": {"classification": {- "search": "Clasificación de búsqueda"+ "search": "Clasificación de búsqueda",+ "select": "Seleccionar clasificación"}},"setting": {diff --git a/frontend/src/react/locales/ja-JP.json b/frontend/src/react/locales/ja-JP.jsonindex 160186c3a1..d9c4281643 100644--- a/frontend/src/react/locales/ja-JP.json+++ b/frontend/src/react/locales/ja-JP.json@@ -347,6 +347,8 @@"common.password": "パスワード","common.project": "プロジェクト","common.read-only": "読み取り専用",+ "common.remove": "削除",+ "common.removed": "削除されました","common.restore": "復元する","common.rollout": "リリース","common.sensitive-placeholder": "機密データ - 書き込みのみ",@@ -518,11 +520,15 @@"expression": "Expression","filter-database": "データベースをフィルター","index-size": "インデックスサイズ",+ "indexes": "索引","last-sync": "最後の同期","mixed-label-values": "混合値","mixed-label-values-warning": "選択されたリソースの一部は、同じキーに対して異なる値を持っています。これらのキーと値のペアを変更する場合にのみ編集してください。",+ "nullable": "null も可能",+ "partition-tables": "パーティションテーブル","partitioned": "パーティション","row-count-est": "推定行数",+ "row-count-estimate": "推定行数","select": "データベースの選択","selected-n-databases": "{{n}} 個のデータベースが選択されました","successfully-transferred-databases": "データベースの転送に成功しました",@@ -555,7 +561,9 @@"transfer-project": "プロジェクトの転送","unassign": "割り当てを解除する","unassign-alert-description": "選択したデータベースがプロジェクトから削除されます",- "unassign-alert-title": "データベースの割り当てを解除する"+ "unassign-alert-title": "データベースの割り当てを解除する",+ "unique": "唯一",+ "visible": "見える"},"database-group": {"condition": {@@ -606,6 +614,12 @@"syncing-databases-for-instance": "{{0}} のデータベースを同期中...","tables": "テーブル","tasks": "タスク",+ "trigger": {+ "body": "本文",+ "event": "イベント",+ "timing": "タイミング"+ },+ "triggers": "トリガー","views": "ビュー"},"db.failed-to-sync-schema": "スキーマの同期に失敗しました",@@ -1372,7 +1386,8 @@},"schema-template": {"classification": {- "search": "カテゴリを検索する"+ "search": "カテゴリを検索する",+ "select": "分類を選択"}},"setting": {diff --git a/frontend/src/react/locales/vi-VN.json b/frontend/src/react/locales/vi-VN.jsonindex 2a733ad57e..ee1e6ba6da 100644--- a/frontend/src/react/locales/vi-VN.json+++ b/frontend/src/react/locales/vi-VN.json@@ -347,6 +347,8 @@"common.password": "Mật khẩu","common.project": "Dự án","common.read-only": "Chỉ đọc",+ "common.remove": "Xóa",+ "common.removed": "LOẠI BỎ","common.restore": "Khôi phục","common.rollout": "Triển khai","common.sensitive-placeholder": "Nhạy cảm - Chỉ ghi",@@ -518,11 +520,15 @@"expression": "Expression","filter-database": "Lọc cơ sở dữ liệu","index-size": "Kích thước chỉ mục",+ "indexes": "Chỉ mục","last-sync": "Lần đồng bộ cuối cùng","mixed-label-values": "giá trị hỗn hợp","mixed-label-values-warning": "Một số tài nguyên đã chọn có các giá trị khác nhau cho cùng một khóa. Chỉ chỉnh sửa các cặp khóa-giá trị này nếu bạn muốn thay đổi chúng.",+ "nullable": "Có thể null",+ "partition-tables": "Bảng phân vùng","partitioned": "Đã phân vùng","row-count-est": "Ước tính số hàng",+ "row-count-estimate": "Ước tính số hàng","select": "Chọn cơ sở dữ liệu","selected-n-databases": "Đã chọn {{n}} cơ sở dữ liệu","successfully-transferred-databases": "Chuyển cơ sở dữ liệu thành công",@@ -555,7 +561,9 @@"transfer-project": "Chuyển dự án","unassign": "Hủy gán","unassign-alert-description": "Các cơ sở dữ liệu đã chọn sẽ bị xóa khỏi dự án",- "unassign-alert-title": "Hủy gán cơ sở dữ liệu"+ "unassign-alert-title": "Hủy gán cơ sở dữ liệu",+ "unique": "Duy nhất",+ "visible": "Hiển thị"},"database-group": {"condition": {@@ -606,6 +614,12 @@"syncing-databases-for-instance": "Đang đồng bộ hóa cơ sở dữ liệu cho {{0}}...","tables": "Bảng","tasks": "Tác vụ",+ "trigger": {+ "body": "Nội dung",+ "event": "Sự kiện",+ "timing": "Thời điểm"+ },+ "triggers": "Trình kích hoạt","views": "Khung nhìn"},"db.failed-to-sync-schema": "Không đồng bộ hóa được lược đồ",@@ -1372,7 +1386,8 @@},"schema-template": {"classification": {- "search": "Tìm kiếm phân loại"+ "search": "Tìm kiếm phân loại",+ "select": "Chọn phân loại"}},"setting": {diff --git a/frontend/src/react/locales/zh-CN.json b/frontend/src/react/locales/zh-CN.jsonindex 13d1465947..c5a3254006 100644--- a/frontend/src/react/locales/zh-CN.json+++ b/frontend/src/react/locales/zh-CN.json@@ -347,6 +347,8 @@"common.password": "密码","common.project": "项目","common.read-only": "只读",+ "common.remove": "删除",+ "common.removed": "已移除","common.restore": "恢复","common.rollout": "发布","common.sensitive-placeholder": "敏感数据 - 仅写入",@@ -518,11 +520,15 @@"expression": "Expression","filter-database": "筛选数据库","index-size": "索引大小",+ "indexes": "索引","last-sync": "最后一次同步","mixed-label-values": "混合值","mixed-label-values-warning": "部分标签拥有不同的值,编辑标签将会批量应用。仅在您打算更改时再编辑这些键值对。",+ "nullable": "可为空",+ "partition-tables": "分区表","partitioned": "分区","row-count-est": "估算行数",+ "row-count-estimate": "估计行数","select": "选择数据库","selected-n-databases": "已选择 {{n}} 个数据库","successfully-transferred-databases": "成功转移数据库",@@ -555,7 +561,9 @@"transfer-project": "转移项目","unassign": "取消分配","unassign-alert-description": "选定的数据库将从项目中移除",- "unassign-alert-title": "取消分配数据库"+ "unassign-alert-title": "取消分配数据库",+ "unique": "唯一",+ "visible": "Visible"},"database-group": {"condition": {@@ -606,6 +614,12 @@"syncing-databases-for-instance": "正在同步 {{0}} 的数据库...","tables": "表","tasks": "任务",+ "trigger": {+ "body": "主体",+ "event": "事件",+ "timing": "时机"+ },+ "triggers": "触发器","views": "视图"},"db.failed-to-sync-schema": "同步 schema 失败",@@ -1372,7 +1386,8 @@},"schema-template": {"classification": {- "search": "搜索分类"+ "search": "搜索分类",+ "select": "选择分类"}},"setting": {diff --git a/frontend/src/react/pages/project/database-detail/overview/DatabaseObjectExplorer.test.tsx b/frontend/src/react/pages/project/database-detail/overview/DatabaseObjectExplorer.test.tsxnew file mode 100644index 0000000000..e481d57025--- /dev/null+++ b/frontend/src/react/pages/project/database-detail/overview/DatabaseObjectExplorer.test.tsx@@ -0,0 +1,314 @@+import { act, createElement } from "react";+import { createRoot } from "react-dom/client";+import { beforeEach, describe, expect, test, vi } from "vitest";+import { Engine } from "@/types/proto-es/v1/common_pb";+import type { Database } from "@/types/proto-es/v1/database_service_pb";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++const mocks = vi.hoisted(() => {+ const currentRoute = {+ value: {+ query: {},+ },+ };++ return {+ currentRoute,+ routerReplace: vi.fn(() => Promise.resolve()),+ useVueState: vi.fn(),+ useDatabaseCatalog: vi.fn(),+ getColumnCatalog: vi.fn(() => ({+ semanticType: "",+ classification: "",+ })),+ getTableCatalog: vi.fn(),+ featureToRef: vi.fn(() => ({ value: true })),+ useDBSchemaV1Store: vi.fn(),+ useSettingV1Store: vi.fn(),+ getDatabaseProject: vi.fn((database: { project: string }) => ({+ name: database.project,+ dataClassificationConfigId: "classification-config",+ })),+ getDatabaseEngine: vi.fn(() => Engine.POSTGRES),+ hasIndexSizeProperty: vi.fn(() => true),+ hasSchemaProperty: vi.fn(() => true),+ hasTableEngineProperty: vi.fn(() => false),+ instanceV1HasCollationAndCharacterSet: vi.fn(() => true),+ instanceV1SupportsColumn: vi.fn(() => true),+ instanceV1SupportsIndex: vi.fn(() => true),+ instanceV1SupportsPackage: vi.fn(() => false),+ instanceV1SupportsSequence: vi.fn(() => false),+ instanceV1SupportsTrigger: vi.fn(() => false),+ bytesToString: vi.fn((size: number) => `${size} B`),+ hasProjectPermissionV2: vi.fn(() => true),+ dialogProps: [] as unknown[],+ useTranslation: vi.fn(() => ({+ t: (key: string) => key,+ })),+ };+});++let DatabaseObjectExplorer: typeof import("./DatabaseObjectExplorer").DatabaseObjectExplorer;++vi.mock("react-i18next", () => ({+ useTranslation: mocks.useTranslation,+}));++vi.mock("@/react/hooks/useVueState", () => ({+ useVueState: mocks.useVueState,+}));++vi.mock("@/router", () => ({+ router: {+ replace: mocks.routerReplace,+ currentRoute: mocks.currentRoute,+ },+}));++vi.mock("@/store", () => ({+ useDBSchemaV1Store: mocks.useDBSchemaV1Store,+ useDatabaseCatalog: mocks.useDatabaseCatalog,+ getColumnCatalog: mocks.getColumnCatalog,+ getTableCatalog: mocks.getTableCatalog,+ featureToRef: mocks.featureToRef,+ useSettingV1Store: mocks.useSettingV1Store,+}));++vi.mock("@/utils", () => ({+ bytesToString: mocks.bytesToString,+ getDatabaseEngine: mocks.getDatabaseEngine,+ getDatabaseProject: mocks.getDatabaseProject,+ hasIndexSizeProperty: mocks.hasIndexSizeProperty,+ hasProjectPermissionV2: mocks.hasProjectPermissionV2,+ hasSchemaProperty: mocks.hasSchemaProperty,+ hasTableEngineProperty: mocks.hasTableEngineProperty,+ instanceV1HasCollationAndCharacterSet:+ mocks.instanceV1HasCollationAndCharacterSet,+ instanceV1SupportsColumn: mocks.instanceV1SupportsColumn,+ instanceV1SupportsIndex: mocks.instanceV1SupportsIndex,+ instanceV1SupportsPackage: mocks.instanceV1SupportsPackage,+ instanceV1SupportsSequence: mocks.instanceV1SupportsSequence,+ instanceV1SupportsTrigger: mocks.instanceV1SupportsTrigger,+}));++vi.mock("@/react/components/ui/input", () => ({+ Input: (props: React.InputHTMLAttributes<HTMLInputElement>) => (+ <input {...props} />+ ),+}));++vi.mock("./TableDetailDialog", () => ({+ EditableClassificationCell: () => null,+ TableDetailDialog: (props: unknown) => {+ mocks.dialogProps.push(props);+ return null;+ },+}));++const renderIntoContainer = (element: ReturnType<typeof createElement>) => {+ const container = document.createElement("div");+ const root = createRoot(container);++ return {+ container,+ render: () => {+ act(() => {+ root.render(element);+ });+ },+ unmount: () =>+ act(() => {+ root.unmount();+ }),+ };+};++const flush = async () => {+ await act(async () => {+ await Promise.resolve();+ await Promise.resolve();+ });+};++const clickElement = (element: Element) => {+ act(() => {+ element.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });+};++const makeDatabase = (): Database =>+ ({+ name: "instances/inst1/databases/db",+ project: "projects/proj1",+ instanceResource: {+ name: "instances/inst1",+ engine: Engine.POSTGRES,+ },+ }) as Database;++const makeTable = (name: string) =>+ ({+ name,+ rowCount: 7,+ dataSize: 64n,+ indexSize: 32n,+ comment: `${name} comment`,+ partitions: [+ {+ name: `${name}_2026`,+ type: 1,+ expression: "FOR VALUES FROM ('2026-01-01') TO ('2027-01-01')",+ subpartitions: [],+ },+ ],+ triggers: [+ {+ name: `${name}_before_insert`,+ event: "INSERT",+ timing: "BEFORE",+ body: "EXECUTE FUNCTION demo()",+ sqlMode: "",+ },+ ],+ columns: [+ {+ name: "id",+ type: "INT",+ comment: "",+ },+ ],+ }) as never;++beforeEach(async () => {+ mocks.currentRoute.value.query = {};+ mocks.routerReplace.mockReset();+ mocks.useTranslation.mockReset();+ mocks.useTranslation.mockReturnValue({+ t: (key: string) => key,+ });+ mocks.getDatabaseEngine.mockReset();+ mocks.getDatabaseEngine.mockReturnValue(Engine.POSTGRES);+ mocks.hasSchemaProperty.mockReset();+ mocks.hasSchemaProperty.mockReturnValue(true);+ mocks.instanceV1SupportsPackage.mockReset();+ mocks.instanceV1SupportsPackage.mockReturnValue(false);+ mocks.instanceV1SupportsSequence.mockReset();+ mocks.instanceV1SupportsSequence.mockReturnValue(false);+ mocks.instanceV1SupportsTrigger.mockReset();+ mocks.instanceV1SupportsTrigger.mockReturnValue(false);+ mocks.bytesToString.mockReset();+ mocks.bytesToString.mockImplementation((size: number) => `${size} B`);+ mocks.hasProjectPermissionV2.mockReset();+ mocks.hasProjectPermissionV2.mockReturnValue(true);+ mocks.useDBSchemaV1Store.mockReset();+ mocks.useDBSchemaV1Store.mockReturnValue({+ getSchemaList: vi.fn(() => [{ name: "public" }]),+ getTableList: vi.fn(() => [makeTable("orders")]),+ getViewList: vi.fn(() => []),+ getExtensionList: vi.fn(() => []),+ getExternalTableList: vi.fn(() => []),+ getFunctionList: vi.fn(() => []),+ getDatabaseMetadata: vi.fn(() => ({+ schemas: [],+ })),+ });+ mocks.useDatabaseCatalog.mockReset();+ mocks.useDatabaseCatalog.mockReturnValue({+ value: {+ schemas: [],+ },+ });+ mocks.getColumnCatalog.mockReset();+ mocks.getColumnCatalog.mockReturnValue({+ semanticType: "",+ classification: "",+ });+ mocks.getTableCatalog.mockReset();+ mocks.getTableCatalog.mockReturnValue({+ classification: "",+ });+ mocks.featureToRef.mockReset();+ mocks.featureToRef.mockReturnValue({ value: true });+ mocks.useSettingV1Store.mockReset();+ mocks.useSettingV1Store.mockReturnValue({+ getOrFetchSettingByName: vi.fn(),+ getProjectClassification: vi.fn(() => undefined),+ });+ mocks.getDatabaseProject.mockReset();+ mocks.getDatabaseProject.mockImplementation(+ (database: { project: string }) => ({+ name: database.project,+ dataClassificationConfigId: "classification-config",+ })+ );+ mocks.hasIndexSizeProperty.mockReset();+ mocks.hasIndexSizeProperty.mockReturnValue(true);+ mocks.useVueState.mockReset();+ mocks.useVueState.mockImplementation((getter: () => unknown) => getter());+ mocks.hasTableEngineProperty.mockReset();+ mocks.hasTableEngineProperty.mockReturnValue(false);+ mocks.instanceV1HasCollationAndCharacterSet.mockReset();+ mocks.instanceV1HasCollationAndCharacterSet.mockReturnValue(true);+ mocks.instanceV1SupportsColumn.mockReset();+ mocks.instanceV1SupportsColumn.mockReturnValue(true);+ mocks.instanceV1SupportsIndex.mockReset();+ mocks.instanceV1SupportsIndex.mockReturnValue(true);+ mocks.dialogProps.length = 0;++ vi.resetModules();+ ({ DatabaseObjectExplorer } = await import("./DatabaseObjectExplorer"));+});++describe("DatabaseObjectExplorer", () => {+ test("passes serializable detail props after selecting a table row", async () => {+ const { container, render, unmount } = renderIntoContainer(+ createElement(DatabaseObjectExplorer, {+ database: makeDatabase(),+ loading: false,+ selectedSchemaName: "public",+ tableSearchKeyword: "",+ externalTableSearchKeyword: "",+ onSelectedSchemaNameChange: vi.fn(),+ onTableSearchKeywordChange: vi.fn(),+ onExternalTableSearchKeywordChange: vi.fn(),+ })+ );++ render();+ await flush();++ const ordersRow = Array.from(container.querySelectorAll("td"))+ .find((cell) => cell.textContent === "orders")+ ?.closest("tr");+ expect(ordersRow).toBeTruthy();++ clickElement(ordersRow as HTMLTableRowElement);+ await flush();++ const latestDialogProps = mocks.dialogProps.at(-1);+ expect(() => JSON.stringify(latestDialogProps)).not.toThrow();+ expect(latestDialogProps).toEqual(+ expect.objectContaining({+ table: expect.objectContaining({+ partitions: [+ expect.objectContaining({+ name: "orders_2026",+ }),+ ],+ showPartitionTables: true,+ showTriggers: false,+ triggers: [+ expect.objectContaining({+ name: "orders_before_insert",+ }),+ ],+ }),+ })+ );++ unmount();+ });+});diff --git a/frontend/src/react/pages/project/database-detail/overview/DatabaseObjectExplorer.tsx b/frontend/src/react/pages/project/database-detail/overview/DatabaseObjectExplorer.tsxindex dabb564dde..95f5421a3c 100644--- a/frontend/src/react/pages/project/database-detail/overview/DatabaseObjectExplorer.tsx+++ b/frontend/src/react/pages/project/database-detail/overview/DatabaseObjectExplorer.tsx@@ -1,9 +1,17 @@-import { useCallback, useEffect, useState } from "react";+import { useEffect, useState } from "react";import { useTranslation } from "react-i18next";+import { getColumnDefaultValuePlaceholder } from "@/components/SchemaEditorLite/utils/columnDefaultValue";import { Input } from "@/react/components/ui/input";import { useVueState } from "@/react/hooks/useVueState";import { router } from "@/router";-import { useDBSchemaV1Store, useSettingV1Store } from "@/store";+import {+ featureToRef,+ getColumnCatalog,+ getTableCatalog,+ useDatabaseCatalog,+ useDBSchemaV1Store,+ useSettingV1Store,+} from "@/store";import { Engine } from "@/types/proto-es/v1/common_pb";import type {Database,@@ -12,19 +20,32 @@ import type {StreamMetadata,TaskMetadata,} from "@/types/proto-es/v1/database_service_pb";+import { TablePartitionMetadata_Type } from "@/types/proto-es/v1/database_service_pb";import { Setting_SettingName } from "@/types/proto-es/v1/setting_service_pb";+import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";import {+ bytesToString,getDatabaseEngine,getDatabaseProject,+ hasIndexSizeProperty,+ hasProjectPermissionV2,hasSchemaProperty,+ hasTableEngineProperty,+ instanceV1HasCollationAndCharacterSet,+ instanceV1SupportsColumn,+ instanceV1SupportsIndex,instanceV1SupportsPackage,instanceV1SupportsSequence,+ instanceV1SupportsTrigger,} from "@/utils";import {type ObjectSectionRow,ObjectSectionTable,} from "./ObjectSectionTable";-import { VueTableDetailDrawerMount } from "./TableDetailDialog";+import {+ TableDetailDialog,+ type TableDetailDialogData,+} from "./TableDetailDialog";import { TableMetadataTable } from "./TableMetadataTable";function filterByKeyword(name: string, keyword: string) {@@ -92,12 +113,21 @@ export function DatabaseObjectExplorer({const databaseMetadata = useVueState(() =>dbSchemaStore.getDatabaseMetadata(database.name));+ const hasSensitiveDataFeature = useVueState(+ () => featureToRef(PlanFeature.FEATURE_DATA_MASKING).value+ );+ const databaseCatalog = useDatabaseCatalog(database.name, false);+ const catalog = useVueState(() => databaseCatalog.value);const project = getDatabaseProject(database);const classificationConfig = useVueState(() =>settingStore.getProjectClassification(project.dataClassificationConfigId ?? ""));+ const canUpdateCatalog = hasProjectPermissionV2(+ project,+ "bb.databaseCatalogs.update"+ );const [selectedTableName, setSelectedTableName] = useState(routeTable);const selectedSchemaMetadata = databaseMetadata.schemas.find(@@ -116,9 +146,115 @@ export function DatabaseObjectExplorer({? (selectedSchemaMetadata?.packages ?? []): databaseMetadata.schemas.flatMap((schema) => schema.packages ?? []);- const handleDismissDrawer = useCallback(() => {- setSelectedTableName("");- }, []);+ const selectedTable = tableList.find(+ (table) => table.name === selectedTableName+ );+ const selectedTableCatalog = selectedTable+ ? getTableCatalog(catalog, selectedSchemaName, selectedTable.name)+ : undefined;+ const showSemanticTypeColumn =+ hasSensitiveDataFeature &&+ [+ Engine.MYSQL,+ Engine.TIDB,+ Engine.POSTGRES,+ Engine.REDSHIFT,+ Engine.ORACLE,+ Engine.SNOWFLAKE,+ Engine.MSSQL,+ Engine.BIGQUERY,+ Engine.SPANNER,+ Engine.CASSANDRA,+ Engine.TRINO,+ ].includes(databaseEngine);+ const selectedTableDetail: TableDetailDialogData | undefined = selectedTable+ ? {+ database,+ editable: canUpdateCatalog,+ classification: selectedTableCatalog?.classification,+ classificationConfig,+ collation: selectedTable.collation,+ columns: selectedTable.columns.map((column) => {+ const columnCatalog = getColumnCatalog(+ catalog,+ selectedSchemaName,+ selectedTable.name,+ column.name+ );+ return {+ name: column.name,+ semanticType: columnCatalog?.semanticType,+ classification: columnCatalog?.classification,+ type: column.type,+ defaultValue: getColumnDefaultValuePlaceholder(column),+ nullable: column.nullable,+ characterSet: column.characterSet,+ collation: column.collation,+ comment: column.comment,+ };+ }),+ dataSize: bytesToString(Number(selectedTable.dataSize)),+ engine: selectedTable.engine,+ indexes: (selectedTable.indexes ?? []).map((index) => ({+ name: index.name,+ expressions: index.expressions,+ unique: index.unique,+ visible: index.visible,+ comment: index.comment,+ })),+ indexSize: bytesToString(Number(selectedTable.indexSize)),+ partitions: (selectedTable.partitions ?? []).map(+ function mapPartition(+ partition+ ): NonNullable<TableDetailDialogData["partitions"]>[number] {+ return {+ name: partition.name,+ type:+ TablePartitionMetadata_Type[partition.type]+ ?.replace("TYPE_UNSPECIFIED", "UNKNOWN")+ .replaceAll("_", " ") || "UNKNOWN",+ expression: partition.expression,+ children: (partition.subpartitions ?? []).map(mapPartition),+ };+ }+ ),+ name:+ supportsSchema && selectedSchemaName+ ? `"${selectedSchemaName}"."${selectedTable.name}"`+ : selectedTable.name,+ rowCount: String(selectedTable.rowCount),+ schema: selectedSchemaName,+ showCharacterSet: databaseEngine !== Engine.POSTGRES,+ showColumnClassification: hasSensitiveDataFeature,+ showColumnCollation:+ databaseEngine !== Engine.CLICKHOUSE &&+ databaseEngine !== Engine.SNOWFLAKE,+ showColumns: instanceV1SupportsColumn(databaseEngine),+ showCollation: instanceV1HasCollationAndCharacterSet(databaseEngine),+ showEngine: hasTableEngineProperty(databaseEngine),+ showIndexComment: databaseEngine !== Engine.MONGODB,+ showIndexes: instanceV1SupportsIndex(databaseEngine),+ showIndexSize: hasIndexSizeProperty(databaseEngine),+ showIndexVisible:+ databaseEngine !== Engine.POSTGRES &&+ databaseEngine !== Engine.MONGODB,+ showPartitionTables:+ databaseEngine === Engine.POSTGRES &&+ (selectedTable.partitions?.length ?? 0) > 0,+ showSemanticType: showSemanticTypeColumn,+ showTriggers:+ instanceV1SupportsTrigger(databaseEngine) &&+ (selectedTable.triggers?.length ?? 0) > 0,+ tableName: selectedTable.name,+ triggers: (selectedTable.triggers ?? []).map((trigger) => ({+ name: trigger.name,+ event: trigger.event,+ timing: trigger.timing,+ body: trigger.body,+ sqlMode: trigger.sqlMode,+ })),+ }+ : undefined;useEffect(() => {void settingStore.getOrFetchSettingByName(@@ -134,14 +270,12 @@ export function DatabaseObjectExplorer({}, [routeTable]);useEffect(() => {- if (!selectedTableName || loading) {+ if (!selectedTableName || loading || selectedTable) {return;}- const exists = tableList.some((t) => t.name === selectedTableName);- if (!exists) {- setSelectedTableName("");- }- }, [loading, selectedTableName, tableList]);++ setSelectedTableName("");+ }, [loading, selectedTable, selectedTableName]);useEffect(() => {const currentQuery = router.currentRoute.value.query;@@ -359,13 +493,14 @@ export function DatabaseObjectExplorer({</>)}- <VueTableDetailDrawerMount- show={!!selectedTableName}- databaseName={database.name}- schemaName={selectedSchemaName}- tableName={selectedTableName}- classificationConfig={classificationConfig}- onDismiss={handleDismissDrawer}+ <TableDetailDialog+ open={!!selectedTableName}+ table={selectedTableDetail}+ onOpenChange={(open) => {+ if (!open) {+ setSelectedTableName("");+ }+ }}/></div>);diff --git a/frontend/src/react/pages/project/database-detail/overview/TableDetailDialog.test.tsx b/frontend/src/react/pages/project/database-detail/overview/TableDetailDialog.test.tsxnew file mode 100644index 0000000000..867fdce9c8--- /dev/null+++ b/frontend/src/react/pages/project/database-detail/overview/TableDetailDialog.test.tsx@@ -0,0 +1,646 @@+import type {+ ButtonHTMLAttributes,+ ElementType,+ InputHTMLAttributes,+ ReactNode,+} from "react";+import { act, createElement } from "react";+import { createRoot } from "react-dom/client";+import { beforeEach, describe, expect, test, vi } from "vitest";+import { Engine } from "@/types/proto-es/v1/common_pb";+import type { Database } from "@/types/proto-es/v1/database_service_pb";+import type { DataClassificationSetting_DataClassificationConfig } from "@/types/proto-es/v1/setting_service_pb";+import { Setting_SettingName } from "@/types/proto-es/v1/setting_service_pb";+import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++const mocks = vi.hoisted(() => ({+ useTranslation: vi.fn(() => ({+ t: (key: string) => key,+ })),+ useVueState: vi.fn(),+ useSettingV1Store: vi.fn(),+ useSubscriptionV1Store: vi.fn(),+ getOrFetchSettingByName: vi.fn(),+ getSettingByName: vi.fn(),+ getProjectClassification: vi.fn(),+ updateColumnCatalog: vi.fn(),+ updateTableCatalog: vi.fn(),+ getDatabaseProject: vi.fn(),+ getInstanceResource: vi.fn(),+ hasProjectPermissionV2: vi.fn(),+ hasWorkspacePermissionV2: vi.fn(),+}));++let TableDetailDialog: typeof import("./TableDetailDialog").TableDetailDialog;++vi.mock("react-i18next", () => ({+ useTranslation: mocks.useTranslation,+}));++vi.mock("@/react/hooks/useVueState", () => ({+ useVueState: mocks.useVueState,+}));++vi.mock("@/react/components/ui/dialog", () => ({+ Dialog: ({ open, children }: { open: boolean; children: ReactNode }) =>+ open ? <div data-testid="dialog-root">{children}</div> : null,+ DialogContent: ({ children }: { children: ReactNode }) => (+ <div>{children}</div>+ ),+ DialogTitle: ({ children }: { children: ReactNode }) => <h1>{children}</h1>,+}));++vi.mock("@/react/components/ui/input", () => ({+ Input: (props: InputHTMLAttributes<HTMLInputElement>) => <input {...props} />,+}));++vi.mock("@/react/components/ui/search-input", () => ({+ SearchInput: (props: InputHTMLAttributes<HTMLInputElement>) => (+ <input {...props} />+ ),+}));++vi.mock("@/react/components/ui/button", () => ({+ Button: ({ children, ...props }: ButtonHTMLAttributes<HTMLButtonElement>) => (+ <button type="button" {...props}>+ {children}+ </button>+ ),+}));++vi.mock("@/react/components/ui/table", () => ({+ Table: ({+ children,+ ...props+ }: React.TableHTMLAttributes<HTMLTableElement>) => (+ <table {...props}>{children}</table>+ ),+ TableBody: ({+ children,+ ...props+ }: React.HTMLAttributes<HTMLTableSectionElement>) => (+ <tbody {...props}>{children}</tbody>+ ),+ TableCell: ({+ children,+ ...props+ }: React.TdHTMLAttributes<HTMLTableCellElement>) => (+ <td {...props}>{children}</td>+ ),+ TableHead: ({+ children,+ ...props+ }: React.ThHTMLAttributes<HTMLTableCellElement>) => (+ <th {...props}>{children}</th>+ ),+ TableHeader: ({+ children,+ ...props+ }: React.HTMLAttributes<HTMLTableSectionElement>) => (+ <thead {...props}>{children}</thead>+ ),+ TableRow: ({+ children,+ ...props+ }: React.HTMLAttributes<HTMLTableRowElement>) => (+ <tr {...props}>{children}</tr>+ ),+}));++vi.mock("@/react/components/FeatureAttention", () => ({+ FeatureAttention: ({ feature }: { feature: PlanFeature }) => (+ <div>{PlanFeature[feature]}</div>+ ),+}));++vi.mock("@/store", () => ({+ useSettingV1Store: mocks.useSettingV1Store,+ useSubscriptionV1Store: mocks.useSubscriptionV1Store,+}));++vi.mock("@/utils", () => ({+ getDatabaseProject: mocks.getDatabaseProject,+ getInstanceResource: mocks.getInstanceResource,+ hasProjectPermissionV2: mocks.hasProjectPermissionV2,+ hasWorkspacePermissionV2: mocks.hasWorkspacePermissionV2,+}));++vi.mock("@/components/ColumnDataTable/utils", () => ({+ updateColumnCatalog: mocks.updateColumnCatalog,+ updateTableCatalog: mocks.updateTableCatalog,+}));++const renderIntoContainer = (element: ReturnType<typeof createElement>) => {+ const container = document.createElement("div");+ const root = createRoot(container);++ return {+ container,+ render: () => {+ act(() => {+ root.render(element);+ });+ },+ unmount: () =>+ act(() => {+ root.unmount();+ }),+ };+};++const flush = async () => {+ await act(async () => {+ await Promise.resolve();+ await Promise.resolve();+ });+};++const click = (element: HTMLElement) => {+ act(() => {+ element.dispatchEvent(+ new MouseEvent("click", { bubbles: true, cancelable: true })+ );+ });+};++const press = (element: HTMLElement) => {+ act(() => {+ element.dispatchEvent(+ new MouseEvent("mousedown", { bubbles: true, cancelable: true })+ );+ element.dispatchEvent(+ new MouseEvent("click", { bubbles: true, cancelable: true })+ );+ });+};++const makeDatabase = (): Database =>+ ({+ name: "instances/inst1/databases/db",+ project: "projects/proj1",+ instanceResource: {+ name: "instances/inst1",+ engine: Engine.POSTGRES,+ },+ }) as Database;++beforeEach(async () => {+ mocks.useTranslation.mockReset();+ mocks.useTranslation.mockReturnValue({+ t: (key: string) => key,+ });+ mocks.useVueState.mockReset();+ mocks.useVueState.mockImplementation((getter: () => unknown) => getter());+ mocks.getOrFetchSettingByName.mockReset();+ mocks.getSettingByName.mockReset();+ mocks.getProjectClassification.mockReset();+ mocks.getProjectClassification.mockReturnValue({+ id: "classification-config",+ levels: [+ { level: 1, title: "Level 1" },+ { level: 2, title: "Level 2" },+ ],+ classification: {+ PII: {+ id: "PII",+ title: "PII",+ level: 1,+ },+ CONFIDENTIAL: {+ id: "CONFIDENTIAL",+ title: "Confidential",+ level: 2,+ },+ },+ });+ mocks.getSettingByName.mockImplementation((name: Setting_SettingName) => {+ if (name !== Setting_SettingName.SEMANTIC_TYPES) {+ return undefined;+ }+ return {+ value: {+ value: {+ case: "semanticType",+ value: {+ types: [+ { id: "EMAIL", title: "Email" },+ { id: "PHONE", title: "Phone" },+ ],+ },+ },+ },+ };+ });+ mocks.useSettingV1Store.mockReset();+ mocks.useSettingV1Store.mockReturnValue({+ getOrFetchSettingByName: mocks.getOrFetchSettingByName,+ getSettingByName: mocks.getSettingByName,+ getProjectClassification: mocks.getProjectClassification,+ });+ mocks.useSubscriptionV1Store.mockReset();+ mocks.useSubscriptionV1Store.mockReturnValue({+ hasFeature: vi.fn(() => true),+ instanceMissingLicense: vi.fn(() => false),+ });+ mocks.updateColumnCatalog.mockReset();+ mocks.updateColumnCatalog.mockResolvedValue(undefined);+ mocks.updateTableCatalog.mockReset();+ mocks.updateTableCatalog.mockResolvedValue(undefined);+ mocks.getDatabaseProject.mockReset();+ mocks.getDatabaseProject.mockReturnValue({+ name: "projects/proj1",+ dataClassificationConfigId: "classification-config",+ });+ mocks.getInstanceResource.mockReset();+ mocks.getInstanceResource.mockReturnValue({+ name: "instances/inst1",+ engine: Engine.POSTGRES,+ });+ mocks.hasProjectPermissionV2.mockReset();+ mocks.hasProjectPermissionV2.mockReturnValue(true);+ mocks.hasWorkspacePermissionV2.mockReset();+ mocks.hasWorkspacePermissionV2.mockReturnValue(true);++ vi.resetModules();+ ({ TableDetailDialog } = await import("./TableDetailDialog"));+});++describe("TableDetailDialog", () => {+ test("restores the legacy table detail sections for columns and indexes", async () => {+ const classificationConfig = {+ id: "classification-config",+ levels: [{ level: 1, title: "L1" }],+ classification: {+ PII: {+ id: "PII",+ title: "PII",+ level: 1,+ },+ },+ } as unknown as DataClassificationSetting_DataClassificationConfig;++ const { container, render, unmount } = renderIntoContainer(+ createElement(TableDetailDialog, {+ open: true,+ onOpenChange: vi.fn(),+ table: {+ database: makeDatabase(),+ editable: true,+ name: '"public"."audit"',+ schema: "public",+ tableName: "audit",+ classification: "PII",+ classificationConfig,+ columns: [+ {+ name: "id",+ semanticType: "",+ classification: "",+ type: "integer",+ defaultValue: "nextval('public.audit_id_seq'::regclass)",+ nullable: false,+ collation: "",+ comment: "",+ },+ {+ name: "query",+ semanticType: "SQL",+ classification: "PII",+ type: "text",+ defaultValue: "No default",+ nullable: true,+ collation: "en_US",+ comment: "query text",+ },+ ],+ rowCount: "0",+ dataSize: "8 KB",+ indexSize: "32 KB",+ collation: "en_US",+ indexes: [+ {+ name: "audit_pkey",+ expressions: ["id"],+ unique: true,+ visible: true,+ comment: "",+ },+ ],+ showColumnClassification: true,+ showColumnCollation: true,+ showCollation: true,+ showIndexComment: true,+ showIndexes: true,+ showIndexSize: true,+ showIndexVisible: false,+ showSemanticType: true,+ },+ })+ );++ render();+ await flush();++ expect(container.textContent).toContain("database.classification.self");+ expect(container.textContent).toContain("PII");+ expect(container.textContent).toContain(+ "settings.sensitive-data.semantic-types.table.semantic-type"+ );+ expect(container.textContent).toContain("common.default");+ expect(container.textContent).toContain("database.nullable");+ expect(container.textContent).toContain("db.collation");+ expect(container.textContent).toContain("database.indexes");+ expect(container.textContent).toContain("audit_pkey");+ expect(container.textContent).toContain("database.expression");+ expect(container.textContent).toContain("database.unique");+ expect(container.textContent).toContain(+ "nextval('public.audit_id_seq'::regclass)"+ );+ expect(container.textContent).toContain("query text");++ unmount();+ });++ test("restores edit actions for table classification and column semantic metadata", async () => {+ const classificationConfig = {+ id: "classification-config",+ levels: [+ { level: 1, title: "Level 1" },+ { level: 2, title: "Level 2" },+ ],+ classification: {+ PII: {+ id: "PII",+ title: "PII",+ level: 1,+ },+ CONFIDENTIAL: {+ id: "CONFIDENTIAL",+ title: "Confidential",+ level: 2,+ },+ },+ } as unknown as DataClassificationSetting_DataClassificationConfig;++ const { container, render, unmount } = renderIntoContainer(+ createElement(TableDetailDialog as unknown as ElementType, {+ open: true,+ onOpenChange: vi.fn(),+ table: {+ database: makeDatabase(),+ editable: true,+ name: '"public"."audit"',+ schema: "public",+ tableName: "audit",+ classification: "PII",+ classificationConfig,+ columns: [+ {+ name: "query",+ semanticType: "EMAIL",+ classification: "PII",+ type: "text",+ defaultValue: "No default",+ nullable: true,+ },+ ],+ rowCount: "0",+ dataSize: "8 KB",+ indexSize: "32 KB",+ indexes: [],+ showColumnClassification: true,+ showIndexes: false,+ showSemanticType: true,+ },+ })+ );++ render();+ await flush();++ const tableEditButton = container.querySelector(+ '[data-testid="table-classification-edit"]'+ );+ const semanticTypeEditButton = container.querySelector(+ '[data-testid="column-semantic-type-query-edit"]'+ );+ const semanticTypeRemoveButton = container.querySelector(+ '[data-testid="column-semantic-type-query-remove"]'+ );+ const classificationEditButton = container.querySelector(+ '[data-testid="column-classification-query-edit"]'+ );+ const classificationRemoveButton = container.querySelector(+ '[data-testid="column-classification-query-remove"]'+ );++ expect(tableEditButton).not.toBeNull();+ expect(semanticTypeEditButton).not.toBeNull();+ expect(semanticTypeRemoveButton).not.toBeNull();+ expect(classificationEditButton).not.toBeNull();+ expect(classificationRemoveButton).not.toBeNull();++ press(tableEditButton as HTMLElement);+ await flush();+ click(+ container.querySelector(+ '[data-testid="classification-option-CONFIDENTIAL"]'+ ) as HTMLElement+ );+ await flush();++ press(semanticTypeEditButton as HTMLElement);+ await flush();+ click(+ container.querySelector(+ '[data-testid="semantic-type-option-PHONE"]'+ ) as HTMLElement+ );+ await flush();++ click(classificationRemoveButton as HTMLElement);+ await flush();++ expect(mocks.updateTableCatalog).toHaveBeenCalledWith(+ expect.objectContaining({+ database: "instances/inst1/databases/db",+ schema: "public",+ table: "audit",+ tableCatalog: { classification: "CONFIDENTIAL" },+ })+ );+ expect(mocks.updateColumnCatalog).toHaveBeenNthCalledWith(+ 1,+ expect.objectContaining({+ database: "instances/inst1/databases/db",+ schema: "public",+ table: "audit",+ column: "query",+ columnCatalog: { semanticType: "PHONE" },+ })+ );+ expect(mocks.updateColumnCatalog).toHaveBeenNthCalledWith(+ 2,+ expect.objectContaining({+ database: "instances/inst1/databases/db",+ schema: "public",+ table: "audit",+ column: "query",+ columnCatalog: { classification: "" },+ })+ );++ unmount();+ });++ test("loads classification config from settings when the dialog prop is unavailable", async () => {+ const { container, render, unmount } = renderIntoContainer(+ createElement(TableDetailDialog as unknown as ElementType, {+ open: true,+ onOpenChange: vi.fn(),+ table: {+ database: makeDatabase(),+ editable: true,+ name: '"public"."audit"',+ schema: "public",+ tableName: "audit",+ classification: "PII",+ columns: [+ {+ name: "query",+ semanticType: "EMAIL",+ classification: "PII",+ type: "text",+ defaultValue: "No default",+ nullable: true,+ },+ ],+ rowCount: "0",+ dataSize: "8 KB",+ indexSize: "32 KB",+ indexes: [],+ showColumnClassification: true,+ showIndexes: false,+ showSemanticType: true,+ },+ })+ );++ render();+ await flush();++ expect(+ container.querySelector('[data-testid="table-classification-edit"]')+ ).not.toBeNull();+ expect(+ container.querySelector(+ '[data-testid="column-classification-query-edit"]'+ )+ ).not.toBeNull();++ press(+ container.querySelector(+ '[data-testid="column-classification-query-edit"]'+ ) as HTMLElement+ );+ await flush();+ click(+ container.querySelector(+ '[data-testid="classification-option-PII"]'+ ) as HTMLElement+ );+ await flush();++ expect(mocks.getOrFetchSettingByName).toHaveBeenCalledWith(+ Setting_SettingName.DATA_CLASSIFICATION,+ true+ );++ unmount();+ });++ test("shows unknown classification ids instead of replacing them with a placeholder", async () => {+ const { container, render, unmount } = renderIntoContainer(+ createElement(TableDetailDialog as unknown as ElementType, {+ open: true,+ onOpenChange: vi.fn(),+ table: {+ database: makeDatabase(),+ editable: false,+ name: '"public"."audit"',+ schema: "public",+ tableName: "audit",+ classification: "LEGACY_PII",+ columns: [],+ rowCount: "0",+ dataSize: "8 KB",+ indexSize: "32 KB",+ indexes: [],+ showIndexes: false,+ },+ })+ );++ render();+ await flush();++ expect(container.textContent).toContain("LEGACY_PII");++ unmount();+ });++ test("restores partition and trigger sections in the React table detail dialog", async () => {+ const { container, render, unmount } = renderIntoContainer(+ createElement(TableDetailDialog as unknown as ElementType, {+ open: true,+ onOpenChange: vi.fn(),+ table: {+ database: makeDatabase(),+ editable: true,+ name: '"public"."audit"',+ schema: "public",+ tableName: "audit",+ columns: [],+ rowCount: "0",+ dataSize: "8 KB",+ indexSize: "32 KB",+ indexes: [],+ partitions: [+ {+ name: "audit_2026",+ type: "RANGE",+ expression: "FOR VALUES FROM ('2026-01-01') TO ('2027-01-01')",+ children: [],+ },+ ],+ triggers: [+ {+ name: "audit_before_insert",+ event: "INSERT",+ timing: "BEFORE",+ body: "EXECUTE FUNCTION audit_insert()",+ },+ ],+ showIndexes: false,+ showPartitionTables: true,+ showTriggers: true,+ },+ })+ );++ render();+ await flush();++ expect(container.textContent).toContain("database.partition-tables");+ expect(container.textContent).toContain("audit_2026");+ expect(container.textContent).toContain("db.triggers");+ expect(container.textContent).toContain("audit_before_insert");+ expect(container.textContent).toContain("EXECUTE FUNCTION audit_insert()");++ unmount();+ });+});diff --git a/frontend/src/react/pages/project/database-detail/overview/TableDetailDialog.tsx b/frontend/src/react/pages/project/database-detail/overview/TableDetailDialog.tsxindex a0f71aa647..6e0434fcea 100644--- a/frontend/src/react/pages/project/database-detail/overview/TableDetailDialog.tsx+++ b/frontend/src/react/pages/project/database-detail/overview/TableDetailDialog.tsx@@ -1,106 +1,1197 @@-import { NConfigProvider } from "naive-ui";-import { useEffect, useRef } from "react";-import { createApp, h, reactive } from "vue";-import { themeOverrides } from "@/../naive-ui.config";-import { updateTableCatalog } from "@/components/ColumnDataTable/utils";-import OverlayStackManager from "@/components/misc/OverlayStackManager.vue";-import TableDetailDrawer from "@/components/TableDetailDrawer.vue";-import i18n from "@/plugins/i18n";-import NaiveUI from "@/plugins/naive-ui";-import { router } from "@/router";-import { pinia } from "@/store";-import type { DataClassificationSetting_DataClassificationConfig } from "@/types/proto-es/v1/setting_service_pb";--export interface VueTableDetailDrawerProps {- show: boolean;- databaseName: string;- schemaName: string;- tableName: string;+import { Pencil, X } from "lucide-react";+import type { MouseEvent, ReactNode } from "react";+import { useEffect, useMemo, useState } from "react";+import { useTranslation } from "react-i18next";+import {+ updateColumnCatalog,+ updateTableCatalog,+} from "@/components/ColumnDataTable/utils";+import { FeatureAttention } from "@/react/components/FeatureAttention";+import { Button } from "@/react/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogTitle,+} from "@/react/components/ui/dialog";+import { Input } from "@/react/components/ui/input";+import { SearchInput } from "@/react/components/ui/search-input";+import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from "@/react/components/ui/table";+import { useVueState } from "@/react/hooks/useVueState";+import { useSettingV1Store, useSubscriptionV1Store } from "@/store";+import type { Database } from "@/types/proto-es/v1/database_service_pb";+import type {+ DataClassificationSetting_DataClassificationConfig,+ SemanticTypeSetting_SemanticType,+} from "@/types/proto-es/v1/setting_service_pb";+import { Setting_SettingName } from "@/types/proto-es/v1/setting_service_pb";+import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";+import {+ getDatabaseProject,+ getInstanceResource,+ hasWorkspacePermissionV2,+} from "@/utils";++interface TableColumnDetail {+ characterSet?: string;+ classification?: string;+ collation?: string;+ comment?: string;+ defaultValue: string;+ name: string;+ nullable: boolean;+ semanticType?: string;+ type: string;+}++interface TablePartitionDetail {+ children: TablePartitionDetail[];+ expression: string;+ name: string;+ type: string;+}++interface TriggerDetail {+ body: string;+ event: string;+ name: string;+ sqlMode?: string;+ timing: string;+}++export interface TableDetailDialogData {+ classification?: string;classificationConfig?: DataClassificationSetting_DataClassificationConfig;- onDismiss: () => void;+ columns: TableColumnDetail[];+ collation?: string;+ dataSize: string;+ database?: Database;+ editable?: boolean;+ engine?: string;+ indexes: {+ comment?: string;+ expressions: string[];+ name: string;+ unique: boolean;+ visible?: boolean;+ }[];+ indexSize: string;+ name: string;+ rowCount: string;+ schema?: string;+ showCharacterSet?: boolean;+ showColumnClassification?: boolean;+ showColumnCollation?: boolean;+ showColumns?: boolean;+ showCollation?: boolean;+ showEngine?: boolean;+ showIndexComment?: boolean;+ showIndexes?: boolean;+ showIndexSize?: boolean;+ showIndexVisible?: boolean;+ showPartitionTables?: boolean;+ showSemanticType?: boolean;+ showTriggers?: boolean;+ tableName?: string;+ partitions?: TablePartitionDetail[];+ triggers?: TriggerDetail[];}-export function VueTableDetailDrawerMount({- show,- databaseName,- schemaName,- tableName,- classificationConfig,- onDismiss,-}: VueTableDetailDrawerProps) {- const containerRef = useRef<HTMLDivElement>(null);- const bridgeStateRef = useRef(- reactive({- show,- databaseName,- schemaName,- tableName,- classificationConfig,- onDismiss,+interface ClassificationTreeNode {+ children: ClassificationTreeNode[];+ id: string;+ isLeaf: boolean;+ level?: number;+ title: string;+}++const bgColorList = [+ "bg-green-200",+ "bg-yellow-200",+ "bg-orange-300",+ "bg-amber-500",+ "bg-red-500",+];++function toTestId(value: string) {+ return value.replace(/[^a-zA-Z0-9_-]/g, "-");+}++function getClassificationEntry(+ classification: string | undefined,+ classificationConfig:+ | DataClassificationSetting_DataClassificationConfig+ | undefined+) {+ if (!classification || !classificationConfig) {+ return undefined;+ }++ return classificationConfig.classification[classification];+}++function sortClassification(item1: { id: string }, item2: { id: string }) {+ const id1s = item1.id.split("-");+ const id2s = item2.id.split("-");++ if (id1s.length !== id2s.length) {+ return id1s.length - id2s.length;+ }++ for (let i = 0; i < id1s.length; i++) {+ if (id1s[i] === id2s[i]) {+ continue;+ }++ const id1 = Number(id1s[i]);+ const id2 = Number(id2s[i]);+ if (Number.isNaN(id1) || Number.isNaN(id2)) {+ return id1s[i].localeCompare(id2s[i]);+ }+ return id1 - id2;+ }++ return 0;+}++function buildClassificationTree(+ classificationConfig: DataClassificationSetting_DataClassificationConfig+) {+ const classifications = Object.values(+ classificationConfig.classification+ ).sort(sortClassification);+ const nodeMap = new Map<string, ClassificationTreeNode>();+ const roots: ClassificationTreeNode[] = [];++ for (const classification of classifications) {+ const node: ClassificationTreeNode = {+ id: classification.id,+ title: classification.title,+ level: classification.level,+ children: [],+ isLeaf: true,+ };+ nodeMap.set(classification.id, node);+ }++ for (const classification of classifications) {+ const node = nodeMap.get(classification.id);+ if (!node) continue;++ const parts = classification.id.split("-");+ if (parts.length === 1) {+ roots.push(node);+ continue;+ }++ const parentId = parts.slice(0, -1).join("-");+ const parent = nodeMap.get(parentId);+ if (!parent) {+ roots.push(node);+ continue;+ }++ parent.children.push(node);+ parent.isLeaf = false;+ }++ const sortNodes = (nodes: ClassificationTreeNode[]) => {+ nodes.sort(sortClassification);+ for (const node of nodes) {+ sortNodes(node.children);+ node.isLeaf = node.children.length === 0;+ }+ };++ sortNodes(roots);+ return roots;+}++function filterClassificationTree(+ nodes: ClassificationTreeNode[],+ searchText: string+): ClassificationTreeNode[] {+ const normalizedSearch = searchText.trim().toLowerCase();+ if (!normalizedSearch) {+ return nodes;+ }++ return nodes+ .map((node) => {+ const children = filterClassificationTree(+ node.children,+ normalizedSearch+ );+ const label = `${node.id} ${node.title}`.toLowerCase();+ if (label.includes(normalizedSearch) || children.length > 0) {+ return {+ ...node,+ children,+ isLeaf: children.length === 0 && node.children.length === 0,+ };+ }+ return undefined;})+ .filter((node): node is ClassificationTreeNode => node !== undefined);+}++function flattenClassificationTree(+ nodes: ClassificationTreeNode[],+ depth = 0+): Array<{ depth: number; node: ClassificationTreeNode }> {+ return nodes.flatMap((node) => [+ { node, depth },+ ...flattenClassificationTree(node.children, depth + 1),+ ]);+}++function getSemanticTypeTitle(+ semanticTypeId: string | undefined,+ semanticTypeList: SemanticTypeSetting_SemanticType[]+) {+ if (!semanticTypeId) {+ return "";+ }++ if (!hasWorkspacePermissionV2("bb.settings.get")) {+ return semanticTypeId;+ }++ return (+ semanticTypeList.find((semanticType) => semanticType.id === semanticTypeId)+ ?.title || semanticTypeId);+}- useEffect(() => {- const state = bridgeStateRef.current;- state.show = show;- state.databaseName = databaseName;- state.schemaName = schemaName;- state.tableName = tableName;- state.classificationConfig = classificationConfig;- state.onDismiss = onDismiss;- }, [- show,- databaseName,- schemaName,- tableName,- classificationConfig,- onDismiss,+function MiniActionButton({+ ariaLabel,+ children,+ className,+ dataTestId,+ disabled,+ onClick,+}: {+ ariaLabel: string;+ children: ReactNode;+ className?: string;+ dataTestId?: string;+ disabled?: boolean;+ onClick: (event: MouseEvent<HTMLButtonElement>) => void;+}) {+ return (+ <button+ type="button"+ aria-label={ariaLabel}+ data-testid={dataTestId}+ className={`inline-flex h-5 w-5 items-center justify-center rounded-xs text-control transition-colors hover:bg-control-bg hover:text-main disabled:cursor-not-allowed disabled:opacity-50 [&_svg]:pointer-events-none ${className ?? ""}`}+ disabled={disabled}+ onKeyDown={(event) => event.stopPropagation()}+ onMouseDown={(event) => event.stopPropagation()}+ onPointerDown={(event) => event.stopPropagation()}+ onClick={onClick}+ >+ {children}+ </button>+ );+}++function ClassificationLevelBadge({+ classification,+ classificationConfig,+ placeholder = "N/A",+ showText = true,+}: {+ classification?: string;+ classificationConfig?: DataClassificationSetting_DataClassificationConfig;+ placeholder?: string;+ showText?: boolean;+}) {+ const classificationEntry = getClassificationEntry(+ classification,+ classificationConfig+ );+ const level = (classificationConfig?.levels ?? []).find(+ (level) => level.level === classificationEntry?.level+ );+ const levelColor =+ bgColorList[(classificationEntry?.level ?? 0) - 1] ?? "bg-gray-200";++ return (+ <span className="flex min-w-0 items-center gap-x-1">+ {showText && (+ <span className="min-w-0 truncate">+ {classificationEntry?.title || classification || (+ <span className="text-control-placeholder italic">+ {placeholder}+ </span>+ )}+ </span>+ )}+ {level && (+ <span className={`rounded px-1 py-0.5 text-xs ${levelColor}`}>+ {level.title}+ </span>+ )}+ </span>+ );+}++function DetailSection({+ children,+ title,+}: {+ children: ReactNode;+ title: string;+}) {+ return (+ <div className="mt-6 flex flex-col gap-y-4">+ <div className="text-sm font-medium text-control-light">{title}</div>+ {children}+ </div>+ );+}++function flattenPartitionRows(+ partitions: TablePartitionDetail[],+ depth = 0+): Array<{ depth: number; partition: TablePartitionDetail }> {+ return partitions.flatMap((partition) => [+ { depth, partition },+ ...flattenPartitionRows(partition.children, depth + 1),]);+}++function ClassificationPickerDialog({+ classificationConfig,+ onOpenChange,+ onSelect,+ open,+}: {+ classificationConfig: DataClassificationSetting_DataClassificationConfig;+ onOpenChange: (open: boolean) => void;+ onSelect: (classificationId: string) => void;+ open: boolean;+}) {+ const { t } = useTranslation();+ const [searchText, setSearchText] = useState("");++ useEffect(() => {+ if (open) {+ setSearchText("");+ }+ }, [open]);++ const rows = useMemo(() => {+ const tree = buildClassificationTree(classificationConfig);+ return flattenClassificationTree(+ filterClassificationTree(tree, searchText)+ );+ }, [classificationConfig, searchText]);++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="max-w-2xl p-6">+ <DialogTitle>{t("schema-template.classification.select")}</DialogTitle>+ <div className="mt-4 flex flex-col gap-y-4">+ <SearchInput+ placeholder={t("schema-template.classification.search")}+ value={searchText}+ onChange={(event) => setSearchText(event.target.value)}+ />+ <div className="max-h-[28rem] overflow-y-auto rounded-lg border border-block-border">+ {rows.length === 0 ? (+ <div className="px-4 py-6 text-sm text-control-light">+ {t("common.no-data")}+ </div>+ ) : (+ <div className="divide-y divide-block-border">+ {rows.map(({ node, depth }) => {+ const content = (+ <>+ <span className="truncate">+ {node.id} {node.title}+ </span>+ {node.level !== undefined && (+ <ClassificationLevelBadge+ classification={node.id}+ classificationConfig={classificationConfig}+ showText={false}+ />+ )}+ </>+ );++ if (!node.isLeaf) {+ return (+ <div+ key={node.id}+ className="flex items-center gap-x-2 px-4 py-2 text-sm font-medium text-main"+ style={{ paddingLeft: `${depth * 16 + 16}px` }}+ >+ {content}+ </div>+ );+ }++ return (+ <button+ key={node.id}+ type="button"+ data-testid={`classification-option-${toTestId(node.id)}`}+ className="flex w-full items-center justify-between gap-x-2 px-4 py-2 text-left text-sm text-control hover:bg-control-bg"+ style={{ paddingLeft: `${depth * 16 + 16}px` }}+ onClick={() => {+ onSelect(node.id);+ onOpenChange(false);+ }}+ >+ {content}+ </button>+ );+ })}+ </div>+ )}+ </div>+ <div className="flex justify-end gap-x-2">+ <Button variant="outline" onClick={() => onOpenChange(false)}>+ {t("common.cancel")}+ </Button>+ </div>+ </div>+ </DialogContent>+ </Dialog>+ );+}++function SemanticTypePickerDialog({+ onOpenChange,+ onSelect,+ open,+ semanticTypeList,+}: {+ onOpenChange: (open: boolean) => void;+ onSelect: (semanticTypeId: string) => void;+ open: boolean;+ semanticTypeList: SemanticTypeSetting_SemanticType[];+}) {+ const { t } = useTranslation();+ const [searchText, setSearchText] = useState("");++ useEffect(() => {+ if (open) {+ setSearchText("");+ }+ }, [open]);++ const filteredSemanticTypeList = useMemo(() => {+ const normalizedSearch = searchText.trim().toLowerCase();+ if (!normalizedSearch) {+ return semanticTypeList;+ }++ return semanticTypeList.filter((semanticType) => {+ return (+ semanticType.id.toLowerCase().includes(normalizedSearch) ||+ semanticType.title.toLowerCase().includes(normalizedSearch) ||+ (semanticType.description?.toLowerCase().includes(normalizedSearch) ??+ false)+ );+ });+ }, [searchText, semanticTypeList]);++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="max-w-3xl p-6">+ <DialogTitle>+ {t("settings.sensitive-data.semantic-types.self")}+ </DialogTitle>+ <div className="mt-4 flex flex-col gap-y-4">+ <SearchInput+ placeholder={t("common.filter-by-name")}+ value={searchText}+ onChange={(event) => setSearchText(event.target.value)}+ />+ <div className="max-h-[28rem] overflow-y-auto rounded-lg border border-block-border">+ {filteredSemanticTypeList.length === 0 ? (+ <div className="px-4 py-6 text-sm text-control-light">+ {t("common.no-data")}+ </div>+ ) : (+ <div className="divide-y divide-block-border">+ {filteredSemanticTypeList.map((semanticType) => (+ <button+ key={semanticType.id}+ type="button"+ data-testid={`semantic-type-option-${toTestId(semanticType.id)}`}+ className="flex w-full flex-col items-start gap-y-1 px-4 py-3 text-left hover:bg-control-bg"+ onClick={() => {+ onSelect(semanticType.id);+ onOpenChange(false);+ }}+ >+ <span className="text-sm font-medium text-main">+ {semanticType.title}+ </span>+ <span className="text-xs text-control">+ {semanticType.id}+ </span>+ {semanticType.description && (+ <span className="text-xs text-control-light">+ {semanticType.description}+ </span>+ )}+ </button>+ ))}+ </div>+ )}+ </div>+ <div className="flex justify-end gap-x-2">+ <Button variant="outline" onClick={() => onOpenChange(false)}>+ {t("common.cancel")}+ </Button>+ </div>+ </div>+ </DialogContent>+ </Dialog>+ );+}++export function EditableClassificationCell({+ classification,+ classificationConfig,+ onApply,+ readonly = false,+ testIdPrefix,+}: {+ classification?: string;+ classificationConfig?: DataClassificationSetting_DataClassificationConfig;+ onApply: (classificationId: string) => Promise<void> | void;+ readonly?: boolean;+ testIdPrefix: string;+}) {+ const { t } = useTranslation();+ const [showPicker, setShowPicker] = useState(false);++ return (+ <>+ <div className="flex min-w-0 items-center gap-x-1">+ <ClassificationLevelBadge+ classification={classification}+ classificationConfig={classificationConfig}+ />+ {!readonly && classification && (+ <MiniActionButton+ ariaLabel={t("common.remove")}+ dataTestId={`${testIdPrefix}-remove`}+ onClick={(event) => {+ event.stopPropagation();+ void onApply("");+ }}+ >+ <X className="h-3 w-3" />+ </MiniActionButton>+ )}+ {!readonly && classificationConfig && (+ <MiniActionButton+ ariaLabel={t("common.edit")}+ dataTestId={`${testIdPrefix}-edit`}+ onClick={(event) => {+ event.stopPropagation();+ setShowPicker(true);+ }}+ >+ <Pencil className="h-3 w-3" />+ </MiniActionButton>+ )}+ </div>+ {classificationConfig && (+ <ClassificationPickerDialog+ classificationConfig={classificationConfig}+ open={showPicker}+ onOpenChange={setShowPicker}+ onSelect={(classificationId) => {+ void onApply(classificationId);+ }}+ />+ )}+ </>+ );+}++function EditableSemanticTypeCell({+ database,+ onApply,+ readonly = false,+ semanticTypeId,+ testIdPrefix,+}: {+ database: Database;+ onApply: (semanticTypeId: string) => Promise<void> | void;+ readonly?: boolean;+ semanticTypeId?: string;+ testIdPrefix: string;+}) {+ const { t } = useTranslation();+ const settingStore = useSettingV1Store();+ const subscriptionStore = useSubscriptionV1Store();+ const [showFeatureDialog, setShowFeatureDialog] = useState(false);+ const [showPicker, setShowPicker] = useState(false);++ const semanticTypeList = useVueState(() => {+ const setting = settingStore.getSettingByName(+ Setting_SettingName.SEMANTIC_TYPES+ );+ return setting?.value?.value.case === "semanticType"+ ? ((setting.value.value.value.types ??+ []) as SemanticTypeSetting_SemanticType[])+ : [];+ });+ const hasSensitiveDataFeature = useVueState(() =>+ subscriptionStore.hasFeature(PlanFeature.FEATURE_DATA_MASKING)+ );+ const instanceMissingLicense = useVueState(() =>+ subscriptionStore.instanceMissingLicense(+ PlanFeature.FEATURE_DATA_MASKING,+ getInstanceResource(database)+ )+ );useEffect(() => {- if (!containerRef.current) {+ void settingStore.getOrFetchSettingByName(+ Setting_SettingName.SEMANTIC_TYPES,+ true+ );+ }, [settingStore]);++ const semanticTypeTitle = getSemanticTypeTitle(+ semanticTypeId,+ semanticTypeList+ );++ return (+ <>+ <div className="flex min-w-0 items-center gap-x-1">+ <span className="min-w-0 truncate">+ {semanticTypeTitle || (+ <span className="text-control-placeholder italic">N/A</span>+ )}+ </span>+ {!readonly && semanticTypeId && (+ <MiniActionButton+ ariaLabel={t("common.remove")}+ dataTestId={`${testIdPrefix}-remove`}+ onClick={(event) => {+ event.stopPropagation();+ void onApply("");+ }}+ >+ <X className="h-3 w-3" />+ </MiniActionButton>+ )}+ {!readonly && (+ <MiniActionButton+ ariaLabel={t("common.edit")}+ dataTestId={`${testIdPrefix}-edit`}+ onClick={(event) => {+ event.stopPropagation();+ if (!hasSensitiveDataFeature || instanceMissingLicense) {+ setShowFeatureDialog(true);+ return;+ }+ setShowPicker(true);+ }}+ >+ <Pencil className="h-3 w-3" />+ </MiniActionButton>+ )}+ </div>++ <SemanticTypePickerDialog+ open={showPicker}+ semanticTypeList={semanticTypeList}+ onOpenChange={setShowPicker}+ onSelect={(nextSemanticTypeId) => {+ void onApply(nextSemanticTypeId);+ }}+ />++ <Dialog open={showFeatureDialog} onOpenChange={setShowFeatureDialog}>+ <DialogContent className="p-6">+ <DialogTitle>{t("common.warning")}</DialogTitle>+ <FeatureAttention+ feature={PlanFeature.FEATURE_DATA_MASKING}+ instance={getInstanceResource(database)}+ />+ <div className="mt-4 flex justify-end gap-x-2">+ <Button+ variant="outline"+ onClick={() => setShowFeatureDialog(false)}+ >+ {t("common.cancel")}+ </Button>+ </div>+ </DialogContent>+ </Dialog>+ </>+ );+}++export function TableDetailDialog({+ table,+ open,+ onOpenChange,+}: {+ table?: TableDetailDialogData;+ open: boolean;+ onOpenChange: (open: boolean) => void;+}) {+ const { t } = useTranslation();+ const settingStore = useSettingV1Store();+ const [columnSearchKeyword, setColumnSearchKeyword] = useState("");++ const filteredColumns = useMemo(() => {+ if (!table) {+ return [];+ }++ const keyword = columnSearchKeyword.trim().toLowerCase();+ if (!keyword) {+ return table.columns;+ }++ return table.columns.filter((column) =>+ column.name.toLowerCase().includes(keyword)+ );+ }, [columnSearchKeyword, table?.columns]);++ useEffect(() => {+ setColumnSearchKeyword("");+ }, [table?.name]);++ const classificationConfig = useVueState(() => {+ if (table?.classificationConfig) {+ return table.classificationConfig;+ }+ if (!table?.database) {+ return undefined;+ }+ return settingStore.getProjectClassification(+ getDatabaseProject(table.database).dataClassificationConfigId ?? ""+ );+ });++ useEffect(() => {+ void settingStore.getOrFetchSettingByName(+ Setting_SettingName.DATA_CLASSIFICATION,+ true+ );+ }, [settingStore]);++ if (!table) {+ return null;+ }++ const showCharacterSetColumn = table.showCharacterSet;+ const showColumnClassification = table.showColumnClassification;+ const showColumnCollation = table.showColumnCollation;+ const showColumns = table.showColumns ?? true;+ const showIndexCommentColumn = table.showIndexComment;+ const showIndexVisibleColumn = table.showIndexVisible;+ const showPartitionTables =+ table.showPartitionTables && (table.partitions?.length ?? 0) > 0;+ const showSemanticTypeColumn = table.showSemanticType;+ const showSummaryCollation = table.showCollation;+ const showTriggers = table.showTriggers && (table.triggers?.length ?? 0) > 0;+ const readonly = !table.editable;+ const partitionRows = flattenPartitionRows(table.partitions ?? []);++ const handleTableClassificationApply = async (classificationId: string) => {+ if (!table.database || !table.tableName) {return;}- const bridgeState = bridgeStateRef.current;-- const app = createApp({- render() {- return h(- NConfigProvider as never,- { themeOverrides: themeOverrides.value },- {- default: () =>- h(OverlayStackManager as never, null, {- default: () =>- h(TableDetailDrawer as never, {- show: bridgeState.show,- databaseName: bridgeState.databaseName,- schemaName: bridgeState.schemaName,- tableName: bridgeState.tableName,- classificationConfig: bridgeState.classificationConfig,- onDismiss: bridgeState.onDismiss,- onApplyClassification: (table: string, id: string) => {- void updateTableCatalog({- database: bridgeState.databaseName,- schema: bridgeState.schemaName,- table,- tableCatalog: { classification: id },- });- },- }),- }),- }- );+ await updateTableCatalog({+ database: table.database.name,+ schema: table.schema ?? "",+ table: table.tableName,+ tableCatalog: {+ classification: classificationId,},});- app.use(router).use(pinia).use(i18n).use(NaiveUI);- app.mount(containerRef.current);+ };- return () => {- app.unmount();- };- }, [databaseName]);+ const handleColumnClassificationApply = async (+ columnName: string,+ classificationId: string+ ) => {+ if (!table.database || !table.tableName) {+ return;+ }++ await updateColumnCatalog({+ database: table.database.name,+ schema: table.schema ?? "",+ table: table.tableName,+ column: columnName,+ columnCatalog: {+ classification: classificationId,+ },+ notification: !classificationId+ ? t("common.removed")+ : t("common.update"),+ });+ };++ const handleColumnSemanticTypeApply = async (+ columnName: string,+ semanticTypeId: string+ ) => {+ if (!table.database || !table.tableName) {+ return;+ }- return <div ref={containerRef} />;+ await updateColumnCatalog({+ database: table.database.name,+ schema: table.schema ?? "",+ table: table.tableName,+ column: columnName,+ columnCatalog: {+ semanticType: semanticTypeId,+ },+ notification: !semanticTypeId ? t("common.removed") : t("common.update"),+ });+ };++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="max-w-6xl p-6">+ <DialogTitle>{table.name}</DialogTitle>+ <div className="mt-4 grid gap-4 sm:grid-cols-3">+ <div>+ <div className="text-sm font-medium text-control-light">+ {t("database.classification.self")}+ </div>+ <div className="mt-1 text-sm text-main">+ <EditableClassificationCell+ classification={table.classification}+ classificationConfig={classificationConfig}+ readonly={readonly}+ testIdPrefix="table-classification"+ onApply={handleTableClassificationApply}+ />+ </div>+ </div>+ {table.showEngine && (+ <div>+ <div className="text-sm font-medium text-control-light">+ {t("database.engine")}+ </div>+ <div className="mt-1 text-sm text-main">+ {table.engine || "-"}+ </div>+ </div>+ )}+ <div>+ <div className="text-sm font-medium text-control-light">+ {t("database.row-count-estimate")}+ </div>+ <div className="mt-1 text-sm text-main">{table.rowCount}</div>+ </div>+ <div>+ <div className="text-sm font-medium text-control-light">+ {t("database.data-size")}+ </div>+ <div className="mt-1 text-sm text-main">{table.dataSize}</div>+ </div>+ {table.showIndexSize && (+ <div>+ <div className="text-sm font-medium text-control-light">+ {t("database.index-size")}+ </div>+ <div className="mt-1 text-sm text-main">{table.indexSize}</div>+ </div>+ )}+ {showSummaryCollation && (+ <div>+ <div className="text-sm font-medium text-control-light">+ {t("db.collation")}+ </div>+ <div className="mt-1 text-sm text-main">+ {table.collation || "-"}+ </div>+ </div>+ )}+ </div>++ {showPartitionTables && (+ <DetailSection title={t("database.partition-tables")}>+ <div className="rounded-lg border border-block-border">+ <Table className="min-w-full">+ <TableHeader className="bg-control-bg">+ <TableRow className="hover:bg-control-bg">+ <TableHead>{t("common.name")}</TableHead>+ <TableHead>{t("common.type")}</TableHead>+ <TableHead>{t("database.expression")}</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody className="bg-white">+ {partitionRows.map(({ depth, partition }) => (+ <TableRow key={`${partition.name}-${depth}`}>+ <TableCell className="text-main">+ <span style={{ paddingLeft: `${depth * 16}px` }}>+ {partition.name}+ </span>+ </TableCell>+ <TableCell>{partition.type}</TableCell>+ <TableCell>{partition.expression || "-"}</TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ </div>+ </DetailSection>+ )}++ {showColumns && (+ <DetailSection title={t("database.columns")}>+ <div className="flex items-center justify-between gap-3">+ <Input+ className="w-full max-w-sm"+ placeholder={t("common.filter-by-name")}+ value={columnSearchKeyword}+ onChange={(event) => setColumnSearchKeyword(event.target.value)}+ />+ </div>+ <div className="rounded-lg border border-block-border">+ <table className="min-w-full divide-y divide-block-border text-sm">+ <thead className="bg-control-bg">+ <tr className="text-left text-sm text-control-light">+ <th className="px-4 py-2 font-medium">+ {t("common.name")}+ </th>+ {showSemanticTypeColumn && (+ <th className="px-4 py-2 font-medium">+ {t(+ "settings.sensitive-data.semantic-types.table.semantic-type"+ )}+ </th>+ )}+ {showColumnClassification && (+ <th className="px-4 py-2 font-medium">+ {t("database.classification.self")}+ </th>+ )}+ <th className="px-4 py-2 font-medium">+ {t("common.type")}+ </th>+ <th className="px-4 py-2 font-medium">+ {t("common.default")}+ </th>+ <th className="px-4 py-2 font-medium">+ {t("database.nullable")}+ </th>+ {showCharacterSetColumn && (+ <th className="px-4 py-2 font-medium">+ {t("db.character-set")}+ </th>+ )}+ {showColumnCollation && (+ <th className="px-4 py-2 font-medium">+ {t("db.collation")}+ </th>+ )}+ <th className="px-4 py-2 font-medium">+ {t("common.comment")}+ </th>+ </tr>+ </thead>+ <tbody className="divide-y divide-block-border bg-white">+ {filteredColumns.map((column) => (+ <tr key={column.name}>+ <td className="px-4 py-3 text-sm text-main">+ {column.name}+ </td>+ {showSemanticTypeColumn && (+ <td className="px-4 py-3 text-sm text-control">+ {table.database ? (+ <EditableSemanticTypeCell+ database={table.database}+ readonly={readonly}+ semanticTypeId={column.semanticType}+ testIdPrefix={`column-semantic-type-${toTestId(column.name)}`}+ onApply={(semanticTypeId) =>+ handleColumnSemanticTypeApply(+ column.name,+ semanticTypeId+ )+ }+ />+ ) : (+ column.semanticType || "-"+ )}+ </td>+ )}+ {showColumnClassification && (+ <td className="px-4 py-3 text-sm text-control">+ <EditableClassificationCell+ classification={column.classification}+ classificationConfig={classificationConfig}+ readonly={readonly}+ testIdPrefix={`column-classification-${toTestId(column.name)}`}+ onApply={(classificationId) =>+ handleColumnClassificationApply(+ column.name,+ classificationId+ )+ }+ />+ </td>+ )}+ <td className="px-4 py-3 text-sm text-control">+ {column.type}+ </td>+ <td className="px-4 py-3 text-sm text-control">+ {column.defaultValue}+ </td>+ <td className="px-4 py-3 text-sm text-control">+ <input+ checked={column.nullable}+ disabled+ readOnly+ type="checkbox"+ />+ </td>+ {showCharacterSetColumn && (+ <td className="px-4 py-3 text-sm text-control">+ {column.characterSet || "-"}+ </td>+ )}+ {showColumnCollation && (+ <td className="px-4 py-3 text-sm text-control">+ {column.collation || "-"}+ </td>+ )}+ <td className="px-4 py-3 text-sm text-control">+ {column.comment || "-"}+ </td>+ </tr>+ ))}+ {filteredColumns.length === 0 && (+ <tr>+ <td+ className="px-4 py-6 text-center text-sm text-control-light"+ colSpan={+ 5 ++ (showSemanticTypeColumn ? 1 : 0) ++ (showColumnClassification ? 1 : 0) ++ (showCharacterSetColumn ? 1 : 0) ++ (showColumnCollation ? 1 : 0)+ }+ >+ {t("common.no-data")}+ </td>+ </tr>+ )}+ </tbody>+ </table>+ </div>+ </DetailSection>+ )}++ {table.showIndexes && table.indexes.length > 0 && (+ <DetailSection title={t("database.indexes")}>+ {table.indexes.map((index) => (+ <div+ key={index.name}+ className="rounded-lg border border-block-border"+ >+ <div className="border-b border-block-border px-4 py-3 text-base font-medium text-main">+ {index.name}+ </div>+ <table className="min-w-full divide-y divide-block-border text-sm">+ <thead className="bg-control-bg">+ <tr className="text-left text-sm text-control-light">+ <th className="px-4 py-2 font-medium">+ {t("database.expression")}+ </th>+ <th className="px-4 py-2 font-medium">+ {t("database.unique")}+ </th>+ {showIndexVisibleColumn && (+ <th className="px-4 py-2 font-medium">+ {t("database.visible")}+ </th>+ )}+ {showIndexCommentColumn && (+ <th className="px-4 py-2 font-medium">+ {t("common.comment")}+ </th>+ )}+ </tr>+ </thead>+ <tbody className="divide-y divide-block-border bg-white">+ <tr>+ <td className="px-4 py-3 text-sm text-control">+ {index.expressions.join(", ") || "-"}+ </td>+ <td className="px-4 py-3 text-sm text-control">+ {String(index.unique)}+ </td>+ {showIndexVisibleColumn && (+ <td className="px-4 py-3 text-sm text-control">+ {String(index.visible)}+ </td>+ )}+ {showIndexCommentColumn && (+ <td className="px-4 py-3 text-sm text-control">+ {index.comment || "-"}+ </td>+ )}+ </tr>+ </tbody>+ </table>+ </div>+ ))}+ </DetailSection>+ )}++ {showTriggers && (+ <DetailSection title={t("db.triggers")}>+ <div className="rounded-lg border border-block-border">+ <Table className="min-w-full">+ <TableHeader className="bg-control-bg">+ <TableRow className="hover:bg-control-bg">+ <TableHead>{t("common.name")}</TableHead>+ <TableHead>{t("db.trigger.event")}</TableHead>+ <TableHead>{t("db.trigger.timing")}</TableHead>+ <TableHead>{t("db.trigger.body")}</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody className="bg-white">+ {table.triggers?.map((trigger) => (+ <TableRow key={trigger.name}>+ <TableCell className="text-main">+ {trigger.name}+ </TableCell>+ <TableCell>{trigger.event || "-"}</TableCell>+ <TableCell>{trigger.timing || "-"}</TableCell>+ <TableCell className="max-w-xl whitespace-pre-wrap break-all">+ {trigger.body || trigger.sqlMode || "-"}+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ </div>+ </DetailSection>+ )}+ </DialogContent>+ </Dialog>+ );}diff --git a/frontend/src/react/pages/project/database-detail/overview/TableMetadataTable.test.tsx b/frontend/src/react/pages/project/database-detail/overview/TableMetadataTable.test.tsxnew file mode 100644index 0000000000..c7cbf5626a--- /dev/null+++ b/frontend/src/react/pages/project/database-detail/overview/TableMetadataTable.test.tsx@@ -0,0 +1,449 @@+import type {+ ButtonHTMLAttributes,+ InputHTMLAttributes,+ ReactNode,+} from "react";+import { act, createElement } from "react";+import { createRoot } from "react-dom/client";+import { beforeEach, describe, expect, test, vi } from "vitest";+import { Engine } from "@/types/proto-es/v1/common_pb";+import type { Database } from "@/types/proto-es/v1/database_service_pb";+import { Setting_SettingName } from "@/types/proto-es/v1/setting_service_pb";+import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++const mocks = vi.hoisted(() => ({+ useTranslation: vi.fn(() => ({+ t: (key: string) => key,+ })),+ useVueState: vi.fn(),+ useDatabaseCatalog: vi.fn(),+ getTableCatalog: vi.fn(),+ featureToRef: vi.fn(() => ({ value: true })),+ useSettingV1Store: vi.fn(),+ updateTableCatalog: vi.fn(),+ getDatabaseEngine: vi.fn(() => Engine.POSTGRES),+ getDatabaseProject: vi.fn(() => ({+ name: "projects/proj1",+ dataClassificationConfigId: "classification-config",+ })),+ bytesToString: vi.fn((value: number) => `${value} B`),+ getInstanceResource: vi.fn(() => ({+ name: "instances/inst1",+ engine: Engine.POSTGRES,+ })),+ hasProjectPermissionV2: vi.fn(() => true),+ hasSchemaProperty: vi.fn(() => true),+ hasWorkspacePermissionV2: vi.fn(() => true),+ getOrFetchSettingByName: vi.fn(),+ getSettingByName: vi.fn(),+ getProjectClassification: vi.fn(),+}));++let TableMetadataTable: typeof import("./TableMetadataTable").TableMetadataTable;++vi.mock("react-i18next", () => ({+ useTranslation: mocks.useTranslation,+}));++vi.mock("@/react/hooks/useVueState", () => ({+ useVueState: mocks.useVueState,+}));++vi.mock("@/store", () => ({+ useDatabaseCatalog: mocks.useDatabaseCatalog,+ getTableCatalog: mocks.getTableCatalog,+ featureToRef: mocks.featureToRef,+ useSettingV1Store: mocks.useSettingV1Store,+}));++vi.mock("@/utils", () => ({+ bytesToString: mocks.bytesToString,+ getDatabaseEngine: mocks.getDatabaseEngine,+ getDatabaseProject: mocks.getDatabaseProject,+ getInstanceResource: mocks.getInstanceResource,+ hasProjectPermissionV2: mocks.hasProjectPermissionV2,+ hasSchemaProperty: mocks.hasSchemaProperty,+ hasWorkspacePermissionV2: mocks.hasWorkspacePermissionV2,+}));++vi.mock("@/components/ColumnDataTable/utils", () => ({+ updateTableCatalog: mocks.updateTableCatalog,+}));++vi.mock("@/react/components/ui/dialog", () => ({+ Dialog: ({ open, children }: { open: boolean; children: ReactNode }) =>+ open ? (+ <div+ onClick={(event) => event.stopPropagation()}+ onMouseDown={(event) => event.stopPropagation()}+ >+ {children}+ </div>+ ) : null,+ DialogContent: ({ children }: { children: ReactNode }) => (+ <div+ onClick={(event) => event.stopPropagation()}+ onMouseDown={(event) => event.stopPropagation()}+ >+ {children}+ </div>+ ),+ DialogTitle: ({ children }: { children: ReactNode }) => <h1>{children}</h1>,+}));++vi.mock("@/react/components/ui/search-input", () => ({+ SearchInput: (props: InputHTMLAttributes<HTMLInputElement>) => (+ <input {...props} />+ ),+}));++vi.mock("@/react/components/ui/button", () => ({+ Button: ({ children, ...props }: ButtonHTMLAttributes<HTMLButtonElement>) => (+ <button type="button" {...props}>+ {children}+ </button>+ ),+}));++vi.mock("@/react/components/ui/table", () => ({+ Table: ({+ children,+ ...props+ }: React.TableHTMLAttributes<HTMLTableElement>) => (+ <table {...props}>{children}</table>+ ),+ TableBody: ({+ children,+ ...props+ }: React.HTMLAttributes<HTMLTableSectionElement>) => (+ <tbody {...props}>{children}</tbody>+ ),+ TableCell: ({+ children,+ ...props+ }: React.TdHTMLAttributes<HTMLTableCellElement>) => (+ <td {...props}>{children}</td>+ ),+ TableHead: ({+ children,+ ...props+ }: React.ThHTMLAttributes<HTMLTableCellElement>) => (+ <th {...props}>{children}</th>+ ),+ TableHeader: ({+ children,+ ...props+ }: React.HTMLAttributes<HTMLTableSectionElement>) => (+ <thead {...props}>{children}</thead>+ ),+ TableRow: ({+ children,+ ...props+ }: React.HTMLAttributes<HTMLTableRowElement>) => (+ <tr {...props}>{children}</tr>+ ),+}));++vi.mock("@/react/components/FeatureAttention", () => ({+ FeatureAttention: ({ feature }: { feature: PlanFeature }) => (+ <div>{PlanFeature[feature]}</div>+ ),+}));++const renderIntoContainer = (element: ReturnType<typeof createElement>) => {+ const container = document.createElement("div");+ const root = createRoot(container);++ return {+ container,+ render: () => {+ act(() => {+ root.render(element);+ });+ },+ unmount: () =>+ act(() => {+ root.unmount();+ }),+ };+};++const flush = async () => {+ await act(async () => {+ await Promise.resolve();+ await Promise.resolve();+ });+};++const click = (element: HTMLElement) => {+ act(() => {+ element.dispatchEvent(+ new MouseEvent("click", { bubbles: true, cancelable: true })+ );+ });+};++const press = (element: HTMLElement) => {+ act(() => {+ element.dispatchEvent(+ new MouseEvent("mousedown", { bubbles: true, cancelable: true })+ );+ element.dispatchEvent(+ new MouseEvent("click", { bubbles: true, cancelable: true })+ );+ });+};++const keydown = (element: HTMLElement, key: string) => {+ act(() => {+ element.dispatchEvent(+ new KeyboardEvent("keydown", { bubbles: true, cancelable: true, key })+ );+ });+};++const makeDatabase = (): Database =>+ ({+ name: "instances/inst1/databases/db",+ project: "projects/proj1",+ instanceResource: {+ name: "instances/inst1",+ engine: Engine.POSTGRES,+ },+ }) as Database;++beforeEach(async () => {+ mocks.useTranslation.mockReset();+ mocks.useTranslation.mockReturnValue({+ t: (key: string) => key,+ });+ mocks.useVueState.mockReset();+ mocks.useVueState.mockImplementation((getter: () => unknown) => getter());+ mocks.useDatabaseCatalog.mockReset();+ mocks.useDatabaseCatalog.mockReturnValue({+ value: { schemas: [] },+ });+ mocks.getTableCatalog.mockReset();+ mocks.getTableCatalog.mockReturnValue({+ classification: "PII",+ });+ mocks.featureToRef.mockReset();+ mocks.featureToRef.mockReturnValue({ value: true });+ mocks.getDatabaseEngine.mockReset();+ mocks.getDatabaseEngine.mockReturnValue(Engine.POSTGRES);+ mocks.getDatabaseProject.mockReset();+ mocks.getDatabaseProject.mockReturnValue({+ name: "projects/proj1",+ dataClassificationConfigId: "classification-config",+ });+ mocks.bytesToString.mockReset();+ mocks.bytesToString.mockImplementation((value: number) => `${value} B`);+ mocks.getInstanceResource.mockReset();+ mocks.getInstanceResource.mockReturnValue({+ name: "instances/inst1",+ engine: Engine.POSTGRES,+ });+ mocks.hasProjectPermissionV2.mockReset();+ mocks.hasProjectPermissionV2.mockReturnValue(true);+ mocks.hasSchemaProperty.mockReset();+ mocks.hasSchemaProperty.mockReturnValue(true);+ mocks.hasWorkspacePermissionV2.mockReset();+ mocks.hasWorkspacePermissionV2.mockReturnValue(true);+ mocks.getOrFetchSettingByName.mockReset();+ mocks.getSettingByName.mockReset();+ mocks.getProjectClassification.mockReset();+ mocks.getProjectClassification.mockReturnValue({+ id: "classification-config",+ levels: [+ { level: 1, title: "Level 1" },+ { level: 2, title: "Level 2" },+ ],+ classification: {+ PII: { id: "PII", title: "PII", level: 1 },+ CONFIDENTIAL: {+ id: "CONFIDENTIAL",+ title: "Confidential",+ level: 2,+ },+ },+ });+ mocks.useSettingV1Store.mockReset();+ mocks.useSettingV1Store.mockReturnValue({+ getOrFetchSettingByName: mocks.getOrFetchSettingByName,+ getSettingByName: mocks.getSettingByName,+ getProjectClassification: mocks.getProjectClassification,+ });+ mocks.updateTableCatalog.mockReset();+ mocks.updateTableCatalog.mockResolvedValue(undefined);++ vi.resetModules();+ ({ TableMetadataTable } = await import("./TableMetadataTable"));+});++describe("TableMetadataTable", () => {+ test("opens table detail when clicking a row", async () => {+ const onRowClick = vi.fn();+ const { container, render, unmount } = renderIntoContainer(+ createElement(TableMetadataTable, {+ database: makeDatabase(),+ schemaName: "public",+ rows: [+ {+ name: "audit",+ rowCount: 0,+ dataSize: 128n,+ indexSize: 64n,+ comment: "audit table",+ partitions: [],+ } as never,+ ],+ onRowClick,+ })+ );++ render();+ await flush();++ const row = Array.from(container.querySelectorAll("tr")).find((row) =>+ row.textContent?.includes("audit")+ );+ expect(row).not.toBeNull();++ click(row as HTMLElement);+ await flush();++ expect(onRowClick).toHaveBeenCalledTimes(1);++ unmount();+ });++ test("clicking the classification icon does not trigger row open", async () => {+ const onRowClick = vi.fn();+ const { container, render, unmount } = renderIntoContainer(+ createElement(TableMetadataTable, {+ database: makeDatabase(),+ schemaName: "public",+ rows: [+ {+ name: "audit",+ rowCount: 0,+ dataSize: 128n,+ indexSize: 64n,+ comment: "audit table",+ partitions: [],+ } as never,+ ],+ onRowClick,+ })+ );++ render();+ await flush();++ const editButton = container.querySelector(+ '[data-testid="table-row-classification-audit-edit"]'+ );+ expect(editButton).not.toBeNull();++ press(editButton as HTMLElement);+ await flush();+ click(+ container.querySelector(+ '[data-testid="classification-option-CONFIDENTIAL"]'+ ) as HTMLElement+ );+ await flush();++ expect(mocks.updateTableCatalog).toHaveBeenCalledWith(+ expect.objectContaining({+ database: "instances/inst1/databases/db",+ schema: "public",+ table: "audit",+ tableCatalog: { classification: "CONFIDENTIAL" },+ })+ );+ expect(onRowClick).not.toHaveBeenCalled();+ expect(mocks.getOrFetchSettingByName).toHaveBeenCalledWith(+ Setting_SettingName.DATA_CLASSIFICATION,+ true+ );++ unmount();+ });++ test("clicking the classification action region does not trigger row open", async () => {+ const onRowClick = vi.fn();+ const { container, render, unmount } = renderIntoContainer(+ createElement(TableMetadataTable, {+ database: makeDatabase(),+ schemaName: "public",+ rows: [+ {+ name: "audit",+ rowCount: 0,+ dataSize: 128n,+ indexSize: 64n,+ comment: "audit table",+ partitions: [],+ } as never,+ ],+ onRowClick,+ })+ );++ render();+ await flush();++ const actionRegion = container.querySelector(+ '[data-testid="table-row-classification-audit-action"]'+ );+ expect(actionRegion).not.toBeNull();++ press(actionRegion as HTMLElement);+ await flush();++ expect(onRowClick).not.toHaveBeenCalled();++ unmount();+ });++ test("pressing enter on the classification edit button does not trigger row open", async () => {+ const onRowClick = vi.fn();+ const { container, render, unmount } = renderIntoContainer(+ createElement(TableMetadataTable, {+ database: makeDatabase(),+ schemaName: "public",+ rows: [+ {+ name: "audit",+ rowCount: 0,+ dataSize: 128n,+ indexSize: 64n,+ comment: "audit table",+ partitions: [],+ } as never,+ ],+ onRowClick,+ })+ );++ render();+ await flush();++ const editButton = container.querySelector(+ '[data-testid="table-row-classification-audit-edit"]'+ );+ expect(editButton).not.toBeNull();++ keydown(editButton as HTMLElement, "Enter");+ await flush();++ expect(onRowClick).not.toHaveBeenCalled();++ unmount();+ });+});diff --git a/frontend/src/react/pages/project/database-detail/overview/TableMetadataTable.tsx b/frontend/src/react/pages/project/database-detail/overview/TableMetadataTable.tsxindex 5b6d3f92ab..2b1a4415b1 100644--- a/frontend/src/react/pages/project/database-detail/overview/TableMetadataTable.tsx+++ b/frontend/src/react/pages/project/database-detail/overview/TableMetadataTable.tsx@@ -1,5 +1,14 @@-import { useMemo } from "react";+import { useEffect, useMemo } from "react";import { useTranslation } from "react-i18next";+import { updateTableCatalog } from "@/components/ColumnDataTable/utils";+import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from "@/react/components/ui/table";import { useVueState } from "@/react/hooks/useVueState";import {featureToRef,@@ -12,54 +21,16 @@ import type {Database,TableMetadata,} from "@/types/proto-es/v1/database_service_pb";-import type { DataClassificationSetting_DataClassificationConfig } from "@/types/proto-es/v1/setting_service_pb";+import { Setting_SettingName } from "@/types/proto-es/v1/setting_service_pb";import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";import {bytesToString,getDatabaseEngine,getDatabaseProject,+ hasProjectPermissionV2,hasSchemaProperty,} from "@/utils";--const BG_COLORS = [- "bg-green-200",- "bg-yellow-200",- "bg-orange-300",- "bg-amber-500",- "bg-red-500",-];--function ClassificationBadge({- classificationId,- classificationConfig,-}: {- classificationId: string | undefined;- classificationConfig:- | DataClassificationSetting_DataClassificationConfig- | undefined;-}) {- if (!classificationId || !classificationConfig) {- return <span>-</span>;- }- const entry = classificationConfig.classification[classificationId];- if (!entry) {- return <span>{classificationId}</span>;- }- const level = (classificationConfig.levels ?? []).find(- (l) => l.level === entry.level- );- const levelColor = BG_COLORS[(entry.level ?? 0) - 1] ?? "bg-gray-200";- return (- <span className="inline-flex items-center gap-x-1">- <span className="truncate">{entry.title}</span>- {level && (- <span className={`shrink-0 rounded px-1 py-0.5 text-xs ${levelColor}`}>- {level.title}- </span>- )}- </span>- );-}+import { EditableClassificationCell } from "./TableDetailDialog";export function TableMetadataTable({database,@@ -89,9 +60,21 @@ export function TableMetadataTable({project.dataClassificationConfigId ?? ""));+ const editable = hasProjectPermissionV2(+ project,+ "bb.databaseCatalogs.update"+ );const showEngineColumn = databaseEngine !== Engine.POSTGRES;const showPartitionedColumn = databaseEngine === Engine.POSTGRES;++ useEffect(() => {+ void settingStore.getOrFetchSettingByName(+ Setting_SettingName.DATA_CLASSIFICATION,+ true+ );+ }, [settingStore]);+const columns = useMemo(() =>[@@ -149,17 +132,15 @@ export function TableMetadataTable({return (<div className="overflow-hidden rounded-lg border border-block-border">- <table className="min-w-full divide-y divide-block-border">- <thead className="bg-control-bg">- <tr className="text-left text-sm text-control-light">+ <Table className="min-w-full">+ <TableHeader className="bg-control-bg">+ <TableRow className="hover:bg-control-bg">{columns.map((column) => (- <th key={column.key} className="px-4 py-2 font-medium">- {column.label}- </th>+ <TableHead key={column.key}>{column.label}</TableHead>))}- </tr>- </thead>- <tbody className="divide-y divide-block-border bg-white">+ </TableRow>+ </TableHeader>+ <TableBody className="bg-white">{rows.map((table) => {const tableCatalog = catalog? getTableCatalog(catalog, schemaName, table.name)@@ -168,17 +149,18 @@ export function TableMetadataTable({tableCatalog?.classification?.trim() || undefined;return (- <tr+ <TableRowkey={`${database.name}.${schemaName}.${table.name}`}- className={- onRowClick ? "cursor-pointer hover:bg-control-bg" : ""- }+ className={onRowClick ? "cursor-pointer" : undefined}role={onRowClick ? "button" : undefined}tabIndex={onRowClick ? 0 : undefined}- onClick={() => onRowClick?.(table)}+ onClick={onRowClick ? () => onRowClick(table) : undefined}onKeyDown={onRowClick? (event) => {+ if (event.target !== event.currentTarget) {+ return;+ }if (event.key === "Enter" || event.key === " ") {event.preventDefault();onRowClick(table);@@ -188,46 +170,56 @@ export function TableMetadataTable({}>{showSchemaColumn && (- <td className="px-4 py-3 text-sm text-main">+ <TableCell className="text-main">{schemaName || t("db.schema.default")}- </td>+ </TableCell>)}- <td className="px-4 py-3 text-sm text-main">{table.name}</td>+ <TableCell className="text-main">{table.name}</TableCell>{showClassificationColumn && (- <td className="px-4 py-3 text-sm text-control">- <ClassificationBadge- classificationId={classification}- classificationConfig={classificationConfig}- />- </td>+ <TableCell>+ <div+ data-testid={`table-row-classification-${table.name}-action`}+ className="inline-flex"+ onClick={(event) => event.stopPropagation()}+ onMouseDown={(event) => event.stopPropagation()}+ onPointerDown={(event) => event.stopPropagation()}+ >+ <EditableClassificationCell+ classification={classification}+ classificationConfig={classificationConfig}+ readonly={!editable}+ testIdPrefix={`table-row-classification-${table.name}`}+ onApply={async (classificationId) => {+ await updateTableCatalog({+ database: database.name,+ schema: schemaName,+ table: table.name,+ tableCatalog: {+ classification: classificationId,+ },+ });+ }}+ />+ </div>+ </TableCell>)}{showEngineColumn && (- <td className="px-4 py-3 text-sm text-control">- {table.engine || "-"}- </td>+ <TableCell>{table.engine || "-"}</TableCell>)}{showPartitionedColumn && (- <td className="px-4 py-3 text-sm text-control">+ <TableCell>{(table.partitions?.length ?? 0) > 0 ? "True" : ""}- </td>+ </TableCell>)}- <td className="px-4 py-3 text-sm text-control">- {String(table.rowCount)}- </td>- <td className="px-4 py-3 text-sm text-control">- {bytesToString(Number(table.dataSize))}- </td>- <td className="px-4 py-3 text-sm text-control">- {bytesToString(Number(table.indexSize))}- </td>- <td className="px-4 py-3 text-sm text-control">- {table.comment || "-"}- </td>- </tr>+ <TableCell>{String(table.rowCount)}</TableCell>+ <TableCell>{bytesToString(Number(table.dataSize))}</TableCell>+ <TableCell>{bytesToString(Number(table.indexSize))}</TableCell>+ <TableCell>{table.comment || "-"}</TableCell>+ </TableRow>);})}- </tbody>- </table>+ </TableBody>+ </Table></div>);}diff --git a/frontend/src/react/pages/project/database-detail/panels/DatabaseOverviewPanel.test.tsx b/frontend/src/react/pages/project/database-detail/panels/DatabaseOverviewPanel.test.tsxnew file mode 100644index 0000000000..aeefa3e026--- /dev/null+++ b/frontend/src/react/pages/project/database-detail/panels/DatabaseOverviewPanel.test.tsx@@ -0,0 +1,996 @@+import { act, createElement } from "react";+import { createRoot } from "react-dom/client";+import { beforeEach, describe, expect, test, vi } from "vitest";+import { Engine, State } from "@/types/proto-es/v1/common_pb";+import {+ type Database,+ SyncStatus,+} from "@/types/proto-es/v1/database_service_pb";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++const mocks = vi.hoisted(() => {+ const currentRoute = {+ value: {+ query: {},+ },+ };++ return {+ localStorage: {+ clear: vi.fn(),+ getItem: vi.fn(() => null),+ removeItem: vi.fn(),+ setItem: vi.fn(),+ },+ useTranslation: vi.fn(() => ({+ t: (key: string) => key,+ })),+ schemaList: [{ name: "public" }, { name: "sales" }],+ currentRoute,+ routerReplace: vi.fn(() => Promise.resolve()),+ useVueState: vi.fn(),+ useDBSchemaV1Store: vi.fn(),+ useDatabaseCatalog: vi.fn(),+ useSubscriptionV1Store: vi.fn(),+ getColumnCatalog: vi.fn(() => ({+ semanticType: "",+ classification: "",+ })),+ getTableCatalog: vi.fn(),+ useSettingV1Store: vi.fn(),+ featureToRef: vi.fn(() => ({ value: true })),+ getDatabaseProject: vi.fn((database: { project: string }) => ({+ name: database.project,+ dataClassificationConfigId: "classification-config",+ })),+ getInstanceResource: vi.fn(+ (database: Database) => database.instanceResource+ ),+ hasProjectPermissionV2: vi.fn(+ (_project?: unknown, _permission?: string) => true+ ),+ getDatabaseEngine: vi.fn(() => Engine.POSTGRES),+ hasIndexSizeProperty: vi.fn(() => true),+ isDev: vi.fn(() => false),+ hasSchemaProperty: vi.fn(() => true),+ hasTableEngineProperty: vi.fn(() => false),+ instanceV1HasCollationAndCharacterSet: vi.fn(() => true),+ instanceV1SupportsColumn: vi.fn(() => true),+ instanceV1SupportsIndex: vi.fn(() => true),+ instanceV1SupportsPackage: vi.fn(() => false),+ instanceV1SupportsSequence: vi.fn(() => false),+ instanceV1SupportsTrigger: vi.fn(() => false),+ bytesToString: vi.fn((size: number) => `${size} B`),+ humanizeDate: vi.fn(() => "5 minutes ago"),+ };+});++vi.stubGlobal("localStorage", mocks.localStorage);++let DatabaseOverviewPanel: typeof import("./DatabaseOverviewPanel").DatabaseOverviewPanel;++vi.mock("react-i18next", () => ({+ useTranslation: mocks.useTranslation,+}));++vi.mock("@/react/hooks/useVueState", () => ({+ useVueState: mocks.useVueState,+}));++vi.mock("@/router", () => ({+ router: {+ replace: mocks.routerReplace,+ currentRoute: mocks.currentRoute,+ },+}));++vi.mock("@/store", () => ({+ useDBSchemaV1Store: mocks.useDBSchemaV1Store,+ useDatabaseCatalog: mocks.useDatabaseCatalog,+ useSubscriptionV1Store: mocks.useSubscriptionV1Store,+ getColumnCatalog: mocks.getColumnCatalog,+ getTableCatalog: mocks.getTableCatalog,+ useSettingV1Store: mocks.useSettingV1Store,+ featureToRef: mocks.featureToRef,+}));++vi.mock("@/utils", () => ({+ bytesToString: mocks.bytesToString,+ getDatabaseEngine: mocks.getDatabaseEngine,+ getInstanceResource: mocks.getInstanceResource,+ getDatabaseProject: mocks.getDatabaseProject,+ humanizeDate: mocks.humanizeDate,+ hasIndexSizeProperty: mocks.hasIndexSizeProperty,+ isDev: mocks.isDev,+ hasProjectPermissionV2: mocks.hasProjectPermissionV2,+ hasSchemaProperty: mocks.hasSchemaProperty,+ hasTableEngineProperty: mocks.hasTableEngineProperty,+ instanceV1HasCollationAndCharacterSet:+ mocks.instanceV1HasCollationAndCharacterSet,+ instanceV1SupportsColumn: mocks.instanceV1SupportsColumn,+ instanceV1SupportsIndex: mocks.instanceV1SupportsIndex,+ instanceV1SupportsPackage: mocks.instanceV1SupportsPackage,+ instanceV1SupportsSequence: mocks.instanceV1SupportsSequence,+ instanceV1SupportsTrigger: mocks.instanceV1SupportsTrigger,+}));++vi.mock("@/react/components/ui/input", () => ({+ Input: (props: React.InputHTMLAttributes<HTMLInputElement>) => (+ <input {...props} />+ ),+}));++vi.mock("@/react/components/ui/dialog", () => ({+ Dialog: ({+ open,+ onOpenChange,+ children,+ }: {+ open: boolean;+ onOpenChange?: (open: boolean) => void;+ children: React.ReactNode;+ }) =>+ open ? (+ <div data-testid="dialog-root">+ <button type="button" onClick={() => onOpenChange?.(false)}>+ close-dialog+ </button>+ {children}+ </div>+ ) : null,+ DialogContent: ({ children }: { children: React.ReactNode }) => (+ <div>{children}</div>+ ),+ DialogTitle: ({ children }: { children: React.ReactNode }) => (+ <h1>{children}</h1>+ ),+}));++const renderIntoContainer = (element: ReturnType<typeof createElement>) => {+ const container = document.createElement("div");+ const root = createRoot(container);++ return {+ container,+ render: (nextElement = element) => {+ act(() => {+ root.render(nextElement);+ });+ },+ unmount: () =>+ act(() => {+ root.unmount();+ }),+ };+};++const flush = async () => {+ await act(async () => {+ await Promise.resolve();+ await Promise.resolve();+ });+};++const setSelectValue = (select: HTMLSelectElement, value: string) => {+ act(() => {+ const descriptor = Object.getOwnPropertyDescriptor(+ HTMLSelectElement.prototype,+ "value"+ );+ descriptor?.set?.call(select, value);+ select.dispatchEvent(new Event("input", { bubbles: true }));+ select.dispatchEvent(new Event("change", { bubbles: true }));+ });+};++const clickElement = (element: Element) => {+ act(() => {+ element.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });+};++const makeTable = (name: string) =>+ ({+ name,+ rowCount: 7,+ dataSize: 64n,+ indexSize: 32n,+ comment: `${name} comment`,+ columns: [+ {+ name: "id",+ type: "INT",+ comment: "",+ },+ ],+ }) as never;++const makeDatabase = (): Database =>+ ({+ name: "instances/inst1/databases/db",+ project: "projects/proj1",+ effectiveEnvironment: "environments/prod",+ state: State.ACTIVE,+ syncStatus: SyncStatus.OK,+ syncError: "",+ successfulSyncTime: {+ seconds: 1n,+ nanos: 0,+ },+ instanceResource: {+ name: "instances/inst1",+ title: "Primary",+ engine: Engine.POSTGRES,+ },+ }) as Database;++beforeEach(async () => {+ mocks.schemaList = [{ name: "public" }, { name: "sales" }];+ mocks.localStorage.clear.mockReset();+ mocks.localStorage.getItem.mockReset();+ mocks.localStorage.getItem.mockReturnValue(null);+ mocks.localStorage.removeItem.mockReset();+ mocks.localStorage.setItem.mockReset();+ mocks.useTranslation.mockReset();+ mocks.useTranslation.mockReturnValue({+ t: (key: string) => key,+ });+ mocks.currentRoute.value.query = {};+ mocks.routerReplace.mockReset();+ mocks.routerReplace.mockImplementation(() => Promise.resolve());+ mocks.getDatabaseProject.mockReset();+ mocks.getDatabaseProject.mockImplementation(+ (database: { project: string }) => ({+ name: database.project,+ dataClassificationConfigId: "classification-config",+ })+ );+ mocks.getInstanceResource.mockReset();+ mocks.getInstanceResource.mockImplementation(+ (database: Database) => database.instanceResource+ );+ mocks.hasProjectPermissionV2.mockReset();+ mocks.hasProjectPermissionV2.mockReturnValue(true);+ mocks.getDatabaseEngine.mockReset();+ mocks.getDatabaseEngine.mockReturnValue(Engine.POSTGRES);+ mocks.isDev.mockReset();+ mocks.isDev.mockReturnValue(false);+ mocks.hasSchemaProperty.mockReset();+ mocks.hasSchemaProperty.mockReturnValue(true);+ mocks.instanceV1HasCollationAndCharacterSet.mockReset();+ mocks.instanceV1HasCollationAndCharacterSet.mockReturnValue(true);+ mocks.instanceV1SupportsColumn.mockReset();+ mocks.instanceV1SupportsColumn.mockReturnValue(true);+ mocks.instanceV1SupportsPackage.mockReset();+ mocks.instanceV1SupportsPackage.mockReturnValue(false);+ mocks.instanceV1SupportsSequence.mockReset();+ mocks.instanceV1SupportsSequence.mockReturnValue(false);+ mocks.bytesToString.mockReset();+ mocks.bytesToString.mockImplementation((size: number) => `${size} B`);+ mocks.humanizeDate.mockReset();+ mocks.humanizeDate.mockReturnValue("5 minutes ago");+ mocks.useDBSchemaV1Store.mockReset();+ mocks.useDBSchemaV1Store.mockReturnValue({+ getSchemaList: vi.fn(() => mocks.schemaList),+ getTableList: vi.fn(() => [makeTable("orders")]),+ getViewList: vi.fn(() => []),+ getExtensionList: vi.fn(() => []),+ getExternalTableList: vi.fn(() => []),+ getFunctionList: vi.fn(() => []),+ getDatabaseMetadata: vi.fn(() => ({+ characterSet: "UTF8",+ collation: "en_US.UTF-8",+ schemas: [],+ })),+ });+ mocks.useDatabaseCatalog.mockReset();+ mocks.useDatabaseCatalog.mockReturnValue({+ value: {+ schemas: [],+ },+ });+ mocks.getColumnCatalog.mockReset();+ mocks.getColumnCatalog.mockReturnValue({+ semanticType: "",+ classification: "",+ });+ mocks.getTableCatalog.mockReset();+ mocks.getTableCatalog.mockReturnValue({+ classification: "",+ });+ mocks.useSettingV1Store.mockReset();+ mocks.useSettingV1Store.mockReturnValue({+ getOrFetchSettingByName: vi.fn(),+ getSettingByName: vi.fn(() => undefined),+ getProjectClassification: vi.fn(() => undefined),+ });+ mocks.useSubscriptionV1Store.mockReset();+ mocks.useSubscriptionV1Store.mockReturnValue({+ hasFeature: vi.fn(() => true),+ instanceMissingLicense: vi.fn(() => false),+ });+ mocks.featureToRef.mockReset();+ mocks.featureToRef.mockReturnValue({+ value: true,+ });+ mocks.hasIndexSizeProperty.mockReset();+ mocks.hasIndexSizeProperty.mockReturnValue(true);+ mocks.hasTableEngineProperty.mockReset();+ mocks.hasTableEngineProperty.mockReturnValue(false);+ mocks.instanceV1SupportsIndex.mockReset();+ mocks.instanceV1SupportsIndex.mockReturnValue(true);+ mocks.useVueState.mockReset();+ mocks.useVueState.mockImplementation((getter: () => unknown) => getter());++ vi.resetModules();+ ({ DatabaseOverviewPanel } = await import("./DatabaseOverviewPanel"));+});++describe("DatabaseOverviewPanel", () => {+ test("renders legacy overview info fields and schema selector", async () => {+ const { container, render, unmount } = renderIntoContainer(+ createElement(DatabaseOverviewPanel, {+ database: makeDatabase(),+ hasSchemaPermission: true,+ })+ );++ render();+ await flush();++ expect(container.textContent).toContain("db.encoding");+ expect(container.textContent).toContain("UTF8");+ expect(container.textContent).toContain("db.collation");+ expect(container.textContent).toContain("en_US.UTF-8");+ expect(container.textContent).toContain("database.sync-status");+ expect(container.textContent).toContain("common.ok");+ expect(container.textContent).toContain("database.last-sync");+ expect(container.textContent).toContain("5 minutes ago");+ expect(container.querySelector("select")).not.toBeNull();+ expect(+ container.querySelector('input[placeholder="common.filter-by-name"]')+ ).not.toBeNull();++ unmount();+ });++ test("renders the legacy tables header instead of the generic object header", async () => {+ const { container, render, unmount } = renderIntoContainer(+ createElement(DatabaseOverviewPanel, {+ database: makeDatabase(),+ hasSchemaPermission: true,+ })+ );++ render();+ await flush();++ const tableHeaderText = Array.from(container.querySelectorAll("th")).map(+ (cell) => cell.textContent+ );++ expect(tableHeaderText).toEqual(+ expect.arrayContaining([+ "common.schema",+ "common.name",+ "database.classification.self",+ "database.partitioned",+ "database.row-count-est",+ "database.data-size",+ "database.index-size",+ "common.comment",+ ])+ );+ expect(tableHeaderText).not.toContain("common.definition");++ unmount();+ });++ test("restores the table engine column for MySQL overview rows", async () => {+ mocks.getDatabaseEngine.mockReturnValue(Engine.MYSQL);+ mocks.useDBSchemaV1Store.mockReturnValue({+ getSchemaList: vi.fn(() => mocks.schemaList),+ getTableList: vi.fn(+ () =>+ [+ {+ name: "orders",+ engine: "InnoDB",+ rowCount: 7,+ dataSize: 64n,+ indexSize: 32n,+ comment: "orders comment",+ columns: [+ {+ name: "id",+ type: "INT",+ comment: "",+ },+ ],+ },+ ] as never+ ),+ getViewList: vi.fn(() => []),+ getExtensionList: vi.fn(() => []),+ getExternalTableList: vi.fn(() => []),+ getFunctionList: vi.fn(() => []),+ getDatabaseMetadata: vi.fn(() => ({+ characterSet: "utf8mb4",+ collation: "utf8mb4_0900_ai_ci",+ schemas: [],+ })),+ });++ vi.resetModules();+ ({ DatabaseOverviewPanel } = await import("./DatabaseOverviewPanel"));++ const { container, render, unmount } = renderIntoContainer(+ createElement(DatabaseOverviewPanel, {+ database: makeDatabase(),+ hasSchemaPermission: true,+ })+ );++ render();+ await flush();++ const tableHeaderText = Array.from(container.querySelectorAll("th")).map(+ (cell) => cell.textContent+ );+ expect(tableHeaderText).toContain("database.engine");+ expect(container.textContent).toContain("InnoDB");++ unmount();+ });++ test("renders failed sync status and error from the legacy overview behavior", async () => {+ const { container, render, unmount } = renderIntoContainer(+ createElement(DatabaseOverviewPanel, {+ database: {+ ...makeDatabase(),+ syncStatus: SyncStatus.FAILED,+ syncError: "sync failed hard",+ },+ hasSchemaPermission: false,+ })+ );++ render();+ await flush();++ expect(container.textContent).toContain("database.sync-status-failed");+ expect(container.textContent).toContain("sync failed hard");++ unmount();+ });++ test("renders dash for last sync when the sync timestamp is missing", async () => {+ const { container, render, unmount } = renderIntoContainer(+ createElement(DatabaseOverviewPanel, {+ database: {+ ...makeDatabase(),+ successfulSyncTime: undefined,+ },+ hasSchemaPermission: false,+ })+ );++ render();+ await flush();++ expect(container.textContent).toContain("database.last-sync");+ expect(container.textContent).toContain("-");+ expect(mocks.humanizeDate).not.toHaveBeenCalled();++ unmount();+ });++ test("syncs selected schema back to the route query", async () => {+ const { container, render, unmount } = renderIntoContainer(+ createElement(DatabaseOverviewPanel, {+ database: makeDatabase(),+ hasSchemaPermission: true,+ })+ );++ render();+ await flush();++ const select = container.querySelector(+ "select"+ ) as HTMLSelectElement | null;+ expect(select).not.toBeNull();++ setSelectValue(select as HTMLSelectElement, "public");+ await flush();++ expect(mocks.routerReplace).toHaveBeenCalledWith(+ expect.objectContaining({+ query: expect.objectContaining({ schema: "public" }),+ })+ );++ unmount();+ });++ test("syncs selected table to the route query and restores it from the route", async () => {+ const { router } = await import("@/router");+ router.currentRoute.value.query = { schema: "public", table: "orders" };++ const { container, render, unmount } = renderIntoContainer(+ createElement(DatabaseOverviewPanel, {+ database: makeDatabase(),+ hasSchemaPermission: true,+ })+ );++ render();+ await flush();++ expect(container.textContent).toContain("orders");+ expect(+ container.querySelector('[data-testid="dialog-root"]')+ ).not.toBeNull();++ const closeButton = Array.from(container.querySelectorAll("button")).find(+ (button) => button.textContent === "close-dialog"+ );+ expect(closeButton).toBeTruthy();+ clickElement(closeButton as HTMLButtonElement);+ await flush();++ expect(mocks.routerReplace).toHaveBeenCalledWith(+ expect.objectContaining({+ query: expect.objectContaining({+ schema: "public",+ table: undefined,+ }),+ })+ );+ router.currentRoute.value.query = { schema: "public" };++ const ordersCell = Array.from(container.querySelectorAll("td")).find(+ (cell) => cell.textContent === "orders"+ );+ expect(ordersCell?.closest("tr")).toBeTruthy();+ clickElement(ordersCell?.closest("tr") as HTMLTableRowElement);+ await flush();++ expect(mocks.routerReplace).toHaveBeenCalledWith(+ expect.objectContaining({+ query: expect.objectContaining({+ schema: "public",+ table: "orders",+ }),+ })+ );++ unmount();+ router.currentRoute.value.query = {};+ });++ test("hides the schema explorer when schema permission is missing", async () => {+ const { container, render, unmount } = renderIntoContainer(+ createElement(DatabaseOverviewPanel, {+ database: makeDatabase(),+ hasSchemaPermission: false,+ })+ );++ render();+ await flush();++ expect(container.textContent).toContain("db");+ expect(container.querySelector("select")).toBeNull();++ unmount();+ });++ test("treats the empty-string schema as a valid resolved selection", async () => {+ mocks.schemaList = [{ name: "" }];+ mocks.useDBSchemaV1Store.mockReturnValue({+ getSchemaList: vi.fn(() => mocks.schemaList),+ getTableList: vi.fn(() => []),+ getViewList: vi.fn(() => []),+ getExtensionList: vi.fn(() => []),+ getExternalTableList: vi.fn(() => []),+ getFunctionList: vi.fn(() => []),+ getDatabaseMetadata: vi.fn(() => ({+ characterSet: "UTF8",+ collation: "en_US.UTF-8",+ schemas: [],+ })),+ });++ vi.resetModules();+ ({ DatabaseOverviewPanel } = await import("./DatabaseOverviewPanel"));++ const { container, render, unmount } = renderIntoContainer(+ createElement(DatabaseOverviewPanel, {+ database: makeDatabase(),+ hasSchemaPermission: true,+ })+ );++ render();+ await flush();++ expect(container.textContent).not.toContain("common.loading");+ expect(container.querySelector("select")?.getAttribute("disabled")).toBe(+ null+ );++ unmount();+ });++ test("clears a stale table query when the table does not exist", async () => {+ const { router } = await import("@/router");+ router.currentRoute.value.query = { schema: "public", table: "missing" };++ const { render, unmount } = renderIntoContainer(+ createElement(DatabaseOverviewPanel, {+ database: makeDatabase(),+ hasSchemaPermission: true,+ })+ );++ render();+ await flush();++ expect(mocks.routerReplace).toHaveBeenCalledWith(+ expect.objectContaining({+ query: expect.objectContaining({+ schema: "public",+ table: undefined,+ }),+ })+ );++ unmount();+ router.currentRoute.value.query = {};+ });++ test("keeps an existing schema query instead of clearing it during initialization", async () => {+ const { router } = await import("@/router");+ router.currentRoute.value.query = { schema: "sales" };++ const { container, render, unmount } = renderIntoContainer(+ createElement(DatabaseOverviewPanel, {+ database: makeDatabase(),+ hasSchemaPermission: true,+ })+ );++ render();+ await flush();++ expect((container.querySelector("select") as HTMLSelectElement).value).toBe(+ "sales"+ );+ expect(mocks.routerReplace).not.toHaveBeenCalledWith({+ query: expect.objectContaining({+ schema: undefined,+ }),+ });++ unmount();+ router.currentRoute.value.query = {};+ });++ test("flattens package objects across schemas when the engine has no schema property", async () => {+ mocks.getDatabaseEngine.mockReturnValue(Engine.ORACLE);+ mocks.hasSchemaProperty.mockReturnValue(false);+ mocks.instanceV1HasCollationAndCharacterSet.mockReturnValue(true);+ mocks.instanceV1SupportsPackage.mockReturnValue(true);+ mocks.useDBSchemaV1Store.mockReturnValue({+ getSchemaList: vi.fn(() => []),+ getTableList: vi.fn(() => []),+ getViewList: vi.fn(() => []),+ getExtensionList: vi.fn(() => []),+ getExternalTableList: vi.fn(() => []),+ getFunctionList: vi.fn(() => []),+ getDatabaseMetadata: vi.fn(() => ({+ characterSet: "AL32UTF8",+ collation: "",+ schemas: [+ {+ name: "alpha",+ packages: [{ name: "pkg_a", definition: "a" }],+ sequences: [],+ streams: [],+ tasks: [],+ },+ {+ name: "beta",+ packages: [{ name: "pkg_b", definition: "b" }],+ sequences: [],+ streams: [],+ tasks: [],+ },+ ],+ })),+ });++ vi.resetModules();+ ({ DatabaseOverviewPanel } = await import("./DatabaseOverviewPanel"));++ const { container, render, unmount } = renderIntoContainer(+ createElement(DatabaseOverviewPanel, {+ database: makeDatabase(),+ hasSchemaPermission: true,+ })+ );++ render();+ await flush();++ expect(container.textContent).toContain("pkg_a");+ expect(container.textContent).toContain("pkg_b");++ unmount();+ });++ test("uses function signatures for overloaded function identity and display", async () => {+ mocks.useDBSchemaV1Store.mockReturnValue({+ getSchemaList: vi.fn(() => mocks.schemaList),+ getTableList: vi.fn(() => [makeTable("orders")]),+ getViewList: vi.fn(() => []),+ getExtensionList: vi.fn(() => []),+ getExternalTableList: vi.fn(() => []),+ getFunctionList: vi.fn(() => [+ { name: "compute", signature: "compute(int)", definition: "sql 1" },+ { name: "compute", signature: "compute(text)", definition: "sql 2" },+ ]),+ getDatabaseMetadata: vi.fn(() => ({+ characterSet: "UTF8",+ collation: "en_US.UTF-8",+ schemas: [],+ })),+ });++ vi.resetModules();+ ({ DatabaseOverviewPanel } = await import("./DatabaseOverviewPanel"));++ const { container, render, unmount } = renderIntoContainer(+ createElement(DatabaseOverviewPanel, {+ database: makeDatabase(),+ hasSchemaPermission: true,+ })+ );++ render();+ await flush();++ expect(container.textContent).toContain("compute(int)");+ expect(container.textContent).toContain("compute(text)");++ unmount();+ });++ test("flattens sequences across schemas when schema properties are unsupported", async () => {+ mocks.hasSchemaProperty.mockReturnValue(false);+ mocks.instanceV1SupportsSequence.mockReturnValue(true);+ mocks.useDBSchemaV1Store.mockReturnValue({+ getSchemaList: vi.fn(() => []),+ getTableList: vi.fn(() => []),+ getViewList: vi.fn(() => []),+ getExtensionList: vi.fn(() => []),+ getExternalTableList: vi.fn(() => []),+ getFunctionList: vi.fn(() => []),+ getDatabaseMetadata: vi.fn(() => ({+ characterSet: "UTF8",+ collation: "",+ schemas: [+ { name: "alpha", sequences: [{ name: "seq_a", dataType: "BIGINT" }] },+ { name: "beta", sequences: [{ name: "seq_b", dataType: "BIGINT" }] },+ ],+ })),+ });++ vi.resetModules();+ ({ DatabaseOverviewPanel } = await import("./DatabaseOverviewPanel"));++ const { container, render, unmount } = renderIntoContainer(+ createElement(DatabaseOverviewPanel, {+ database: makeDatabase(),+ hasSchemaPermission: true,+ })+ );++ render();+ await flush();++ expect(container.textContent).toContain("seq_a");+ expect(container.textContent).toContain("seq_b");++ unmount();+ });++ test("does not fall back to the first schema for schema-scoped sequences", async () => {+ const { router } = await import("@/router");+ router.currentRoute.value.query = { schema: "sales" };++ mocks.instanceV1SupportsSequence.mockReturnValue(true);+ mocks.useDBSchemaV1Store.mockReturnValue({+ getSchemaList: vi.fn(() => mocks.schemaList),+ getTableList: vi.fn(() => []),+ getViewList: vi.fn(() => []),+ getExtensionList: vi.fn(() => []),+ getExternalTableList: vi.fn(() => []),+ getFunctionList: vi.fn(() => []),+ getDatabaseMetadata: vi.fn(() => ({+ characterSet: "UTF8",+ collation: "",+ schemas: [+ { name: "alpha", sequences: [{ name: "seq_a", dataType: "BIGINT" }] },+ ],+ })),+ });++ vi.resetModules();+ ({ DatabaseOverviewPanel } = await import("./DatabaseOverviewPanel"));++ const { container, render, unmount } = renderIntoContainer(+ createElement(DatabaseOverviewPanel, {+ database: makeDatabase(),+ hasSchemaPermission: true,+ })+ );++ render();+ await flush();++ expect(container.textContent).not.toContain("seq_a");++ unmount();+ router.currentRoute.value.query = {};+ });++ test("flattens streams and tasks across schemas when schema properties are unsupported", async () => {+ mocks.getDatabaseEngine.mockReturnValue(Engine.SNOWFLAKE);+ mocks.hasSchemaProperty.mockReturnValue(false);+ mocks.useDBSchemaV1Store.mockReturnValue({+ getSchemaList: vi.fn(() => []),+ getTableList: vi.fn(() => []),+ getViewList: vi.fn(() => []),+ getExtensionList: vi.fn(() => []),+ getExternalTableList: vi.fn(() => []),+ getFunctionList: vi.fn(() => []),+ getDatabaseMetadata: vi.fn(() => ({+ characterSet: "UTF8",+ collation: "",+ schemas: [+ {+ name: "alpha",+ streams: [{ name: "stream_a", tableName: "orders" }],+ tasks: [{ name: "task_a", schedule: "cron_a" }],+ },+ {+ name: "beta",+ streams: [{ name: "stream_b", tableName: "users" }],+ tasks: [{ name: "task_b", schedule: "cron_b" }],+ },+ ],+ })),+ });++ vi.resetModules();+ ({ DatabaseOverviewPanel } = await import("./DatabaseOverviewPanel"));++ const { container, render, unmount } = renderIntoContainer(+ createElement(DatabaseOverviewPanel, {+ database: makeDatabase(),+ hasSchemaPermission: true,+ })+ );++ render();+ await flush();++ expect(container.textContent).toContain("stream_a");+ expect(container.textContent).toContain("stream_b");+ expect(container.textContent).toContain("task_a");+ expect(container.textContent).toContain("task_b");++ unmount();+ });++ test("does not fall back to the first schema for schema-scoped streams and tasks", async () => {+ const { router } = await import("@/router");+ router.currentRoute.value.query = { schema: "sales" };++ mocks.getDatabaseEngine.mockReturnValue(Engine.SNOWFLAKE);+ mocks.useDBSchemaV1Store.mockReturnValue({+ getSchemaList: vi.fn(() => mocks.schemaList),+ getTableList: vi.fn(() => []),+ getViewList: vi.fn(() => []),+ getExtensionList: vi.fn(() => []),+ getExternalTableList: vi.fn(() => []),+ getFunctionList: vi.fn(() => []),+ getDatabaseMetadata: vi.fn(() => ({+ characterSet: "UTF8",+ collation: "",+ schemas: [+ {+ name: "alpha",+ streams: [{ name: "stream_a", tableName: "orders" }],+ tasks: [{ name: "task_a", schedule: "cron_a" }],+ },+ ],+ })),+ });++ vi.resetModules();+ ({ DatabaseOverviewPanel } = await import("./DatabaseOverviewPanel"));++ const { container, render, unmount } = renderIntoContainer(+ createElement(DatabaseOverviewPanel, {+ database: makeDatabase(),+ hasSchemaPermission: true,+ })+ );++ render();+ await flush();++ expect(container.textContent).not.toContain("stream_a");+ expect(container.textContent).not.toContain("task_a");++ unmount();+ router.currentRoute.value.query = {};+ });++ test("does not fall back to the first schema for schema-scoped package objects", async () => {+ const { router } = await import("@/router");+ router.currentRoute.value.query = { schema: "sales" };++ mocks.getDatabaseEngine.mockReturnValue(Engine.ORACLE);+ mocks.hasSchemaProperty.mockReturnValue(true);+ mocks.instanceV1SupportsPackage.mockReturnValue(true);+ mocks.useDBSchemaV1Store.mockReturnValue({+ getSchemaList: vi.fn(() => mocks.schemaList),+ getTableList: vi.fn(() => []),+ getViewList: vi.fn(() => []),+ getExtensionList: vi.fn(() => []),+ getExternalTableList: vi.fn(() => []),+ getFunctionList: vi.fn(() => []),+ getDatabaseMetadata: vi.fn(() => ({+ characterSet: "AL32UTF8",+ collation: "",+ schemas: [+ {+ name: "alpha",+ packages: [{ name: "pkg_a", definition: "a" }],+ sequences: [],+ streams: [],+ tasks: [],+ },+ ],+ })),+ });++ vi.resetModules();+ ({ DatabaseOverviewPanel } = await import("./DatabaseOverviewPanel"));++ const { container, render, unmount } = renderIntoContainer(+ createElement(DatabaseOverviewPanel, {+ database: makeDatabase(),+ hasSchemaPermission: true,+ })+ );++ render();+ await flush();++ expect((container.querySelector("select") as HTMLSelectElement).value).toBe(+ "sales"+ );+ expect(container.textContent).not.toContain("pkg_a");++ unmount();+ router.currentRoute.value.query = {};+ });+});