Skip to content

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

fix(frontend): restore database detail parity after #19924 (#19926)

p0nyb3f45ddf9ef7
diff --git a/frontend/src/components/Revision/CreateRevisionDrawer.vue b/frontend/src/components/Revision/CreateRevisionDrawer.vue
index ed466f7892..67561aa21c 100644
--- a/frontend/src/components/Revision/CreateRevisionDrawer.vue
+++ b/frontend/src/components/Revision/CreateRevisionDrawer.vue
@@ -554,12 +554,12 @@ const loadReleases = async () => {
// Load existing revisions to check for duplicates
const loadExistingRevisions = async () => {
try {
- const response = await revisionStore.fetchRevisionsByDatabase(
+ const revisions = await revisionStore.fetchAllRevisionsByDatabase(
props.database,
{ pageSize: 1000 }
);
const versions = new Set<string>();
- response.revisions.forEach((revision) => {
+ revisions.forEach((revision) => {
if (revision.version) {
versions.add(revision.version);
}
diff --git a/frontend/src/react/locales/en-US.json b/frontend/src/react/locales/en-US.json
index df02a9911f..3afc59b0e6 100644
--- a/frontend/src/react/locales/en-US.json
+++ b/frontend/src/react/locales/en-US.json
@@ -521,11 +521,14 @@
"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",
"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",
@@ -556,10 +559,11 @@
"sync-status": "Sync status",
"sync-status-failed": "Sync failed",
"transfer-project": "Transfer Project",
- "type": "Type",
"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": {
diff --git a/frontend/src/react/locales/es-ES.json b/frontend/src/react/locales/es-ES.json
index ddaf5c233f..fc7d3c109b 100644
--- a/frontend/src/react/locales/es-ES.json
+++ b/frontend/src/react/locales/es-ES.json
@@ -521,11 +521,14 @@
"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",
"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",
@@ -556,10 +559,11 @@
"sync-status": "Estado de sincronización",
"sync-status-failed": "Sincronización fallida",
"transfer-project": "Transferir proyecto",
- "type": "Tipo",
"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": {
diff --git a/frontend/src/react/locales/ja-JP.json b/frontend/src/react/locales/ja-JP.json
index c3c4ea1c13..03ae98ffc8 100644
--- a/frontend/src/react/locales/ja-JP.json
+++ b/frontend/src/react/locales/ja-JP.json
@@ -521,11 +521,14 @@
"expression": "Expression",
"filter-database": "データベースをフィルター",
"index-size": "インデックスサイズ",
+ "indexes": "索引",
"last-sync": "最後の同期",
"mixed-label-values": "混合値",
"mixed-label-values-warning": "選択されたリソースの一部は、同じキーに対して異なる値を持っています。これらのキーと値のペアを変更する場合にのみ編集してください。",
+ "nullable": "null も可能",
"partitioned": "パーティション",
"row-count-est": "推定行数",
+ "row-count-estimate": "推定行数",
"select": "データベースの選択",
"selected-n-databases": "{{n}} 個のデータベースが選択されました",
"successfully-transferred-databases": "データベースの転送に成功しました",
@@ -556,10 +559,11 @@
"sync-status": "同期ステータス",
"sync-status-failed": "同期に失敗しました",
"transfer-project": "プロジェクトの転送",
- "type": "タイプ",
"unassign": "割り当てを解除する",
"unassign-alert-description": "選択したデータベースがプロジェクトから削除されます",
- "unassign-alert-title": "データベースの割り当てを解除する"
+ "unassign-alert-title": "データベースの割り当てを解除する",
+ "unique": "唯一",
+ "visible": "見える"
},
"database-group": {
"condition": {
diff --git a/frontend/src/react/locales/vi-VN.json b/frontend/src/react/locales/vi-VN.json
index 4be7b09724..477084a6bc 100644
--- a/frontend/src/react/locales/vi-VN.json
+++ b/frontend/src/react/locales/vi-VN.json
@@ -521,11 +521,14 @@
"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",
"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",
@@ -556,10 +559,11 @@
"sync-status": "Trạng thái đồng bộ",
"sync-status-failed": "Đồng bộ thất bại",
"transfer-project": "Chuyển dự án",
- "type": "Loại",
"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": {
diff --git a/frontend/src/react/locales/zh-CN.json b/frontend/src/react/locales/zh-CN.json
index 1deea4887a..52935645a7 100644
--- a/frontend/src/react/locales/zh-CN.json
+++ b/frontend/src/react/locales/zh-CN.json
@@ -521,11 +521,14 @@
"expression": "Expression",
"filter-database": "筛选数据库",
"index-size": "索引大小",
+ "indexes": "索引",
"last-sync": "最后一次同步",
"mixed-label-values": "混合值",
"mixed-label-values-warning": "部分标签拥有不同的值,编辑标签将会批量应用。仅在您打算更改时再编辑这些键值对。",
+ "nullable": "可为空",
"partitioned": "分区",
"row-count-est": "估算行数",
+ "row-count-estimate": "估计行数",
"select": "选择数据库",
"selected-n-databases": "已选择 {{n}} 个数据库",
"successfully-transferred-databases": "成功转移数据库",
@@ -556,10 +559,11 @@
"sync-status": "同步状态",
"sync-status-failed": "同步失败",
"transfer-project": "转移项目",
- "type": "类型",
"unassign": "取消分配",
"unassign-alert-description": "选定的数据库将从项目中移除",
- "unassign-alert-title": "取消分配数据库"
+ "unassign-alert-title": "取消分配数据库",
+ "unique": "唯一",
+ "visible": "Visible"
},
"database-group": {
"condition": {
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.tsx
index 9d8b967d66..4204e9a3d2 100644
--- a/frontend/src/react/pages/project/database-detail/overview/DatabaseObjectExplorer.test.tsx
+++ b/frontend/src/react/pages/project/database-detail/overview/DatabaseObjectExplorer.test.tsx
@@ -20,11 +20,25 @@ const mocks = vi.hoisted(() => {
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),
bytesToString: vi.fn((size: number) => `${size} B`),
@@ -55,14 +69,23 @@ vi.mock("@/router", () => ({
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,
hasSchemaProperty: mocks.hasSchemaProperty,
+ hasTableEngineProperty: mocks.hasTableEngineProperty,
+ instanceV1HasCollationAndCharacterSet:
+ mocks.instanceV1HasCollationAndCharacterSet,
+ instanceV1SupportsColumn: mocks.instanceV1SupportsColumn,
+ instanceV1SupportsIndex: mocks.instanceV1SupportsIndex,
instanceV1SupportsPackage: mocks.instanceV1SupportsPackage,
instanceV1SupportsSequence: mocks.instanceV1SupportsSequence,
}));
@@ -172,14 +195,41 @@ beforeEach(async () => {
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();
diff --git a/frontend/src/react/pages/project/database-detail/overview/DatabaseObjectExplorer.tsx b/frontend/src/react/pages/project/database-detail/overview/DatabaseObjectExplorer.tsx
index fb374e29ee..65f73ccfcb 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 { 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 } from "@/store";
+import {
+ featureToRef,
+ getColumnCatalog,
+ getTableCatalog,
+ useDatabaseCatalog,
+ useDBSchemaV1Store,
+ useSettingV1Store,
+} from "@/store";
import { Engine } from "@/types/proto-es/v1/common_pb";
import type {
Database,
@@ -12,10 +20,18 @@ import type {
StreamMetadata,
TaskMetadata,
} 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,
hasSchemaProperty,
+ hasTableEngineProperty,
+ instanceV1HasCollationAndCharacterSet,
+ instanceV1SupportsColumn,
+ instanceV1SupportsIndex,
instanceV1SupportsPackage,
instanceV1SupportsSequence,
} from "@/utils";
@@ -54,6 +70,7 @@ export function DatabaseObjectExplorer({
}) {
const { t } = useTranslation();
const dbSchemaStore = useDBSchemaV1Store();
+ const settingStore = useSettingV1Store();
const databaseEngine = getDatabaseEngine(database);
const supportsSchema = hasSchemaProperty(databaseEngine);
const schemaList = useVueState(() =>
@@ -93,6 +110,17 @@ 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 [selectedTableName, setSelectedTableName] = useState(routeTable);
const selectedSchemaMetadata = databaseMetadata.schemas.find(
@@ -114,20 +142,88 @@ export function DatabaseObjectExplorer({
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
? {
- name: selectedTable.name,
- rowCount: String(selectedTable.rowCount),
+ 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)),
- indexSize: bytesToString(Number(selectedTable.indexSize)),
- columns: selectedTable.columns.map((column) => ({
- name: column.name,
- type: column.type,
- comment: column.comment,
+ 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)),
+ name:
+ supportsSchema && selectedSchemaName
+ ? `"${selectedSchemaName}"."${selectedTable.name}"`
+ : selectedTable.name,
+ rowCount: String(selectedTable.rowCount),
+ 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,
+ showSemanticType: showSemanticTypeColumn,
}
: undefined;
+ useEffect(() => {
+ void settingStore.getOrFetchSettingByName(
+ Setting_SettingName.DATA_CLASSIFICATION,
+ true
+ );
+ }, [settingStore]);
+
useEffect(() => {
setSelectedTableName((current) =>
current === routeTable ? current : routeTable
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.tsx
new file mode 100644
index 0000000000..e77cd11eff
--- /dev/null
+++ b/frontend/src/react/pages/project/database-detail/overview/TableDetailDialog.test.tsx
@@ -0,0 +1,165 @@
+import { act, createElement } from "react";
+import { createRoot } from "react-dom/client";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import type { DataClassificationSetting_DataClassificationConfig } from "@/types/proto-es/v1/setting_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,
+ })),
+}));
+
+let TableDetailDialog: typeof import("./TableDetailDialog").TableDetailDialog;
+
+vi.mock("react-i18next", () => ({
+ useTranslation: mocks.useTranslation,
+}));
+
+vi.mock("@/react/components/ui/dialog", () => ({
+ Dialog: ({ open, children }: { open: boolean; children: React.ReactNode }) =>
+ open ? <div data-testid="dialog-root">{children}</div> : null,
+ DialogContent: ({ children }: { children: React.ReactNode }) => (
+ <div>{children}</div>
+ ),
+ DialogTitle: ({ children }: { children: React.ReactNode }) => (
+ <h1>{children}</h1>
+ ),
+}));
+
+vi.mock("@/react/components/ui/input", () => ({
+ Input: (props: React.InputHTMLAttributes<HTMLInputElement>) => (
+ <input {...props} />
+ ),
+}));
+
+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();
+ });
+};
+
+beforeEach(async () => {
+ mocks.useTranslation.mockReset();
+ mocks.useTranslation.mockReturnValue({
+ t: (key: string) => key,
+ });
+
+ 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: {
+ name: '"public"."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();
+ });
+});
diff --git a/frontend/src/react/pages/project/database-detail/overview/TableDetailDialog.tsx b/frontend/src/react/pages/project/database-detail/overview/TableDetailDialog.tsx
index f8f023aa62..151f156a19 100644
--- a/frontend/src/react/pages/project/database-detail/overview/TableDetailDialog.tsx
+++ b/frontend/src/react/pages/project/database-detail/overview/TableDetailDialog.tsx
@@ -1,19 +1,66 @@
+import { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import {
Dialog,
DialogContent,
DialogTitle,
} from "@/react/components/ui/dialog";
+import { Input } from "@/react/components/ui/input";
+import type { DataClassificationSetting_DataClassificationConfig } from "@/types/proto-es/v1/setting_service_pb";
+
export interface TableDetailDialogData {
+ classification?: string;
+ classificationConfig?: DataClassificationSetting_DataClassificationConfig;
columns: {
+ characterSet?: string;
+ classification?: string;
+ collation?: string;
comment?: string;
+ defaultValue: string;
name: string;
+ nullable: boolean;
+ semanticType?: string;
type: string;
}[];
+ collation?: string;
dataSize: string;
+ engine?: string;
+ indexes: {
+ comment?: string;
+ expressions: string[];
+ name: string;
+ unique: boolean;
+ visible?: boolean;
+ }[];
indexSize: string;
name: string;
rowCount: string;
+ showCharacterSet?: boolean;
+ showColumnClassification?: boolean;
+ showColumnCollation?: boolean;
+ showColumns?: boolean;
+ showCollation?: boolean;
+ showEngine?: boolean;
+ showIndexComment?: boolean;
+ showIndexes?: boolean;
+ showIndexSize?: boolean;
+ showIndexVisible?: boolean;
+ showSemanticType?: boolean;
+}
+
+function getClassificationTitle(
+ classification: string | undefined,
+ classificationConfig:
+ | DataClassificationSetting_DataClassificationConfig
+ | undefined
+) {
+ if (!classification || !classificationConfig) {
+ return "-";
+ }
+
+ return (
+ classificationConfig.classification[classification]?.title || classification
+ );
}
export function TableDetailDialog({
@@ -26,70 +73,283 @@ export function TableDetailDialog({
onOpenChange: (open: boolean) => void;
}) {
const { t } = useTranslation();
+ 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]);
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 showSemanticTypeColumn = table.showSemanticType;
+ const showSummaryCollation = table.showCollation;
+
return (
<Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent className="max-w-3xl p-6">
+ <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.row-count-est")}
+ {t("database.classification.self")}
+ </div>
+ <div className="mt-1 text-sm text-main">
+ {getClassificationTitle(
+ table.classification,
+ table.classificationConfig
+ )}
</div>
- <div className="mt-1 text-sm text-main">{table.rowCount}</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.data-size")}
+ {t("database.row-count-estimate")}
</div>
- <div className="mt-1 text-sm text-main">{table.dataSize}</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.index-size")}
+ {t("database.data-size")}
</div>
- <div className="mt-1 text-sm text-main">{table.indexSize}</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>
- <div className="mt-6">
- <div className="text-sm font-medium text-control-light">
- {t("database.columns")}
- </div>
- <div className="mt-2 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">
- <th className="px-4 py-2 font-medium">{t("common.name")}</th>
- <th className="px-4 py-2 font-medium">
- {t("database.type")}
- </th>
- <th className="px-4 py-2 font-medium">
- {t("common.comment")}
- </th>
- </tr>
- </thead>
- <tbody className="divide-y divide-block-border bg-white">
- {table.columns.map((column) => (
- <tr key={column.name}>
- <td className="px-4 py-3 text-sm text-main">
- {column.name}
- </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.comment || "-"}
- </td>
+
+ {showColumns && (
+ <div className="mt-6 flex flex-col gap-y-4">
+ <div className="flex items-center justify-between gap-3">
+ <div className="text-sm font-medium text-control-light">
+ {t("database.columns")}
+ </div>
+ <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>
- ))}
- </tbody>
- </table>
+ </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">
+ {column.semanticType || "-"}
+ </td>
+ )}
+ {showColumnClassification && (
+ <td className="px-4 py-3 text-sm text-control">
+ {getClassificationTitle(
+ column.classification,
+ table.classificationConfig
+ )}
+ </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>
</div>
- </div>
+ )}
+
+ {table.showIndexes && table.indexes.length > 0 && (
+ <div className="mt-6 flex flex-col gap-y-4">
+ <div className="text-sm font-medium text-control-light">
+ {t("database.indexes")}
+ </div>
+ {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>
+ ))}
+ </div>
+ )}
</DialogContent>
</Dialog>
);
diff --git a/frontend/src/react/pages/project/database-detail/overview/TableMetadataTable.tsx b/frontend/src/react/pages/project/database-detail/overview/TableMetadataTable.tsx
index d7a598d4d3..d84a4ae2ba 100644
--- a/frontend/src/react/pages/project/database-detail/overview/TableMetadataTable.tsx
+++ b/frontend/src/react/pages/project/database-detail/overview/TableMetadataTable.tsx
@@ -32,6 +32,7 @@ export function TableMetadataTable({
const databaseCatalog = useDatabaseCatalog(database.name, false);
const catalog = useVueState(() => databaseCatalog.value);
+ const showEngineColumn = databaseEngine !== Engine.POSTGRES;
const showPartitionedColumn = databaseEngine === Engine.POSTGRES;
const columns = useMemo(
() =>
@@ -46,6 +47,12 @@ export function TableMetadataTable({
label: t("database.classification.self"),
}
: undefined,
+ showEngineColumn
+ ? {
+ key: "engine",
+ label: t("database.engine"),
+ }
+ : undefined,
showPartitionedColumn
? {
key: "partitioned",
@@ -57,7 +64,13 @@ export function TableMetadataTable({
{ key: "indexSize", label: t("database.index-size") },
{ key: "comment", label: t("common.comment") },
].filter((column) => column !== undefined),
- [showClassificationColumn, showPartitionedColumn, showSchemaColumn, t]
+ [
+ showClassificationColumn,
+ showEngineColumn,
+ showPartitionedColumn,
+ showSchemaColumn,
+ t,
+ ]
);
if (loading) {
@@ -127,6 +140,11 @@ export function TableMetadataTable({
{classification || "-"}
</td>
)}
+ {showEngineColumn && (
+ <td className="px-4 py-3 text-sm text-control">
+ {table.engine || "-"}
+ </td>
+ )}
{showPartitionedColumn && (
<td className="px-4 py-3 text-sm text-control">
{(table.partitions?.length ?? 0) > 0 ? "True" : ""}
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.tsx
index f1af1daa6e..ff14ead85f 100644
--- a/frontend/src/react/pages/project/database-detail/panels/DatabaseOverviewPanel.test.tsx
+++ b/frontend/src/react/pages/project/database-detail/panels/DatabaseOverviewPanel.test.tsx
@@ -34,7 +34,12 @@ const mocks = vi.hoisted(() => {
useVueState: vi.fn(),
useDBSchemaV1Store: vi.fn(),
useDatabaseCatalog: 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,
@@ -44,8 +49,12 @@ const mocks = vi.hoisted(() => {
(_project?: unknown, _permission?: string) => true
),
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),
bytesToString: vi.fn((size: number) => `${size} B`),
@@ -75,7 +84,9 @@ vi.mock("@/router", () => ({
vi.mock("@/store", () => ({
useDBSchemaV1Store: mocks.useDBSchemaV1Store,
useDatabaseCatalog: mocks.useDatabaseCatalog,
+ getColumnCatalog: mocks.getColumnCatalog,
getTableCatalog: mocks.getTableCatalog,
+ useSettingV1Store: mocks.useSettingV1Store,
featureToRef: mocks.featureToRef,
}));
@@ -84,10 +95,14 @@ vi.mock("@/utils", () => ({
getDatabaseEngine: mocks.getDatabaseEngine,
getDatabaseProject: mocks.getDatabaseProject,
humanizeDate: mocks.humanizeDate,
+ 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,
}));
@@ -231,6 +246,8 @@ beforeEach(async () => {
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();
@@ -259,14 +276,30 @@ beforeEach(async () => {
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(),
+ getProjectClassification: vi.fn(() => undefined),
+ });
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());
@@ -334,6 +367,63 @@ describe("DatabaseOverviewPanel", () => {
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, {
diff --git a/frontend/src/react/pages/project/database-detail/panels/DatabaseRevisionPanel.test.tsx b/frontend/src/react/pages/project/database-detail/panels/DatabaseRevisionPanel.test.tsx
index 4124e9482d..eb486019a1 100644
--- a/frontend/src/react/pages/project/database-detail/panels/DatabaseRevisionPanel.test.tsx
+++ b/frontend/src/react/pages/project/database-detail/panels/DatabaseRevisionPanel.test.tsx
@@ -22,16 +22,20 @@ const mocks = vi.hoisted(() => ({
useTranslation: vi.fn(() => ({
t: (key: string) => key,
})),
+ CreateRevisionDrawer: Symbol("CreateRevisionDrawer"),
listRevisions: vi.fn(),
- batchCreateRevisions: vi.fn(),
- createSheet: vi.fn(),
deleteRevision: vi.fn(),
- pushNotification: vi.fn(),
currentUser: {
value: {
},
},
+ appRenderers: [] as Array<
+ () => {
+ component: unknown;
+ props: Record<string, unknown>;
+ }
+ >,
createApp: vi.fn(),
h: vi.fn((component: unknown, props: Record<string, unknown>) => ({
component,
@@ -62,7 +66,7 @@ vi.mock("@/components/Revision", () => ({
}));
vi.mock("@/components/Revision/CreateRevisionDrawer.vue", () => ({
- default: Symbol("CreateRevisionDrawer"),
+ default: mocks.CreateRevisionDrawer,
}));
vi.mock("@/plugins/i18n", () => ({
@@ -104,7 +108,6 @@ vi.mock("@/react/components/ui/dialog", () => ({
vi.mock("@/connect", () => ({
revisionServiceClientConnect: {
listRevisions: mocks.listRevisions,
- batchCreateRevisions: mocks.batchCreateRevisions,
},
}));
@@ -112,14 +115,10 @@ vi.mock("@/store", () => ({
pinia: {
install: vi.fn(),
},
- pushNotification: mocks.pushNotification,
useCurrentUserV1: () => mocks.currentUser,
useRevisionStore: () => ({
deleteRevision: mocks.deleteRevision,
}),
- useSheetV1Store: () => ({
- createSheet: mocks.createSheet,
- }),
}));
vi.mock("@/utils/v1/revision", () => ({
@@ -160,21 +159,6 @@ const click = (element: HTMLElement) => {
});
};
-const inputValue = (
- element: HTMLInputElement | HTMLTextAreaElement,
- value: string
-) => {
- act(() => {
- const descriptor = Object.getOwnPropertyDescriptor(
- Object.getPrototypeOf(element),
- "value"
- );
- descriptor?.set?.call(element, value);
- element.dispatchEvent(new Event("input", { bubbles: true }));
- element.dispatchEvent(new Event("change", { bubbles: true }));
- });
-};
-
const makeDatabase = (): Database =>
({
name: "instances/inst1/databases/db1",
@@ -204,38 +188,35 @@ beforeEach(async () => {
} as Revision,
],
});
- mocks.batchCreateRevisions.mockReset();
- mocks.batchCreateRevisions.mockResolvedValue({
- revisions: [
- {
- name: "instances/inst1/databases/db1/revisions/2",
- version: "2.0.0",
- type: Revision_Type.VERSIONED,
- } as Revision,
- ],
- });
- mocks.createSheet.mockReset();
- mocks.createSheet.mockResolvedValue({
- name: "projects/proj1/sheets/sheet-1",
- });
mocks.deleteRevision.mockReset();
mocks.deleteRevision.mockResolvedValue(undefined);
- mocks.pushNotification.mockReset();
+ mocks.appRenderers.length = 0;
mocks.createApp.mockReset();
- mocks.createApp.mockImplementation(() => ({
- use() {
- return this;
- },
- mount() {},
- unmount: vi.fn(),
- }));
+ mocks.createApp.mockImplementation(
+ (appDefinition: { render: () => unknown }) => {
+ return {
+ use() {
+ return this;
+ },
+ mount() {
+ mocks.appRenderers.push(
+ appDefinition.render as () => {
+ component: unknown;
+ props: Record<string, unknown>;
+ }
+ );
+ },
+ unmount: vi.fn(),
+ };
+ }
+ );
vi.resetModules();
({ DatabaseRevisionPanel } = await import("./DatabaseRevisionPanel"));
});
describe("DatabaseRevisionPanel", () => {
- test("opens the revision import dialog and refreshes after create", async () => {
+ test("opens the legacy revision drawer and refreshes after create", async () => {
const { container, render, unmount } = renderIntoContainer(
createElement(DatabaseRevisionPanel, {
database: makeDatabase(),
@@ -245,6 +226,8 @@ describe("DatabaseRevisionPanel", () => {
render();
await flush();
+ expect(mocks.createApp).toHaveBeenCalledTimes(1);
+
const importButton = Array.from(container.querySelectorAll("button")).find(
(button) => button.textContent === "common.import"
) as HTMLButtonElement | undefined;
@@ -253,33 +236,30 @@ describe("DatabaseRevisionPanel", () => {
click(importButton as HTMLButtonElement);
await flush();
- expect(
- container.querySelector('[data-testid="dialog-root"]')
- ).not.toBeNull();
-
- const versionInput = container.querySelector(
- 'input[name="version"]'
- ) as HTMLInputElement | null;
- const statementInput = container.querySelector(
- 'textarea[name="statement"]'
- ) as HTMLTextAreaElement | null;
- expect(versionInput).not.toBeNull();
- expect(statementInput).not.toBeNull();
-
- inputValue(versionInput as HTMLInputElement, "2.0.0");
- inputValue(statementInput as HTMLTextAreaElement, "select 1;");
+ expect(mocks.createApp).toHaveBeenCalledTimes(1);
- const createButton = Array.from(container.querySelectorAll("button")).find(
- (button) => button.textContent === "common.create"
- ) as HTMLButtonElement | undefined;
- expect(createButton).toBeDefined();
+ const latestDrawerVNode = mocks.appRenderers.at(-1)?.();
+ expect(latestDrawerVNode).toMatchObject({
+ component: mocks.CreateRevisionDrawer,
+ props: expect.objectContaining({
+ database: "instances/inst1/databases/db1",
+ show: true,
+ }),
+ });
- click(createButton as HTMLButtonElement);
+ act(() => {
+ (latestDrawerVNode?.props["onCreated"] as (() => void) | undefined)?.();
+ });
await flush();
- expect(mocks.createSheet).toHaveBeenCalledTimes(1);
- expect(mocks.batchCreateRevisions).toHaveBeenCalledTimes(1);
- expect(mocks.listRevisions).toHaveBeenCalledTimes(3);
+ expect(mocks.listRevisions).toHaveBeenCalledTimes(2);
+ expect(mocks.createApp).toHaveBeenCalledTimes(1);
+ expect(mocks.appRenderers.at(-1)?.()).toMatchObject({
+ component: mocks.CreateRevisionDrawer,
+ props: expect.objectContaining({
+ show: false,
+ }),
+ });
unmount();
});
@@ -316,81 +296,4 @@ describe("DatabaseRevisionPanel", () => {
unmount();
});
-
- test("checks duplicate versions across paginated revision results", async () => {
- mocks.listRevisions.mockReset();
- mocks.listRevisions
- .mockResolvedValueOnce({
- nextPageToken: "page-2",
- revisions: [
- {
- name: "instances/inst1/databases/db1/revisions/1",
- version: "1.0.0",
- type: Revision_Type.VERSIONED,
- } as Revision,
- ],
- })
- .mockResolvedValueOnce({
- nextPageToken: "page-2",
- revisions: [
- {
- name: "instances/inst1/databases/db1/revisions/1",
- version: "1.0.0",
- type: Revision_Type.VERSIONED,
- } as Revision,
- ],
- })
- .mockResolvedValueOnce({
- nextPageToken: "",
- revisions: [
- {
- name: "instances/inst1/databases/db1/revisions/2",
- version: "2.0.0",
- type: Revision_Type.VERSIONED,
- } as Revision,
- ],
- });
-
- const { container, render, unmount } = renderIntoContainer(
- createElement(DatabaseRevisionPanel, {
- database: makeDatabase(),
- })
- );
-
- render();
- await flush();
-
- const importButton = Array.from(container.querySelectorAll("button")).find(
- (button) => button.textContent === "common.import"
- ) as HTMLButtonElement | undefined;
- expect(importButton).toBeDefined();
-
- click(importButton as HTMLButtonElement);
- await flush();
-
- const versionInput = container.querySelector(
- 'input[name="version"]'
- ) as HTMLInputElement | null;
- const statementInput = container.querySelector(
- 'textarea[name="statement"]'
- ) as HTMLTextAreaElement | null;
- expect(versionInput).not.toBeNull();
- expect(statementInput).not.toBeNull();
-
- inputValue(versionInput as HTMLInputElement, "2.0.0");
- inputValue(statementInput as HTMLTextAreaElement, "select 1;");
- await flush();
-
- expect(container.textContent).toContain(
- "database.revision.version-already-exists"
- );
-
- const createButton = Array.from(container.querySelectorAll("button")).find(
- (button) => button.textContent === "common.create"
- ) as HTMLButtonElement | undefined;
- expect(createButton).toBeDefined();
- expect(createButton?.disabled).toBe(true);
-
- unmount();
- });
});
diff --git a/frontend/src/react/pages/project/database-detail/panels/DatabaseRevisionPanel.tsx b/frontend/src/react/pages/project/database-detail/panels/DatabaseRevisionPanel.tsx
index 40d26a692b..ad8aec6877 100644
--- a/frontend/src/react/pages/project/database-detail/panels/DatabaseRevisionPanel.tsx
+++ b/frontend/src/react/pages/project/database-detail/panels/DatabaseRevisionPanel.tsx
@@ -1,27 +1,82 @@
import { create } from "@bufbuild/protobuf";
-import { useCallback, useEffect, useState } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
+import { createApp, h, reactive } from "vue";
+import CreateRevisionDrawer from "@/components/Revision/CreateRevisionDrawer.vue";
import { revisionServiceClientConnect } from "@/connect";
+import i18n from "@/plugins/i18n";
+import NaiveUI from "@/plugins/naive-ui";
import { Button } from "@/react/components/ui/button";
import { PagedTableFooter, usePagedData } from "@/react/hooks/usePagedData";
-import { useRevisionStore } from "@/store";
+import { router } from "@/router";
+import { pinia, useRevisionStore } from "@/store";
import type { Database } from "@/types/proto-es/v1/database_service_pb";
import type { Revision } from "@/types/proto-es/v1/revision_service_pb";
-import {
- ListRevisionsRequestSchema,
- type Revision as RevisionMessage,
-} from "@/types/proto-es/v1/revision_service_pb";
-import { CreateRevisionDialog } from "../revision/CreateRevisionDialog";
+import { ListRevisionsRequestSchema } from "@/types/proto-es/v1/revision_service_pb";
import { DatabaseRevisionTable } from "../revision/DatabaseRevisionTable";
+function VueCreateRevisionDrawerMount({
+ databaseName,
+ open,
+ onCreated,
+ onOpenChange,
+}: {
+ databaseName: string;
+ open: boolean;
+ onCreated: (revisions: Revision[]) => void;
+ onOpenChange: (open: boolean) => void;
+}) {
+ const containerRef = useRef<HTMLDivElement>(null);
+ const bridgeStateRef = useRef(
+ reactive({
+ databaseName,
+ onCreated,
+ onOpenChange,
+ open,
+ })
+ );
+
+ useEffect(() => {
+ const bridgeState = bridgeStateRef.current;
+ bridgeState.databaseName = databaseName;
+ bridgeState.onCreated = onCreated;
+ bridgeState.onOpenChange = onOpenChange;
+ bridgeState.open = open;
+ }, [databaseName, onCreated, onOpenChange, open]);
+
+ useEffect(() => {
+ if (!containerRef.current) {
+ return;
+ }
+
+ const bridgeState = bridgeStateRef.current;
+
+ const app = createApp({
+ render() {
+ return h(CreateRevisionDrawer as never, {
+ database: bridgeState.databaseName,
+ show: bridgeState.open,
+ "onUpdate:show": bridgeState.onOpenChange,
+ onCreated: bridgeState.onCreated,
+ });
+ },
+ });
+ app.use(router).use(pinia).use(i18n).use(NaiveUI);
+ app.mount(containerRef.current);
+
+ return () => {
+ app.unmount();
+ };
+ }, []);
+
+ return <div ref={containerRef} />;
+}
+
export function DatabaseRevisionPanel({ database }: { database: Database }) {
const { t } = useTranslation();
const revisionStore = useRevisionStore();
const [showCreateRevisionDrawer, setShowCreateRevisionDrawer] =
useState(false);
- const [existingVersions, setExistingVersions] = useState<string[]>([]);
- const [isLoadingExistingVersions, setIsLoadingExistingVersions] =
- useState(false);
const fetchRevisionList = useCallback(
async ({
pageToken,
@@ -44,61 +99,13 @@ export function DatabaseRevisionPanel({ database }: { database: Database }) {
},
[database.name]
);
- const fetchAllRevisionVersions = useCallback(async () => {
- const versions = new Set<string>();
- let pageToken = "";
-
- do {
- const request = create(ListRevisionsRequestSchema, {
- parent: database.name,
- pageSize: 1000,
- pageToken,
- });
- const { nextPageToken, revisions } =
- await revisionServiceClientConnect.listRevisions(request);
-
- for (const revision of revisions) {
- if (revision.version) {
- versions.add(revision.version);
- }
- }
-
- pageToken = nextPageToken;
- } while (pageToken);
-
- return Array.from(versions);
- }, [database.name]);
const paged = usePagedData<Revision>({
sessionKey: `bb.paged-revision-table.${database.name}`,
fetchList: fetchRevisionList,
});
- useEffect(() => {
- if (!showCreateRevisionDrawer) {
- return;
- }
-
- let cancelled = false;
- setIsLoadingExistingVersions(true);
- void fetchAllRevisionVersions()
- .then((versions) => {
- if (!cancelled) {
- setExistingVersions(versions);
- }
- })
- .finally(() => {
- if (!cancelled) {
- setIsLoadingExistingVersions(false);
- }
- });
-
- return () => {
- cancelled = true;
- };
- }, [fetchAllRevisionVersions, showCreateRevisionDrawer]);
-
const handleRevisionCreated = useCallback(
- (_revisions: RevisionMessage[]) => {
+ (_revisions: Revision[]) => {
setShowCreateRevisionDrawer(false);
paged.refresh();
},
@@ -143,14 +150,11 @@ export function DatabaseRevisionPanel({ database }: { database: Database }) {
onLoadMore={paged.loadMore}
/>
</div>
- <CreateRevisionDialog
+ <VueCreateRevisionDrawerMount
databaseName={database.name}
- existingVersions={existingVersions}
- isCheckingExistingVersions={isLoadingExistingVersions}
open={showCreateRevisionDrawer}
- projectName={database.project}
- onOpenChange={setShowCreateRevisionDrawer}
onCreated={handleRevisionCreated}
+ onOpenChange={setShowCreateRevisionDrawer}
/>
</>
);
diff --git a/frontend/src/store/modules/revision.test.ts b/frontend/src/store/modules/revision.test.ts
new file mode 100644
index 0000000000..5656233ee6
--- /dev/null
+++ b/frontend/src/store/modules/revision.test.ts
@@ -0,0 +1,69 @@
+import { createPinia, setActivePinia } from "pinia";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import type { Revision } from "@/types/proto-es/v1/revision_service_pb";
+
+const mocks = vi.hoisted(() => ({
+ listRevisions: vi.fn(),
+}));
+
+vi.mock("@/connect", () => ({
+ revisionServiceClientConnect: {
+ listRevisions: mocks.listRevisions,
+ },
+}));
+
+let useRevisionStore: typeof import("./revision").useRevisionStore;
+
+beforeEach(async () => {
+ setActivePinia(createPinia());
+ mocks.listRevisions.mockReset();
+
+ vi.resetModules();
+ ({ useRevisionStore } = await import("./revision"));
+});
+
+describe("revision store", () => {
+ test("fetchAllRevisionsByDatabase keeps loading until every page is fetched", async () => {
+ mocks.listRevisions
+ .mockResolvedValueOnce({
+ nextPageToken: "page-2",
+ revisions: [
+ {
+ name: "instances/inst1/databases/db1/revisions/1",
+ version: "1.0.0",
+ } as Revision,
+ ],
+ })
+ .mockResolvedValueOnce({
+ nextPageToken: "",
+ revisions: [
+ {
+ name: "instances/inst1/databases/db1/revisions/2",
+ version: "2.0.0",
+ } as Revision,
+ ],
+ });
+
+ const store = useRevisionStore();
+ const revisions = await store.fetchAllRevisionsByDatabase(
+ "instances/inst1/databases/db1",
+ { pageSize: 1000 }
+ );
+
+ expect(mocks.listRevisions).toHaveBeenCalledTimes(2);
+ expect(mocks.listRevisions.mock.calls[0]?.[0]).toMatchObject({
+ parent: "instances/inst1/databases/db1",
+ pageSize: 1000,
+ pageToken: "",
+ });
+ expect(mocks.listRevisions.mock.calls[1]?.[0]).toMatchObject({
+ parent: "instances/inst1/databases/db1",
+ pageSize: 1000,
+ pageToken: "page-2",
+ });
+ expect(revisions.map((revision) => revision.version)).toEqual([
+ "1.0.0",
+ "2.0.0",
+ ]);
+ });
+});
diff --git a/frontend/src/store/modules/revision.ts b/frontend/src/store/modules/revision.ts
index c00e161f99..5005a6afc0 100644
--- a/frontend/src/store/modules/revision.ts
+++ b/frontend/src/store/modules/revision.ts
@@ -36,6 +36,27 @@ export const useRevisionStore = defineStore("revision", () => {
return resp;
};
+ const fetchAllRevisionsByDatabase = async (
+ database: string,
+ pagination?: {
+ pageSize?: number;
+ }
+ ) => {
+ const revisions: Revision[] = [];
+ let pageToken = "";
+
+ do {
+ const resp = await fetchRevisionsByDatabase(database, {
+ pageSize: pagination?.pageSize,
+ pageToken,
+ });
+ revisions.push(...resp.revisions);
+ pageToken = resp.nextPageToken;
+ } while (pageToken);
+
+ return revisions;
+ };
+
const getRevisionsByDatabase = (database: string) => {
return revisionList.value.filter((revision) =>
revision.name.startsWith(`${database}/${revisionNamePrefix}`)
@@ -65,6 +86,7 @@ export const useRevisionStore = defineStore("revision", () => {
return {
revisionList,
+ fetchAllRevisionsByDatabase,
fetchRevisionsByDatabase,
getRevisionsByDatabase,
getOrFetchRevisionByName,