Skip to content

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

refactor(frontend): remove Vue bridges from project database detail (#19924)

p0ny79dd009d2c73
diff --git a/docs/superpowers/specs/2026-04-09-database-detail-react-migration-design.md b/docs/superpowers/specs/2026-04-09-database-detail-react-migration-design.md
new file mode 100644
index 0000000000..6c34e72abd
--- /dev/null
+++ b/docs/superpowers/specs/2026-04-09-database-detail-react-migration-design.md
@@ -0,0 +1,317 @@
+# Database Detail React Migration Design
+
+Date: 2026-04-09
+
+## Summary
+
+Migrate the project database detail page to a fully React-owned implementation by removing all page-local Vue bridge mounts and replacing them with native React panels and interactions.
+
+This migration is driven by a production failure on the database detail page caused by provider mismatches inside Vue islands mounted from React. The target state is not a repaired bridge layer. The target state is a bridge-free database detail page.
+
+## Problem
+
+The current React page at `frontend/src/react/pages/project/ProjectDatabaseDetailPage.tsx` still mounts several legacy Vue components via `createApp(...)` bridge wrappers. These wrappers do not inherit the provider tree from the main Vue app root, which leads to runtime failures such as missing `n-config-provider` and missing `OverlayStackManager` context.
+
+The immediate crash occurs in the overview tab, but the underlying issue affects the page architecture more broadly:
+
+- React owns the route and tab shell
+- Vue islands own meaningful page content
+- each island mounts its own app boundary
+- provider assumptions leak across those boundaries
+
+This creates fragility during migration and slows removal of Vue from the page.
+
+## Goals
+
+- Remove all Vue bridge mounts from the project database detail page
+- Keep the route, tabs, and top-level page ownership in React
+- Preserve core user workflows for overview, changelog, revision, catalog, settings, and schema diagram entry
+- Keep permission behavior and route synchronization intact
+- Reuse existing stores, services, and router integration patterns already used by React pages
+
+## Non-Goals
+
+- Full app-wide removal of Vue
+- Rewriting shared Vue stores during this task
+- Creating a new generic Vue bridge helper
+- Perfect visual parity where the old implementation adds migration cost without user value
+
+## Scope
+
+### In Scope
+
+- `frontend/src/react/pages/project/ProjectDatabaseDetailPage.tsx`
+- `frontend/src/react/pages/project/database-detail/DatabaseDetailHeader.tsx`
+- `frontend/src/react/pages/project/database-detail/panels/DatabaseOverviewPanel.tsx`
+- `frontend/src/react/pages/project/database-detail/panels/DatabaseCatalogPanel.tsx`
+- `frontend/src/react/pages/project/database-detail/panels/DatabaseChangelogPanel.tsx`
+- `frontend/src/react/pages/project/database-detail/panels/DatabaseRevisionPanel.tsx`
+- schema diagram interaction on the database detail page
+- page-specific tests for database detail React flows
+
+### To Delete
+
+- `frontend/src/react/pages/project/database-detail/legacy/DatabaseObjectExplorerBridge.tsx`
+- `frontend/src/react/pages/project/database-detail/legacy/DatabaseOverviewInfoBridge.tsx`
+- `frontend/src/react/pages/project/database-detail/legacy/SensitiveColumnTableBridge.tsx`
+- `frontend/src/react/pages/project/database-detail/legacy/GrantAccessDrawerBridge.tsx`
+- page-local `createApp(...)` mounts in database detail panels
+
+## Existing Vue-backed Areas
+
+The database detail page still depends on Vue-backed islands in these areas:
+
+- Overview info
+- Object explorer
+- Sensitive column catalog table
+- Grant access drawer
+- Changelog table
+- Revision table
+- Create revision drawer
+- Schema diagram button dialog content
+
+Settings is already React and does not need migration.
+
+## Proposed Approach
+
+Use a full React rewrite for the database detail page with acceptable simplification for secondary flows.
+
+This approach explicitly avoids introducing a better bridge layer. Any effort spent improving bridge composition would increase migration debt and preserve the same failure mode class.
+
+### Why This Approach
+
+- fixes the current crash by removing the failing boundary rather than patching it
+- aligns with the migration direction
+- reduces duplicated runtime stacks inside one page
+- makes page testing simpler and more deterministic
+- avoids future provider-context bugs for this page
+
+## Component Design
+
+### 1. Database Overview Panel
+
+Replace the current bridge-driven overview panel with a React-native implementation.
+
+Responsibilities:
+
+- render overview info fields now provided by `DatabaseOverviewInfo.vue`
+- render schema selector
+- render object sections by engine:
+ - tables
+ - views
+ - external tables
+ - extensions
+ - functions
+ - sequences
+ - streams
+ - tasks
+ - packages
+- keep route query sync for selected schema
+- keep local search state for tables and external tables
+
+Implementation notes:
+
+- use `useVueState` with existing stores rather than creating a new React data layer
+- replace Vue data tables with React tables or list views using existing React UI primitives
+- implement table-detail interactions in React instead of reusing `TableDetailDrawer.vue`
+
+### 2. Database Catalog Panel
+
+Replace the sensitive data table and grant-access bridge flow with React-native equivalents.
+
+Responsibilities:
+
+- flatten database catalog into display rows
+- support search filtering
+- support row selection
+- support delete/removal actions where permitted
+- support opening grant-access flow for selected rows
+
+Implementation notes:
+
+- preserve existing masking and exemption policy semantics
+- allow a simpler visual table design if selection and actions remain clear
+- use existing React dialogs and buttons instead of Vue drawers
+
+### 3. Database Changelog Panel
+
+Replace the Vue changelog table mount with a native React table.
+
+Responsibilities:
+
+- display paged changelog rows
+- keep `usePagedData` behavior
+- keep pagination footer behavior
+- keep current changelog row navigation behavior
+
+### 4. Database Revision Panel
+
+Replace both the Vue revision table mount and the Vue create-revision drawer mount.
+
+Responsibilities:
+
+- display paged revision rows
+- support deletion refresh behavior
+- support opening an import/create revision flow
+- refresh list after create/import
+
+Implementation notes:
+
+- the import flow may use a React dialog rather than reproducing the exact Vue drawer
+- functional parity matters more than visual parity
+
+### 5. Schema Diagram Interaction
+
+Replace `SchemaDiagramButtonBridge.tsx` with a React-owned interaction.
+
+Preferred outcome:
+
+- open a React dialog
+- render a React-native schema visualization or schema browser
+
+Acceptable fallback for this migration:
+
+- ship a simpler React representation of schema structure if the existing schema diagram is too expensive to port immediately
+
+The schema diagram must no longer depend on a Vue app mounted inside the React page.
+
+## State and Data Flow
+
+Top-level page responsibilities remain in `ProjectDatabaseDetailPage.tsx` and `useProjectDatabaseDetail.ts`:
+
+- fetch database
+- fetch schema metadata
+- normalize canonical project route
+- maintain selected tab from route hash
+
+Panel-level responsibilities:
+
+- derive their own display state from shared stores
+- manage local search, selection, and dialog state
+- call store actions and service clients directly
+
+This preserves the current repo pattern used by React pages:
+
+- direct store access
+- `useVueState` for reactive Vue store reads
+- no extra bridge store layer
+
+## Permission Model
+
+Keep existing permission checks:
+
+- route-level permissions remain unchanged
+- `ComponentPermissionGuard` continues to guard changelog, revision, and catalog sections where used
+- project-level checks inside panels remain based on `hasProjectPermissionV2`
+
+No permission logic should move into ad hoc UI-only checks that diverge from the current page behavior.
+
+## Routing Behavior
+
+Must preserve:
+
+- tab state encoded in route hash
+- schema selection encoded in route query
+- canonical project redirect when database project differs from route project
+- existing database detail route name and params
+
+## Simplifications Allowed
+
+These are acceptable in this migration if they reduce complexity without breaking primary workflows:
+
+- use a simpler schema diagram experience
+- use a simpler catalog table layout
+- use a React dialog instead of a drawer for revision import or grant-access flows
+- reduce non-essential visual polish inherited from Vue components
+
+These are not acceptable:
+
+- losing schema selection
+- losing ability to inspect database objects
+- losing changelog or revision listing
+- losing catalog search and grant-access entry
+- reintroducing page-local Vue mounts
+
+## Risks
+
+### Functional Risk
+
+The overview panel covers many engine-specific branches. Reimplementing it risks silent regressions for engines not covered by the immediate reproduction case.
+
+Mitigation:
+
+- keep logic close to current Vue implementation structure
+- derive section lists from the same stores and utility functions
+- add focused tests for engine-driven rendering conditions where feasible
+
+### Migration Risk
+
+Trying to preserve exact Vue component behavior can expand scope rapidly.
+
+Mitigation:
+
+- prefer acceptable simplification for secondary flows
+- preserve behaviorally important outcomes, not internal component parity
+
+### Test Risk
+
+Current tests mock bridge components. Those tests will need to move up to actual React panel assertions.
+
+Mitigation:
+
+- rewrite tests around rendered React behavior rather than bridge call assertions
+
+## Implementation Phases
+
+### Phase 1
+
+Replace overview tab and remove:
+
+- `DatabaseOverviewInfoBridge`
+- `DatabaseObjectExplorerBridge`
+
+This fixes the current page crash.
+
+### Phase 2
+
+Replace changelog and revision panels with native React tables and dialogs.
+
+### Phase 3
+
+Replace catalog sensitive-column table and grant-access flow.
+
+### Phase 4
+
+Replace schema diagram bridge and remove remaining page-local Vue mounts.
+
+### Phase 5
+
+Delete unused `legacy/` files and update tests.
+
+## Verification
+
+Minimum verification for this migration:
+
+- database detail overview tab renders without console provider errors
+- schema selection updates route query correctly
+- changelog tab renders and paginates
+- revision tab renders and import/create flow opens and refreshes
+- catalog tab renders, filters, selects rows, and opens grant-access flow
+- settings tab still works
+- no remaining imports of page-local database-detail bridge files
+
+Required commands after implementation:
+
+- `pnpm --dir frontend fix`
+- `pnpm --dir frontend check`
+- `pnpm --dir frontend type-check`
+- targeted `pnpm --dir frontend test`
+
+## Success Criteria
+
+The migration is complete when:
+
+- the database detail page is fully usable
+- the page no longer mounts Vue apps from React
+- the original provider-context crash is impossible because the failing architecture has been removed
+- tests cover the new React-native behavior rather than bridge invocation details
diff --git a/docs/superpowers/specs/2026-04-09-locale-sorter-design.md b/docs/superpowers/specs/2026-04-09-locale-sorter-design.md
new file mode 100644
index 0000000000..bdc2223318
--- /dev/null
+++ b/docs/superpowers/specs/2026-04-09-locale-sorter-design.md
@@ -0,0 +1,77 @@
+# Locale Sorter Design
+
+## Goal
+
+Add an automatic locale key sorter so `pnpm --dir frontend fix` normalizes locale JSON ordering and prevents `pnpm --dir frontend test` from failing on alphabetization drift.
+
+## Scope
+
+- Add a Node script under `frontend/scripts/` to sort locale JSON keys recursively.
+- Cover both locale trees:
+ - `frontend/src/locales`
+ - `frontend/src/react/locales`
+- Include nested locale directories such as `dynamic/`.
+- Update `frontend/package.json` so `pnpm --dir frontend fix` runs the sorter automatically.
+
+## Non-Goals
+
+- Do not change locale values.
+- Do not modify `pnpm --dir frontend check` or `pnpm --dir frontend test` to mutate files.
+- Do not change the i18n key policy or flattening behavior.
+
+## Sorting Rule
+
+The sorter must match the existing test contract in [frontend/src/plugins/i18n.test.ts](/Users/p0ny/.codex/worktrees/772d/bytebase-mux/frontend/src/plugins/i18n.test.ts):
+
+- Recursively sort object keys using JavaScript's default lexical ordering, equivalent to `Object.keys(obj).sort()`.
+- Preserve arrays as-is.
+- Rebuild objects recursively so nested keys are also sorted.
+
+## File Format
+
+- Read each locale file as JSON.
+- Write back pretty-printed JSON with two-space indentation and a trailing newline.
+- Keep output stable across runs so repeated `fix` invocations are no-ops once files are normalized.
+
+## Script Behavior
+
+The script will:
+
+1. Discover all `.json` files under the two locale roots.
+2. Parse each file.
+3. Recursively sort all object keys.
+4. Rewrite only when the normalized content differs from the current file.
+5. Print a short summary of updated files.
+
+## Package Script Integration
+
+Add a dedicated script, for example `sort:i18n`, and call it from `fix` before the existing ESLint and Biome steps.
+
+Resulting behavior:
+
+- `pnpm --dir frontend fix`
+ - sorts locale files
+ - runs ESLint autofix
+ - runs Biome write
+
+This keeps `fix` as the single repair command for frontend formatting and structure.
+
+## Error Handling
+
+- Fail fast on invalid JSON with the file path in the error message.
+- Exit non-zero if any file cannot be parsed or written.
+- Avoid partial silent success.
+
+## Testing
+
+Verification for the implementation:
+
+- Run `pnpm --dir frontend fix`.
+- Run `CI=1 pnpm --dir frontend test --run src/plugins/i18n.test.ts`.
+- Run `pnpm --dir frontend check`.
+
+Success criteria:
+
+- Locale ordering is normalized automatically by `fix`.
+- The alphabetical-order assertions in `i18n.test.ts` pass without manual file editing.
+- Re-running `fix` after normalization produces no further locale diffs.
diff --git a/docs/superpowers/specs/2026-04-09-revision-import-parity-design.md b/docs/superpowers/specs/2026-04-09-revision-import-parity-design.md
new file mode 100644
index 0000000000..4428f3ea5c
--- /dev/null
+++ b/docs/superpowers/specs/2026-04-09-revision-import-parity-design.md
@@ -0,0 +1,239 @@
+# Revision Import Functional Parity Design
+
+## Goal
+
+Restore the missing revision import capabilities on the React database detail page so users can import revisions from:
+
+- Manual SQL input
+- Release files
+- Local files
+
+The goal is functional parity with the previous Vue drawer, not UI parity. The React implementation can use a simpler layout as long as the same workflows are available and duplicate-version protection remains intact.
+
+## Scope
+
+In scope:
+
+- Extend the React revision import dialog on the database detail page
+- Support selecting a source: manual, release, or local files
+- Support importing multiple revisions from local files
+- Support importing revisions from release files
+- Preserve current duplicate-version validation across all existing revisions, not just the first loaded page
+- Keep the page bridge-free and React-native
+
+Out of scope:
+
+- Recreating the Vue stepper UI
+- Reusing Vue components through a bridge
+- Changing revision semantics or backend APIs
+
+## Current Problem
+
+The React rewrite currently supports only a single manual SQL statement in [CreateRevisionDialog.tsx](/Users/p0ny/.codex/worktrees/772d/bytebase-mux/frontend/src/react/pages/project/database-detail/revision/CreateRevisionDialog.tsx). The legacy Vue drawer in [CreateRevisionDrawer.vue](/Users/p0ny/.codex/worktrees/772d/bytebase-mux/frontend/src/components/Revision/CreateRevisionDrawer.vue) supported additional import sources:
+
+- Import from release
+- Import from local files
+
+This is a functional regression because users can no longer perform those existing import workflows from the React database detail page.
+
+## Recommended Approach
+
+Extend the existing React dialog into a multi-source import dialog.
+
+Why this approach:
+
+- Keeps the current React entry point and panel structure intact
+- Restores the missing capabilities without reintroducing Vue
+- Avoids creating multiple separate dialogs and handoff state
+- Preserves the current manual flow while broadening the available sources
+
+Alternatives considered:
+
+1. Separate dialog per source
+ This isolates state but adds more UI transitions and more panel-level orchestration.
+
+2. Rebuild the Vue stepper one-for-one in React
+ This would overshoot the requirement because the request is for functional parity, not identical UI.
+
+## User Flow
+
+### Manual Source
+
+The existing manual mode remains:
+
+- User selects `manual`
+- User enters version
+- User selects revision type
+- User enters SQL statement
+- User creates one revision
+
+### Local File Source
+
+- User selects `local`
+- User uploads one or more local files
+- The dialog reads file content client-side
+- Each uploaded file becomes one pending revision item
+- For each item, the user sets:
+ - version
+ - revision type
+- The dialog shows:
+ - file name
+ - file size
+ - content preview
+ - invalid-version error
+ - duplicate-version error
+- User submits
+- The dialog creates one sheet per file and batches revision creation
+
+### Release Source
+
+- User selects `release`
+- The dialog loads releases for the current project
+- User selects one release
+- The dialog lists files belonging to that release
+- Files whose versions already exist are shown but not importable
+- Remaining files can be selected for import
+- User submits
+- The dialog creates revisions from the selected release files
+
+## Data Flow
+
+### Existing Revision Versions
+
+[DatabaseRevisionPanel.tsx](/Users/p0ny/.codex/worktrees/772d/bytebase-mux/frontend/src/react/pages/project/database-detail/panels/DatabaseRevisionPanel.tsx) already fetches all revision versions to avoid page-local duplicate checks. That logic stays as the source of truth and is passed into the dialog.
+
+The dialog uses that list to validate:
+
+- manual version
+- every local file version
+- every release file version
+
+### Local File Import
+
+For local files:
+
+- Read each selected file with `File.text()`
+- Convert content to `Uint8Array` using `TextEncoder`
+- Create one sheet per file through `useSheetV1Store`
+- Build one `CreateRevisionRequest` per file
+- Call `batchCreateRevisions`
+
+### Release Import
+
+For release files:
+
+- Load releases using the existing release data path already available in the frontend
+- Load file metadata/content for the selected release
+- For each selected release file:
+ - derive version from the file metadata
+ - derive revision type from the file metadata or current release-file semantics
+ - create a sheet from the file content if required by the current revision API path
+- Batch the create requests through `batchCreateRevisions`
+
+The implementation should follow the current backend-facing contract already used by the Vue workflow rather than inventing a new client-side interpretation.
+
+## Component Structure
+
+Keep the dialog readable by splitting source-specific sections into focused React components under:
+
+- `frontend/src/react/pages/project/database-detail/revision/`
+
+Expected pieces:
+
+- `CreateRevisionDialog.tsx`
+ - owns source selection
+ - owns submit dispatch
+ - owns shared reset behavior
+- `RevisionSourcePicker.tsx`
+ - source selection UI
+- `LocalRevisionFileList.tsx`
+ - uploaded file list, per-file validation, previews
+- `ReleaseRevisionImport.tsx`
+ - release loading, release selection, file selection, duplicate-file display
+
+The final structure can differ slightly if a helper is trivial, but the dialog should not absorb all source-specific rendering and state into one large file.
+
+## Validation Rules
+
+For all sources:
+
+- Version must match the existing numeric dotted format
+- Version must not already exist in the full revision history
+
+Additional local-file rules:
+
+- Each file must have non-empty content
+- Each file must have a version before submit
+
+Additional release rules:
+
+- Only files with non-duplicate versions are importable
+- Submit is disabled until at least one importable file is selected
+
+## State Reset
+
+Closing the dialog resets:
+
+- selected source
+- manual form state
+- uploaded local files
+- selected release
+- selected release files
+- transient loading and error state
+
+Reopening the dialog should start clean.
+
+## Error Handling
+
+If release loading fails:
+
+- keep the dialog open
+- show an inline error state or rely on the existing store notification path
+
+If file reading fails:
+
+- show an inline error for the affected file or reject that file cleanly
+
+If sheet creation or revision creation fails:
+
+- preserve dialog state
+- show the current critical notification pattern
+- allow the user to retry without re-entering everything
+
+## Testing
+
+Add React tests covering:
+
+- manual flow still works
+- local-file import creates multiple revisions
+- local-file duplicate versions are blocked
+- release import excludes already-imported files
+- release import can submit selected files
+- closing and reopening resets source-specific state
+
+Verification after implementation:
+
+- `pnpm --dir frontend fix`
+- `pnpm --dir frontend check`
+- `pnpm --dir frontend type-check`
+- `pnpm --dir frontend test`
+
+## Risks
+
+### Release data access
+
+The main implementation risk is the release-file data path. The React page must use an existing frontend-accessible store or service path rather than pulling Vue UI back in. If the current release data flow is coupled to legacy components, we should reuse the underlying store/client layer directly and rebuild only the UI.
+
+### Dialog size
+
+Supporting three sources can bloat the dialog. This is why the design splits source-specific sections into smaller React components.
+
+## Success Criteria
+
+This work is complete when:
+
+- The React database detail page supports manual, release, and local-file revision import
+- Users can import multiple revisions from local files
+- Users can import revisions from release files
+- Duplicate-version validation works against the full revision history
+- No Vue bridge is reintroduced
diff --git a/frontend/package.json b/frontend/package.json
index 8e1d92ac79..913b1acc43 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -9,8 +9,8 @@
"release-docker": "export NODE_OPTIONS=--max_old_space_size=8000 && pnpm run prepare:artifacts && vite build --mode release",
"release-aws": "export NODE_OPTIONS=--max_old_space_size=8000 && pnpm run prepare:artifacts && vite build --mode release-aws",
"precheck": "pnpm run prepare:artifacts",
- "check": "eslint --cache src && biome ci . && node scripts/check-react-i18n.mjs",
- "fix": "eslint --cache --fix src && biome check --write .",
+ "check": "eslint --cache src && biome ci . && node scripts/check-react-i18n.mjs && node scripts/sort_i18n_keys.mjs --check",
+ "fix": "pnpm run sort:i18n && eslint --cache --fix src && biome check --write .",
"bundle-visualize": "export NODE_OPTIONS=--max_old_space_size=80000 && vite-bundle-visualizer -c vite.config.ts",
"pretype-check": "pnpm run prepare:artifacts",
"type-check": "export NODE_OPTIONS=--max_old_space_size=8000 && vue-tsc --build --force && tsc --project tsconfig.react.json --noEmit",
@@ -19,6 +19,7 @@
"precoverage": "pnpm run prepare:artifacts",
"coverage": "vitest --coverage",
"i18n": "TS_NODE_PROJECT='./tsconfig.i18n.json' ts-node i18n.ts && pnpm fix",
+ "sort:i18n": "node scripts/sort_i18n_keys.mjs",
"generate:openapi-index": "node scripts/generate_openapi_index.js"
},
"dependencies": {
diff --git a/frontend/scripts/sort_i18n_keys.mjs b/frontend/scripts/sort_i18n_keys.mjs
new file mode 100644
index 0000000000..17eeb1e637
--- /dev/null
+++ b/frontend/scripts/sort_i18n_keys.mjs
@@ -0,0 +1,170 @@
+import { readFileSync, readdirSync, writeFileSync } from "node:fs";
+import { dirname, extname, resolve } from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const ROOT = resolve(__dirname, "..");
+const LOCALE_ROOTS = [
+ resolve(ROOT, "src/locales"),
+ resolve(ROOT, "src/react/locales"),
+];
+
+export function sortObjectKeys(value) {
+ if (Array.isArray(value) || value === null || typeof value !== "object") {
+ return value;
+ }
+
+ return Object.fromEntries(
+ Object.keys(value)
+ .sort()
+ .map((key) => [key, sortObjectKeys(value[key])])
+ );
+}
+
+function findJsonFiles(dir) {
+ const files = [];
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ const fullPath = resolve(dir, entry.name);
+ if (entry.isDirectory()) {
+ files.push(...findJsonFiles(fullPath));
+ continue;
+ }
+ if (entry.isFile() && extname(entry.name) === ".json") {
+ files.push(fullPath);
+ }
+ }
+ return files;
+}
+
+function prepareLocaleFile(filePath, read = readFileSync) {
+ let current;
+ try {
+ current = read(filePath, "utf-8");
+ } catch (error) {
+ throw new Error(`Failed to read locale file ${filePath}: ${error.message}`);
+ }
+
+ let parsed;
+ try {
+ parsed = JSON.parse(current);
+ } catch (error) {
+ throw new Error(`Failed to parse locale file ${filePath}: ${error.message}`);
+ }
+
+ return {
+ current,
+ normalized: `${JSON.stringify(sortObjectKeys(parsed), null, 2)}\n`,
+ };
+}
+
+export function normalizeLocaleFile(filePath) {
+ const { current, normalized } = prepareLocaleFile(filePath);
+ if (normalized === current) {
+ return false;
+ }
+ try {
+ writeFileSync(filePath, normalized);
+ } catch (error) {
+ throw new Error(`Failed to write locale file ${filePath}: ${error.message}`);
+ }
+ return true;
+}
+
+export function checkLocaleFiles(files, io = {}) {
+ const read = io.readFileSync ?? readFileSync;
+ const preparedFiles = files.map((filePath) => ({
+ filePath,
+ ...prepareLocaleFile(filePath, read),
+ }));
+
+ return preparedFiles
+ .filter((file) => file.normalized !== file.current)
+ .map((file) => file.filePath);
+}
+
+export function sortLocaleFiles(files, io = {}) {
+ const read = io.readFileSync ?? readFileSync;
+ const write = io.writeFileSync ?? writeFileSync;
+ const preparedFiles = files.map((filePath) => ({
+ filePath,
+ ...prepareLocaleFile(filePath, read),
+ }));
+
+ const updated = [];
+ const originalContents = new Map();
+ for (const file of preparedFiles) {
+ if (file.normalized === file.current) {
+ continue;
+ }
+
+ originalContents.set(file.filePath, file.current);
+ try {
+ write(file.filePath, file.normalized);
+ } catch (error) {
+ const writeError = error instanceof Error ? error : new Error(String(error));
+ const rollbackErrors = [];
+ const rollbackTargets = [...updated].reverse();
+ rollbackTargets.push(file.filePath);
+ for (const updatedFile of rollbackTargets) {
+ try {
+ write(updatedFile, originalContents.get(updatedFile));
+ } catch (rollbackError) {
+ rollbackErrors.push(
+ `Failed to restore locale file ${updatedFile}: ${
+ rollbackError instanceof Error ? rollbackError.message : String(rollbackError)
+ }`
+ );
+ }
+ }
+
+ if (rollbackErrors.length > 0) {
+ throw new Error(
+ `Failed to write locale file ${file.filePath}: ${writeError.message}. ` +
+ `Rollback also failed: ${rollbackErrors.join("; ")}`
+ );
+ }
+
+ throw new Error(
+ `Failed to write locale file ${file.filePath}: ${writeError.message}. ` +
+ `Rolled back ${updated.length} earlier file(s) and restored the current file.`
+ );
+ }
+ updated.push(file.filePath);
+ }
+
+ return updated;
+}
+
+function main() {
+ const checkOnly = process.argv.includes("--check");
+ const files = LOCALE_ROOTS.flatMap((root) => findJsonFiles(root));
+ const updated = checkOnly ? checkLocaleFiles(files) : sortLocaleFiles(files);
+
+ if (checkOnly) {
+ if (updated.length === 0) {
+ console.log(`Locale sorter: all ${files.length} file(s) are normalized.`);
+ return;
+ }
+
+ console.error(
+ `Locale sorter: ${updated.length} file(s) need sorting:\n` +
+ updated.map((filePath) => ` - ${filePath}`).join("\n")
+ );
+ process.exitCode = 1;
+ return;
+ }
+
+ const unchanged = files.length - updated.length;
+ if (updated.length === 0) {
+ console.log(`Locale sorter: no changes (${files.length} file(s) checked).`);
+ return;
+ }
+
+ console.log(
+ `Locale sorter: updated ${updated.length} file(s), left ${unchanged} unchanged.`
+ );
+}
+
+if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
+ main();
+}
diff --git a/frontend/scripts/sort_i18n_keys.test.mjs b/frontend/scripts/sort_i18n_keys.test.mjs
new file mode 100644
index 0000000000..f5f8365b24
--- /dev/null
+++ b/frontend/scripts/sort_i18n_keys.test.mjs
@@ -0,0 +1,240 @@
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, test } from "vitest";
+import {
+ checkLocaleFiles,
+ normalizeLocaleFile,
+ sortLocaleFiles,
+ sortObjectKeys,
+} from "./sort_i18n_keys.mjs";
+
+let tempDir = "";
+
+afterEach(() => {
+ if (tempDir) {
+ rmSync(tempDir, { recursive: true, force: true });
+ tempDir = "";
+ }
+});
+
+describe("sortObjectKeys", () => {
+ test("sorts nested object keys recursively and preserves arrays", () => {
+ expect(
+ sortObjectKeys({
+ z: "last",
+ a: {
+ d: "delta",
+ b: "bravo",
+ nested: {
+ c: "charlie",
+ a: "alpha",
+ },
+ },
+ m: ["keep", { y: 2, x: 1 }],
+ })
+ ).toEqual({
+ a: {
+ b: "bravo",
+ d: "delta",
+ nested: {
+ a: "alpha",
+ c: "charlie",
+ },
+ },
+ m: ["keep", { y: 2, x: 1 }],
+ z: "last",
+ });
+ });
+});
+
+describe("normalizeLocaleFile", () => {
+ test("rewrites files with stable 2-space JSON and trailing newline", () => {
+ tempDir = mkdtempSync(join(tmpdir(), "locale-sorter-"));
+ const filePath = join(tempDir, "en-US.json");
+ writeFileSync(filePath, '{"z":1,"a":{"d":4,"b":2},"m":[{"y":2,"x":1}]}');
+
+ expect(normalizeLocaleFile(filePath)).toBe(true);
+ expect(readFileSync(filePath, "utf-8")).toBe(
+ [
+ "{",
+ ' "a": {',
+ ' "b": 2,',
+ ' "d": 4',
+ " },",
+ ' "m": [',
+ " {",
+ ' "y": 2,',
+ ' "x": 1',
+ " }",
+ " ],",
+ ' "z": 1',
+ "}",
+ "",
+ ].join("\n")
+ );
+ });
+
+ test("does not rewrite already normalized files and fails fast on invalid JSON", () => {
+ tempDir = mkdtempSync(join(tmpdir(), "locale-sorter-"));
+ const validPath = join(tempDir, "ja-JP.json");
+ const invalidPath = join(tempDir, "broken.json");
+
+ const normalized = [
+ "{",
+ ' "a": {',
+ ' "b": 2,',
+ ' "d": 4',
+ " },",
+ ' "z": 1',
+ "}",
+ "",
+ ].join("\n");
+ writeFileSync(validPath, normalized);
+ writeFileSync(invalidPath, '{"a":');
+
+ expect(normalizeLocaleFile(validPath)).toBe(false);
+ expect(readFileSync(validPath, "utf-8")).toBe(normalized);
+ expect(() => normalizeLocaleFile(invalidPath)).toThrow(
+ /Failed to parse locale file .*broken\.json/
+ );
+ });
+
+ test("sortLocaleFiles validates every file before writing any change", () => {
+ const validPath = "/tmp/locale-sorter-valid.json";
+ const invalidPath = "/tmp/locale-sorter-invalid.json";
+ const writes = [];
+ const readStub = (filePath) => {
+ if (filePath === validPath) {
+ return '{"z":1,"a":2}';
+ }
+ if (filePath === invalidPath) {
+ return '{"a":';
+ }
+ throw new Error(`Unexpected file read: ${String(filePath)}`);
+ };
+ const writeStub = (...args) => {
+ writes.push(args);
+ };
+
+ expect(
+ () =>
+ sortLocaleFiles([validPath, invalidPath], {
+ readFileSync: readStub,
+ writeFileSync: writeStub,
+ })
+ ).toThrow(/Failed to parse locale file .*locale-sorter-invalid\.json/);
+ expect(writes).toEqual([]);
+ });
+
+ test("checkLocaleFiles reports unsorted files without writing", () => {
+ const sortedPath = "/tmp/locale-sorter-sorted.json";
+ const unsortedPath = "/tmp/locale-sorter-unsorted.json";
+ const writes = [];
+ const readStub = (filePath) => {
+ if (filePath === sortedPath) {
+ return '{\n "a": 1,\n "b": 2\n}\n';
+ }
+ if (filePath === unsortedPath) {
+ return '{"b":2,"a":1}';
+ }
+ throw new Error(`Unexpected file read: ${String(filePath)}`);
+ };
+ const writeStub = (...args) => {
+ writes.push(args);
+ };
+
+ expect(
+ checkLocaleFiles([sortedPath, unsortedPath], {
+ readFileSync: readStub,
+ writeFileSync: writeStub,
+ })
+ ).toEqual([unsortedPath]);
+ expect(writes).toEqual([]);
+ });
+
+ test("sortLocaleFiles rolls back earlier writes when a later write fails", () => {
+ const firstPath = "/tmp/locale-sorter-first.json";
+ const secondPath = "/tmp/locale-sorter-second.json";
+ const contents = new Map([
+ [firstPath, '{"z":1,"a":2}'],
+ [secondPath, '{"y":1,"b":2}'],
+ ]);
+ const writes = [];
+ const readStub = (filePath) => {
+ const content = contents.get(filePath);
+ if (content === undefined) {
+ throw new Error(`Unexpected file read: ${String(filePath)}`);
+ }
+ return content;
+ };
+ const writeStub = (filePath, content) => {
+ writes.push([filePath, content]);
+ if (filePath === secondPath && content.includes('"b": 2')) {
+ throw new Error("disk full");
+ }
+ contents.set(filePath, content);
+ };
+
+ expect(
+ () =>
+ sortLocaleFiles([firstPath, secondPath], {
+ readFileSync: readStub,
+ writeFileSync: writeStub,
+ })
+ ).toThrow(
+ /Failed to write locale file .*locale-sorter-second\.json: disk full\. Rolled back 1 earlier file\(s\) and restored the current file\./
+ );
+ expect(contents.get(firstPath)).toBe('{"z":1,"a":2}');
+ expect(contents.get(secondPath)).toBe('{"y":1,"b":2}');
+ expect(writes).toEqual([
+ [firstPath, '{\n "a": 2,\n "z": 1\n}\n'],
+ [secondPath, '{\n "b": 2,\n "y": 1\n}\n'],
+ [firstPath, '{"z":1,"a":2}'],
+ [secondPath, '{"y":1,"b":2}'],
+ ]);
+ });
+
+ test("sortLocaleFiles restores the current file after a partial write failure", () => {
+ const firstPath = "/tmp/locale-sorter-first.json";
+ const secondPath = "/tmp/locale-sorter-second.json";
+ const contents = new Map([
+ [firstPath, '{"z":1,"a":2}'],
+ [secondPath, '{"y":1,"b":2}'],
+ ]);
+ const writes = [];
+ const readStub = (filePath) => {
+ const content = contents.get(filePath);
+ if (content === undefined) {
+ throw new Error(`Unexpected file read: ${String(filePath)}`);
+ }
+ return content;
+ };
+ const writeStub = (filePath, content) => {
+ writes.push([filePath, content]);
+ if (filePath === secondPath && content.includes('"b": 2')) {
+ contents.set(filePath, '{"y":1');
+ throw new Error("write interrupted after partial flush");
+ }
+ contents.set(filePath, content);
+ };
+
+ expect(
+ () =>
+ sortLocaleFiles([firstPath, secondPath], {
+ readFileSync: readStub,
+ writeFileSync: writeStub,
+ })
+ ).toThrow(
+ /Failed to write locale file .*locale-sorter-second\.json: write interrupted after partial flush\. Rolled back 1 earlier file\(s\) and restored the current file\./
+ );
+ expect(contents.get(firstPath)).toBe('{"z":1,"a":2}');
+ expect(contents.get(secondPath)).toBe('{"y":1,"b":2}');
+ expect(writes).toEqual([
+ [firstPath, '{\n "a": 2,\n "z": 1\n}\n'],
+ [secondPath, '{\n "b": 2,\n "y": 1\n}\n'],
+ [firstPath, '{"z":1,"a":2}'],
+ [secondPath, '{"y":1,"b":2}'],
+ ]);
+ });
+});
diff --git a/frontend/src/react/locales/en-US.json b/frontend/src/react/locales/en-US.json
index 4bb4df2946..df02a9911f 100644
--- a/frontend/src/react/locales/en-US.json
+++ b/frontend/src/react/locales/en-US.json
@@ -170,6 +170,7 @@
"databases": "Databases",
"deactivate": "Deactivate",
"default": "Default",
+ "definition": "Definition",
"delete": "Delete",
"delete-resource": "Delete {{type}}",
"delete-resource-description": "Once you delete \"{{name}}\", there is no going back. Please be certain.",
@@ -337,15 +338,20 @@
"common.learn-more": "Learn more",
"common.load-more": "Load more",
"common.loading": "Loading",
+ "common.members": "Members",
"common.minutes": "Minutes",
"common.no-data": "No data",
+ "common.operation": "Operation",
"common.optional": "Optional",
"common.or": "or",
"common.overview": "Overview",
"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",
"common.show-more": "Show more",
"common.unknown": "Unknown",
@@ -355,6 +361,7 @@
"common.user": "User",
"common.username": "Username",
"common.value": "Value",
+ "common.version": "Version",
"common.warning": "Warning",
"common.write-only": "write only",
"create-db": {
@@ -506,13 +513,19 @@
"classification": {
"description": "Define classification levels to apply consistent masking policies across columns and databases."
},
+ "columns": "Columns",
+ "data-size": "Data size",
"edit-environment": "Edit Environment",
"edit-labels": "Edit Labels",
"engine": "Engine",
"expression": "Expression",
"filter-database": "Filter database",
+ "index-size": "Index size",
+ "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.",
+ "partitioned": "Partitioned",
+ "row-count-est": "Row count est.",
"select": "Select database",
"selected-n-databases": "{{n}} database(s) selected",
"successfully-transferred-databases": "Successfully transferred databases",
@@ -540,8 +553,10 @@
"with-diff": "With diff"
},
"sync-schema-button": "Sync Schema",
+ "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"
@@ -556,6 +571,8 @@
"select": "Select database group",
"unmatched-database": "Unmatched database"
},
+ "database.classification.self": "Classification",
+ "database.column": "Column",
"database.engine": "Engine",
"database.export-schema": "Export Schema",
"database.export-schema-multi-file": "Multi-File (ZIP)",
@@ -563,19 +580,38 @@
"database.failed-to-export-schema": "Failed to export schema",
"database.filter-database": "Filter database",
"database.labels": "Database Labels",
+ "database.revision.delete-confirm-dialog": "This will delete these applied revisions and the database schema will not be changed. This action cannot be undone.",
+ "database.revision.import-revision": "Import Revision",
+ "database.revision.invalid-version-format": "Version must be numeric parts separated by dots (e.g., 1.0.0)",
"database.revision.self": "Revision",
+ "database.revision.type-declarative": "Declarative",
+ "database.revision.type-versioned": "Versioned",
+ "database.revision.version-already-exists": "This version already exists in the database",
"database.successfully-exported-schema": "Successfully exported schema",
"database.sync-complete-for-instance": "Sync complete for instance '{{0}}'",
"database.sync-database": "Sync Database",
"db": {
"character-set": "Character set",
"collation": "Collation",
+ "collections": "Collections",
"encoding": "Encoding",
+ "extensions": "Extensions",
+ "external-tables": "External tables",
"failed-to-sync-schema": "Failed to sync schema",
+ "functions": "Functions",
"n-databases-had-sync-errors": "{{0}} database(s) had sync errors",
+ "packages": "Packages",
+ "schema": {
+ "default": "Default schema"
+ },
+ "sequences": "Sequences",
"start-to-sync-schema": "Start to sync schema",
+ "streams": "Streams",
"successfully-synced-schema": "Successfully synced schema",
- "syncing-databases-for-instance": "Syncing databases for {{0}}..."
+ "syncing-databases-for-instance": "Syncing databases for {{0}}...",
+ "tables": "Tables",
+ "tasks": "Tasks",
+ "views": "Views"
},
"db.failed-to-sync-schema": "Failed to sync schema",
"db.failed-to-sync-schema-for-database-database-value-name": "Failed to sync schema for database '{{0}}'.",
@@ -1725,6 +1761,7 @@
},
"grant-access": "Grant Access",
"never-expires": "Never expires",
+ "remove-sensitive-column-tips": "Remove the masking configuration from this sensitive column?",
"semantic-types": {
"label": "Columns having the same semantic type will use the same masking algorithms.",
"select": "Select semantic type",
diff --git a/frontend/src/react/locales/es-ES.json b/frontend/src/react/locales/es-ES.json
index b834dcf61b..ddaf5c233f 100644
--- a/frontend/src/react/locales/es-ES.json
+++ b/frontend/src/react/locales/es-ES.json
@@ -170,6 +170,7 @@
"databases": "Bases de datos",
"deactivate": "Desactivar",
"default": "Predeterminado",
+ "definition": "Definición",
"delete": "Eliminar",
"delete-resource": "Delete {{type}}",
"delete-resource-description": "Once you delete \"{{name}}\", there is no going back. Please be certain.",
@@ -337,15 +338,20 @@
"common.learn-more": "Aprender más",
"common.load-more": "Cargar más",
"common.loading": "Cargando",
+ "common.members": "Miembros",
"common.minutes": "Minutos",
"common.no-data": "Sin datos",
+ "common.operation": "Operación",
"common.optional": "Opcional",
"common.or": "o",
"common.overview": "Resumen",
"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",
"common.show-more": "Mostrar más",
"common.unknown": "Desconocido",
@@ -355,6 +361,7 @@
"common.user": "Usuario",
"common.username": "Nombre de usuario",
"common.value": "Valor",
+ "common.version": "Versión",
"common.warning": "Advertencia",
"common.write-only": "solo escritura",
"create-db": {
@@ -506,13 +513,19 @@
"classification": {
"description": "Define classification levels to apply consistent masking policies across columns and databases."
},
+ "columns": "Columnas",
+ "data-size": "Tamaño de datos",
"edit-environment": "Editar entorno",
"edit-labels": "Editar etiquetas",
"engine": "Motor",
"expression": "Expression",
"filter-database": "Filtrar base de datos",
+ "index-size": "Tamaño del índice",
+ "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.",
+ "partitioned": "Particionado",
+ "row-count-est": "Conteo estimado 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",
@@ -540,8 +553,10 @@
"with-diff": "With diff"
},
"sync-schema-button": "Sincronizar esquema",
+ "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"
@@ -556,6 +571,8 @@
"select": "Select database group",
"unmatched-database": "Unmatched database"
},
+ "database.classification.self": "Clasificación",
+ "database.column": "Columna",
"database.engine": "Motor",
"database.export-schema": "Exportar esquema",
"database.export-schema-multi-file": "Multi-archivo (ZIP)",
@@ -563,19 +580,38 @@
"database.failed-to-export-schema": "Error al exportar el esquema",
"database.filter-database": "Filtrar base de datos",
"database.labels": "Etiquetas de base de datos",
+ "database.revision.delete-confirm-dialog": "Esto eliminará las revisiones aplicadas y el esquema de la base de datos no se modificará. Esta acción no se puede deshacer.",
+ "database.revision.import-revision": "Revisión de importación",
+ "database.revision.invalid-version-format": "La versión debe tener partes numéricas separadas por puntos (por ejemplo, 1.0.0)",
"database.revision.self": "Revisión",
+ "database.revision.type-declarative": "Declarativo",
+ "database.revision.type-versioned": "Versionado",
+ "database.revision.version-already-exists": "Esta versión ya existe en la base de datos",
"database.successfully-exported-schema": "Esquema exportado correctamente",
"database.sync-complete-for-instance": "Sincronización completada para la instancia '{{0}}'",
"database.sync-database": "Sincronizar base de datos",
"db": {
"character-set": "Juego de caracteres",
"collation": "Colación",
+ "collections": "Colecciones",
"encoding": "Codificación",
+ "extensions": "Extensiones",
+ "external-tables": "Tablas externas",
"failed-to-sync-schema": "Error al sincronizar el esquema",
+ "functions": "Funciones",
"n-databases-had-sync-errors": "{{0}} base(s) de datos tuvieron errores de sincronización",
+ "packages": "Paquetes",
+ "schema": {
+ "default": "Esquema predeterminado"
+ },
+ "sequences": "Secuencias",
"start-to-sync-schema": "Comenzar a sincronizar el esquema",
+ "streams": "Streams",
"successfully-synced-schema": "Esquema sincronizado exitosamente",
- "syncing-databases-for-instance": "Sincronizando bases de datos para {{0}}..."
+ "syncing-databases-for-instance": "Sincronizando bases de datos para {{0}}...",
+ "tables": "Tablas",
+ "tasks": "Tareas",
+ "views": "Vistas"
},
"db.failed-to-sync-schema": "No se pudo sincronizar el esquema",
"db.failed-to-sync-schema-for-database-database-value-name": "Error al sincronizar el esquema para la base de datos '{{0}}'.",
@@ -1725,6 +1761,7 @@
},
"grant-access": "Autorizará el acceso",
"never-expires": "Nunca expira",
+ "remove-sensitive-column-tips": "¿Eliminar la configuración de enmascaramiento de esta columna sensible?",
"semantic-types": {
"label": "Las columnas que tengan el mismo tipo semántico utilizarán los mismos algoritmos de enmascaramiento.",
"select": "Seleccionar tipo semántico",
diff --git a/frontend/src/react/locales/ja-JP.json b/frontend/src/react/locales/ja-JP.json
index 8dc8950e57..c3c4ea1c13 100644
--- a/frontend/src/react/locales/ja-JP.json
+++ b/frontend/src/react/locales/ja-JP.json
@@ -170,6 +170,7 @@
"databases": "データベース",
"deactivate": "無効化",
"default": "デフォルト",
+ "definition": "定義",
"delete": "消去",
"delete-resource": "Delete {{type}}",
"delete-resource-description": "Once you delete \"{{name}}\", there is no going back. Please be certain.",
@@ -337,15 +338,20 @@
"common.learn-more": "もっと詳しく知る",
"common.load-more": "さらに読み込む",
"common.loading": "読み込み中",
+ "common.members": "メンバー",
"common.minutes": "分",
"common.no-data": "データなし",
+ "common.operation": "操作",
"common.optional": "オプション",
"common.or": "または",
"common.overview": "概要",
"common.password": "パスワード",
"common.project": "プロジェクト",
"common.read-only": "読み取り専用",
+ "common.remove": "削除",
+ "common.removed": "削除しました",
"common.restore": "復元する",
+ "common.rollout": "リリース",
"common.sensitive-placeholder": "機密データ - 書き込みのみ",
"common.show-more": "もっと見る",
"common.unknown": "不明",
@@ -355,6 +361,7 @@
"common.user": "ユーザー",
"common.username": "ユーザー名",
"common.value": "値",
+ "common.version": "バージョン",
"common.warning": "警告する",
"common.write-only": "書き込み専用",
"create-db": {
@@ -506,13 +513,19 @@
"classification": {
"description": "Define classification levels to apply consistent masking policies across columns and databases."
},
+ "columns": "カラム",
+ "data-size": "データサイズ",
"edit-environment": "環境の編集",
"edit-labels": "ラベルを編集",
"engine": "エンジン",
"expression": "Expression",
"filter-database": "データベースをフィルター",
+ "index-size": "インデックスサイズ",
+ "last-sync": "最後の同期",
"mixed-label-values": "混合値",
"mixed-label-values-warning": "選択されたリソースの一部は、同じキーに対して異なる値を持っています。これらのキーと値のペアを変更する場合にのみ編集してください。",
+ "partitioned": "パーティション",
+ "row-count-est": "推定行数",
"select": "データベースの選択",
"selected-n-databases": "{{n}} 個のデータベースが選択されました",
"successfully-transferred-databases": "データベースの転送に成功しました",
@@ -540,8 +553,10 @@
"with-diff": "With diff"
},
"sync-schema-button": "スキーマを同期",
+ "sync-status": "同期ステータス",
"sync-status-failed": "同期に失敗しました",
"transfer-project": "プロジェクトの転送",
+ "type": "タイプ",
"unassign": "割り当てを解除する",
"unassign-alert-description": "選択したデータベースがプロジェクトから削除されます",
"unassign-alert-title": "データベースの割り当てを解除する"
@@ -556,6 +571,8 @@
"select": "Select database group",
"unmatched-database": "Unmatched database"
},
+ "database.classification.self": "分類",
+ "database.column": "列",
"database.engine": "エンジン",
"database.export-schema": "スキーマをエクスポート",
"database.export-schema-multi-file": "複数ファイル (ZIP)",
@@ -563,19 +580,38 @@
"database.failed-to-export-schema": "スキーマのエクスポートに失敗しました",
"database.filter-database": "フィルターデータベース",
"database.labels": "データベースラベル",
+ "database.revision.delete-confirm-dialog": "これにより、適用されたリビジョンが削除され、データベース スキーマは変更されません。このアクションは元に戻せません。",
+ "database.revision.import-revision": "インポートリビジョン",
+ "database.revision.invalid-version-format": "バージョンはドットで区切られた数字部分でなければなりません(例:1.0.0)",
"database.revision.self": "リビジョン",
+ "database.revision.type-declarative": "宣言的",
+ "database.revision.type-versioned": "バージョン管理",
+ "database.revision.version-already-exists": "このバージョンは既にデータベースに存在します",
"database.successfully-exported-schema": "スキーマのエクスポートに成功しました",
"database.sync-complete-for-instance": "インスタンス '{{0}}' の同期が完了しました",
"database.sync-database": "データベースを同期",
"db": {
"character-set": "文字セット",
"collation": "照合順序",
+ "collections": "コレクション",
"encoding": "エンコーディング",
+ "extensions": "拡張機能",
+ "external-tables": "外部テーブル",
"failed-to-sync-schema": "スキーマの同期に失敗しました",
+ "functions": "関数",
"n-databases-had-sync-errors": "{{0}} 個のデータベースで同期エラーが発生しました",
+ "packages": "パッケージ",
+ "schema": {
+ "default": "デフォルトスキーマ"
+ },
+ "sequences": "シーケンス",
"start-to-sync-schema": "スキーマの同期を開始します",
+ "streams": "ストリーム",
"successfully-synced-schema": "スキーマの同期に成功しました",
- "syncing-databases-for-instance": "{{0}} のデータベースを同期中..."
+ "syncing-databases-for-instance": "{{0}} のデータベースを同期中...",
+ "tables": "テーブル",
+ "tasks": "タスク",
+ "views": "ビュー"
},
"db.failed-to-sync-schema": "スキーマの同期に失敗しました",
"db.failed-to-sync-schema-for-database-database-value-name": "データベース '{{0}}' のスキーマを同期できませんでした。",
@@ -1725,6 +1761,7 @@
},
"grant-access": "許可されたアクセス",
"never-expires": "有効期限なし",
+ "remove-sensitive-column-tips": "この機密列からマスキング設定を削除しますか?",
"semantic-types": {
"label": "同じセマンティック タイプの列は、同じマスキング アルゴリズムを使用します。",
"select": "セマンティックタイプの選択",
diff --git a/frontend/src/react/locales/vi-VN.json b/frontend/src/react/locales/vi-VN.json
index da23e8b0d4..4be7b09724 100644
--- a/frontend/src/react/locales/vi-VN.json
+++ b/frontend/src/react/locales/vi-VN.json
@@ -170,6 +170,7 @@
"databases": "Cơ sở dữ liệu",
"deactivate": "Hủy kích hoạt",
"default": "Mặc định",
+ "definition": "Định nghĩa",
"delete": "Xóa",
"delete-resource": "Delete {{type}}",
"delete-resource-description": "Once you delete \"{{name}}\", there is no going back. Please be certain.",
@@ -337,15 +338,20 @@
"common.learn-more": "Tìm hiểu thêm",
"common.load-more": "Tải thêm",
"common.loading": "Đang tải",
+ "common.members": "Thành viên",
"common.minutes": "Phút",
"common.no-data": "Không có dữ liệu",
+ "common.operation": "Thao tác",
"common.optional": "Tùy chọn",
"common.or": "hoặc",
"common.overview": "Tổng quan",
"common.password": "Mật khẩu",
"common.project": "Dự án",
"common.read-only": "Chỉ đọc",
+ "common.remove": "Xóa",
+ "common.removed": "Đã xóa",
"common.restore": "Khôi phục",
+ "common.rollout": "Triển khai",
"common.sensitive-placeholder": "Nhạy cảm - Chỉ ghi",
"common.show-more": "Hiển thị thêm",
"common.unknown": "Không xác định",
@@ -355,6 +361,7 @@
"common.user": "Người dùng",
"common.username": "Tên người dùng",
"common.value": "Giá trị",
+ "common.version": "Phiên bản",
"common.warning": "Cảnh báo",
"common.write-only": "chỉ ghi",
"create-db": {
@@ -506,13 +513,19 @@
"classification": {
"description": "Define classification levels to apply consistent masking policies across columns and databases."
},
+ "columns": "Cột",
+ "data-size": "Kích thước dữ liệu",
"edit-environment": "Chỉnh sửa Môi trường",
"edit-labels": "Chỉnh sửa nhãn",
"engine": "Engine",
"expression": "Expression",
"filter-database": "Lọc cơ sở dữ liệu",
+ "index-size": "Kích thước 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.",
+ "partitioned": "Đã phân vùng",
+ "row-count-est": "Ướ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",
@@ -540,8 +553,10 @@
"with-diff": "With diff"
},
"sync-schema-button": "Đồng bộ lược đồ",
+ "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"
@@ -556,6 +571,8 @@
"select": "Select database group",
"unmatched-database": "Unmatched database"
},
+ "database.classification.self": "Phân loại",
+ "database.column": "Cột",
"database.engine": "Engine",
"database.export-schema": "Xuất schema",
"database.export-schema-multi-file": "Nhiều tệp (ZIP)",
@@ -563,19 +580,38 @@
"database.failed-to-export-schema": "Không thể xuất schema",
"database.filter-database": "Lọc cơ sở dữ liệu",
"database.labels": "Nhãn cơ sở dữ liệu",
+ "database.revision.delete-confirm-dialog": "Thao tác này sẽ xóa các bản sửa đổi đã áp dụng này và lược đồ cơ sở dữ liệu sẽ không bị thay đổi. Hành động này không thể hoàn tác.",
+ "database.revision.import-revision": "Nhập bản sửa đổi",
+ "database.revision.invalid-version-format": "Phiên bản phải là các phần số được phân tách bằng dấu chấm (ví dụ: 1.0.0)",
"database.revision.self": "Phiên bản",
+ "database.revision.type-declarative": "Khai báo",
+ "database.revision.type-versioned": "Phiên bản",
+ "database.revision.version-already-exists": "Phiên bản này đã tồn tại trong cơ sở dữ liệu",
"database.successfully-exported-schema": "Đã xuất schema thành công",
"database.sync-complete-for-instance": "Đồng bộ hoàn tất cho instance '{{0}}'",
"database.sync-database": "Đồng bộ cơ sở dữ liệu",
"db": {
"character-set": "Bộ ký tự",
"collation": "Đối chiếu",
+ "collections": "Bộ sưu tập",
"encoding": "Mã hóa",
+ "extensions": "Tiện ích mở rộng",
+ "external-tables": "Bảng ngoài",
"failed-to-sync-schema": "Đồng bộ hóa lược đồ thất bại",
+ "functions": "Hàm",
"n-databases-had-sync-errors": "{{0}} cơ sở dữ liệu gặp lỗi đồng bộ",
+ "packages": "Gói",
+ "schema": {
+ "default": "Schema mặc định"
+ },
+ "sequences": "Chuỗi",
"start-to-sync-schema": "Bắt đầu đồng bộ hóa lược đồ",
+ "streams": "Luồng",
"successfully-synced-schema": "Đồng bộ hóa lược đồ thành công",
- "syncing-databases-for-instance": "Đang đồng bộ hóa cơ sở dữ liệu cho {{0}}..."
+ "syncing-databases-for-instance": "Đang đồng bộ hóa cơ sở dữ liệu cho {{0}}...",
+ "tables": "Bảng",
+ "tasks": "Tác vụ",
+ "views": "Khung nhìn"
},
"db.failed-to-sync-schema": "Không đồng bộ hóa được lược đồ",
"db.failed-to-sync-schema-for-database-database-value-name": "Không đồng bộ hóa được lược đồ cho cơ sở dữ liệu '{{0}}'.",
@@ -1725,6 +1761,7 @@
},
"grant-access": "Cấp quyền truy cập",
"never-expires": "Không bao giờ hết hạn",
+ "remove-sensitive-column-tips": "Xóa cấu hình che dữ liệu khỏi cột nhạy cảm này?",
"semantic-types": {
"label": "Các cột có cùng loại ngữ nghĩa sẽ sử dụng cùng một thuật toán che.",
"select": "Chọn loại ngữ nghĩa",
diff --git a/frontend/src/react/locales/zh-CN.json b/frontend/src/react/locales/zh-CN.json
index 8772a19940..1deea4887a 100644
--- a/frontend/src/react/locales/zh-CN.json
+++ b/frontend/src/react/locales/zh-CN.json
@@ -170,6 +170,7 @@
"databases": "数据库",
"deactivate": "禁用",
"default": "默认",
+ "definition": "定义",
"delete": "删除",
"delete-resource": "删除{{type}}",
"delete-resource-description": "删除「{{name}}」后将无法恢复,请确认。",
@@ -337,15 +338,20 @@
"common.learn-more": "了解更多",
"common.load-more": "加载更多",
"common.loading": "加载中",
+ "common.members": "成员",
"common.minutes": "分钟",
"common.no-data": "无数据",
+ "common.operation": "操作",
"common.optional": "可选",
"common.or": "或者",
"common.overview": "概览",
"common.password": "密码",
"common.project": "项目",
"common.read-only": "只读",
+ "common.remove": "移除",
+ "common.removed": "已移除",
"common.restore": "恢复",
+ "common.rollout": "发布",
"common.sensitive-placeholder": "敏感数据 - 仅写入",
"common.show-more": "显示更多",
"common.unknown": "未知",
@@ -355,6 +361,7 @@
"common.user": "用户",
"common.username": "用户名",
"common.value": "值",
+ "common.version": "版本",
"common.warning": "警告",
"common.write-only": "仅写入",
"create-db": {
@@ -506,13 +513,19 @@
"classification": {
"description": "定义分类分级,跨列和数据库统一应用脱敏策略。"
},
+ "columns": "列",
+ "data-size": "数据大小",
"edit-environment": "编辑环境",
"edit-labels": "编辑标签",
"engine": "引擎",
"expression": "Expression",
"filter-database": "筛选数据库",
+ "index-size": "索引大小",
+ "last-sync": "最后一次同步",
"mixed-label-values": "混合值",
"mixed-label-values-warning": "部分标签拥有不同的值,编辑标签将会批量应用。仅在您打算更改时再编辑这些键值对。",
+ "partitioned": "分区",
+ "row-count-est": "估算行数",
"select": "选择数据库",
"selected-n-databases": "已选择 {{n}} 个数据库",
"successfully-transferred-databases": "成功转移数据库",
@@ -540,8 +553,10 @@
"with-diff": "有差异"
},
"sync-schema-button": "同步 Schema",
+ "sync-status": "同步状态",
"sync-status-failed": "同步失败",
"transfer-project": "转移项目",
+ "type": "类型",
"unassign": "取消分配",
"unassign-alert-description": "选定的数据库将从项目中移除",
"unassign-alert-title": "取消分配数据库"
@@ -556,6 +571,8 @@
"select": "Select database group",
"unmatched-database": "Unmatched database"
},
+ "database.classification.self": "分类",
+ "database.column": "列",
"database.engine": "引擎",
"database.export-schema": "导出 Schema",
"database.export-schema-multi-file": "多文件 (ZIP)",
@@ -563,19 +580,38 @@
"database.failed-to-export-schema": "导出 Schema 失败",
"database.filter-database": "过滤数据库",
"database.labels": "数据库标签",
+ "database.revision.delete-confirm-dialog": "这将删除这些已应用的修改,但不会影响数据库 Schema。此操作无法撤消。",
+ "database.revision.import-revision": "导入版本",
+ "database.revision.invalid-version-format": "版本必须是用点分隔的数字部分(例如,1.0.0)",
"database.revision.self": "版本",
+ "database.revision.type-declarative": "声明式",
+ "database.revision.type-versioned": "版本化",
+ "database.revision.version-already-exists": "此版本已存在于数据库中",
"database.successfully-exported-schema": "成功导出 Schema",
"database.sync-complete-for-instance": "实例 '{{0}}' 同步完成",
"database.sync-database": "同步数据库",
"db": {
"character-set": "字符集",
"collation": "排序规则",
+ "collections": "集合",
"encoding": "编码",
+ "extensions": "扩展",
+ "external-tables": "外部表",
"failed-to-sync-schema": "同步 schema 失败",
+ "functions": "函数",
"n-databases-had-sync-errors": "{{0}} 个数据库同步出错",
+ "packages": "包",
+ "schema": {
+ "default": "默认 Schema"
+ },
+ "sequences": "序列",
"start-to-sync-schema": "开始同步 schema",
+ "streams": "流",
"successfully-synced-schema": "成功同步 schema",
- "syncing-databases-for-instance": "正在同步 {{0}} 的数据库..."
+ "syncing-databases-for-instance": "正在同步 {{0}} 的数据库...",
+ "tables": "表",
+ "tasks": "任务",
+ "views": "视图"
},
"db.failed-to-sync-schema": "同步 schema 失败",
"db.failed-to-sync-schema-for-database-database-value-name": "为数据库 '{{0}}' 同步 schema 失败。",
@@ -1725,6 +1761,7 @@
},
"grant-access": "授权访问",
"never-expires": "无过期时间",
+ "remove-sensitive-column-tips": "要移除此敏感列上的脱敏配置吗?",
"semantic-types": {
"label": "具有相同语义类型的列会使用相同的脱敏算法。",
"select": "选择语义类型",
diff --git a/frontend/src/react/pages/project/ProjectDatabaseDetailPage.test.tsx b/frontend/src/react/pages/project/ProjectDatabaseDetailPage.test.tsx
index 95781cdcab..b5ccd04557 100644
--- a/frontend/src/react/pages/project/ProjectDatabaseDetailPage.test.tsx
+++ b/frontend/src/react/pages/project/ProjectDatabaseDetailPage.test.tsx
@@ -133,7 +133,9 @@ const mocks = vi.hoisted(() => {
})),
useDBSchemaV1Store: vi.fn(() => ({
getOrFetchDatabaseMetadata: vi.fn(),
- getDatabaseMetadata: vi.fn(() => undefined),
+ getDatabaseMetadata: vi.fn(() => undefined as unknown),
+ getSchemaList: vi.fn(() => [] as unknown[]),
+ getTableList: vi.fn(() => [] as unknown[]),
})),
usePermissionStore: vi.fn(() => ({
currentPermissions: new Set([
@@ -478,7 +480,9 @@ beforeEach(() => {
mocks.useDBSchemaV1Store.mockReset();
mocks.useDBSchemaV1Store.mockReturnValue({
getOrFetchDatabaseMetadata: vi.fn(),
- getDatabaseMetadata: vi.fn(() => undefined),
+ getDatabaseMetadata: vi.fn(() => undefined as unknown),
+ getSchemaList: vi.fn(() => [] as unknown[]),
+ getTableList: vi.fn(() => [] as unknown[]),
});
mocks.usePermissionStore.mockReset();
mocks.usePermissionStore.mockReturnValue({
@@ -781,6 +785,18 @@ describe("ProjectDatabaseDetailPage", () => {
});
test("renders the header metadata and top-level action cluster", async () => {
+ mocks.useDBSchemaV1Store.mockReturnValue({
+ getOrFetchDatabaseMetadata: vi.fn(),
+ getDatabaseMetadata: vi.fn(() => ({
+ schemas: [
+ {
+ name: "public",
+ },
+ ],
+ })),
+ getSchemaList: vi.fn(() => [{ name: "public" }]),
+ getTableList: vi.fn(() => [{ name: "book" }, { name: "orders" }]),
+ });
mocks.useProjectDatabaseDetail.mockReturnValue({
database: {
name: "instances/inst1/databases/db1",
diff --git a/frontend/src/react/pages/project/database-detail/DatabaseDetailHeader.tsx b/frontend/src/react/pages/project/database-detail/DatabaseDetailHeader.tsx
index c86587770a..8e61b1b626 100644
--- a/frontend/src/react/pages/project/database-detail/DatabaseDetailHeader.tsx
+++ b/frontend/src/react/pages/project/database-detail/DatabaseDetailHeader.tsx
@@ -5,7 +5,7 @@ import { Button } from "@/react/components/ui/button";
import type { Database } from "@/types/proto-es/v1/database_service_pb";
import { extractReleaseUID } from "@/utils/v1/release";
import { DatabaseSQLEditorButton } from "./DatabaseSQLEditorButton";
-import { SchemaDiagramButtonBridge } from "./SchemaDiagramButtonBridge";
+import { SchemaBrowserButton } from "./schema-browser/SchemaBrowserButton";
const extractDatabaseParts = (resource: string) => {
const matches = resource.match(
@@ -97,7 +97,7 @@ export function DatabaseDetailHeader({
database={database}
onFailed={onSQLEditorFailed}
/>
- {allowAlterSchema && <SchemaDiagramButtonBridge database={database} />}
+ {allowAlterSchema && <SchemaBrowserButton database={database} />}
</div>
</div>
);
diff --git a/frontend/src/react/pages/project/database-detail/SchemaDiagramButtonBridge.tsx b/frontend/src/react/pages/project/database-detail/SchemaDiagramButtonBridge.tsx
deleted file mode 100644
index 766e04e36a..0000000000
--- a/frontend/src/react/pages/project/database-detail/SchemaDiagramButtonBridge.tsx
+++ /dev/null
@@ -1,88 +0,0 @@
-import { Workflow } from "lucide-react";
-import { useCallback, useEffect, useRef, useState } from "react";
-import { useTranslation } from "react-i18next";
-import { createApp, h } from "vue";
-import SchemaDiagram from "@/components/SchemaDiagram";
-import highlight from "@/plugins/highlight";
-import i18n from "@/plugins/i18n";
-import NaiveUI from "@/plugins/naive-ui";
-import { Button } from "@/react/components/ui/button";
-import {
- Dialog,
- DialogContent,
- DialogTitle,
-} from "@/react/components/ui/dialog";
-import { pinia, useDBSchemaV1Store } from "@/store";
-import type { Database } from "@/types/proto-es/v1/database_service_pb";
-
-function VueSchemaDiagramMount({ database }: { database: Database }) {
- const containerRef = useRef<HTMLDivElement>(null);
- const dbSchemaStore = useDBSchemaV1Store();
-
- useEffect(() => {
- if (!containerRef.current) {
- return;
- }
-
- const app = createApp({
- render() {
- return h(SchemaDiagram as never, {
- database,
- databaseMetadata: dbSchemaStore.getDatabaseMetadata(database.name),
- });
- },
- });
- app.use(pinia).use(highlight).use(i18n).use(NaiveUI);
- app.mount(containerRef.current);
-
- return () => {
- app.unmount();
- };
- }, [database, dbSchemaStore]);
-
- return <div className="h-[70vh] w-[80vw]" ref={containerRef} />;
-}
-
-export function SchemaDiagramButtonBridge({
- database,
- disabled = false,
-}: {
- database: Database;
- disabled?: boolean;
-}) {
- const { t } = useTranslation();
- const dbSchemaStore = useDBSchemaV1Store();
- const [open, setOpen] = useState(false);
-
- const handleOpen = useCallback(async () => {
- if (disabled) {
- return;
- }
-
- await dbSchemaStore.getOrFetchDatabaseMetadata({
- database: database.name,
- skipCache: false,
- });
- setOpen(true);
- }, [database, dbSchemaStore, disabled]);
-
- return (
- <>
- <Button
- variant="ghost"
- size="sm"
- disabled={disabled}
- onClick={() => void handleOpen()}
- >
- <Workflow className="h-4 w-4" />
- {t("schema-diagram.self")}
- </Button>
- <Dialog open={open} onOpenChange={setOpen}>
- <DialogContent className="max-w-fit p-4">
- <DialogTitle>{t("schema-diagram.self")}</DialogTitle>
- {open && <VueSchemaDiagramMount database={database} />}
- </DialogContent>
- </Dialog>
- </>
- );
-}
diff --git a/frontend/src/react/pages/project/database-detail/catalog/GrantAccessDialog.tsx b/frontend/src/react/pages/project/database-detail/catalog/GrantAccessDialog.tsx
new file mode 100644
index 0000000000..f7496ea924
--- /dev/null
+++ b/frontend/src/react/pages/project/database-detail/catalog/GrantAccessDialog.tsx
@@ -0,0 +1,238 @@
+import { create } from "@bufbuild/protobuf";
+import dayjs from "dayjs";
+import { useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { rewriteResourceDatabase } from "@/components/SensitiveData/exemptionDataUtils";
+import type { SensitiveColumn } from "@/components/SensitiveData/types";
+import {
+ convertSensitiveColumnToDatabaseResource,
+ getExpressionsForDatabaseResource,
+} from "@/components/SensitiveData/utils";
+import { AccountMultiSelect } from "@/react/components/AccountMultiSelect";
+import { Button } from "@/react/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogTitle,
+} from "@/react/components/ui/dialog";
+import { ExpirationPicker } from "@/react/components/ui/expiration-picker";
+import { Input } from "@/react/components/ui/input";
+import { pushNotification, usePolicyV1Store } from "@/store";
+import type { DatabaseResource } from "@/types";
+import { ExprSchema } from "@/types/proto-es/google/type/expr_pb";
+import {
+ MaskingExemptionPolicy_ExemptionSchema,
+ MaskingExemptionPolicySchema,
+ PolicyResourceType,
+ PolicyType,
+} from "@/types/proto-es/v1/org_policy_service_pb";
+
+export interface GrantAccessDialogProps {
+ columnList: SensitiveColumn[];
+ open: boolean;
+ projectName: string;
+ onDismiss: () => void;
+}
+
+export function GrantAccessDialog({
+ columnList,
+ open,
+ projectName,
+ onDismiss,
+}: GrantAccessDialogProps) {
+ const { t } = useTranslation();
+ const policyStore = usePolicyV1Store();
+
+ const databaseResources = useMemo<DatabaseResource[]>(
+ () => columnList.map(convertSensitiveColumnToDatabaseResource),
+ [columnList]
+ );
+ const [description, setDescription] = useState("");
+ const [expirationTimestamp, setExpirationTimestamp] = useState<
+ string | undefined
+ >();
+ const [memberList, setMemberList] = useState<string[]>([]);
+ const [processing, setProcessing] = useState(false);
+
+ const minDatetime = useMemo(
+ () => dayjs().startOf("day").format("YYYY-MM-DDTHH:mm"),
+ []
+ );
+ const submitDisabled =
+ memberList.length === 0 || databaseResources.length === 0;
+
+ const handleOpenChange = (nextOpen: boolean) => {
+ if (!nextOpen) {
+ onDismiss();
+ }
+ };
+
+ const handleSubmit = async () => {
+ if (submitDisabled || processing) {
+ return;
+ }
+ setProcessing(true);
+
+ try {
+ const extraExpressions: string[] = [];
+ if (expirationTimestamp) {
+ extraExpressions.push(
+ `request.time < timestamp("${new Date(expirationTimestamp).toISOString()}")`
+ );
+ }
+
+ const resourceExpressions = databaseResources
+ .map(getExpressionsForDatabaseResource)
+ .map((parts) => parts.filter((part) => part).join(" && "));
+ const nonEmptyResourceExpressions = resourceExpressions.filter(
+ (expression) => expression
+ );
+
+ let resourceCondition = "";
+ if (nonEmptyResourceExpressions.length === 1) {
+ resourceCondition = nonEmptyResourceExpressions[0];
+ } else if (nonEmptyResourceExpressions.length > 1) {
+ resourceCondition = nonEmptyResourceExpressions
+ .map((expression) => `(${expression})`)
+ .join(" || ");
+ }
+
+ const expression = rewriteResourceDatabase(
+ [resourceCondition, ...extraExpressions]
+ .filter((part) => part)
+ .join(" && ")
+ );
+
+ const policy = await policyStore.getOrFetchPolicyByParentAndType({
+ parentPath: projectName,
+ policyType: PolicyType.MASKING_EXEMPTION,
+ });
+ const existed =
+ policy?.policy?.case === "maskingExemptionPolicy"
+ ? policy.policy.value.exemptions
+ : [];
+
+ await policyStore.upsertPolicy({
+ parentPath: projectName,
+ policy: {
+ name: policy?.name,
+ type: PolicyType.MASKING_EXEMPTION,
+ resourceType: PolicyResourceType.PROJECT,
+ policy: {
+ case: "maskingExemptionPolicy",
+ value: create(MaskingExemptionPolicySchema, {
+ exemptions: [
+ ...existed,
+ create(MaskingExemptionPolicy_ExemptionSchema, {
+ members: memberList,
+ condition: create(ExprSchema, {
+ description,
+ expression,
+ }),
+ }),
+ ],
+ }),
+ },
+ },
+ });
+
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.created"),
+ });
+ onDismiss();
+ } catch (error) {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: `${error}`,
+ });
+ } finally {
+ setProcessing(false);
+ }
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={handleOpenChange}>
+ <DialogContent className="max-w-4xl p-6">
+ <DialogTitle>{t("settings.sensitive-data.grant-access")}</DialogTitle>
+ <div className="mt-4 flex flex-col gap-y-6">
+ <div className="flex flex-col gap-y-2">
+ <span className="text-sm font-medium text-main">
+ {t("common.resources")}
+ </span>
+ <div className="max-h-60 overflow-y-auto rounded-sm border border-control-border">
+ {databaseResources.map((resource) => (
+ <div
+ key={[
+ resource.databaseFullName,
+ resource.schema ?? "",
+ resource.table ?? "",
+ (resource.columns ?? []).join(","),
+ ].join("/")}
+ className="border-b border-control-border px-3 py-2 text-sm last:border-b-0"
+ >
+ {[
+ resource.databaseFullName.split("/").pop(),
+ resource.schema,
+ resource.table,
+ ...(resource.columns ?? []),
+ ]
+ .filter(Boolean)
+ .join(".")}
+ </div>
+ ))}
+ </div>
+ </div>
+
+ <div className="flex flex-col gap-y-2">
+ <span className="text-sm font-medium text-main">
+ {t("common.reason")}
+ </span>
+ <Input
+ value={description}
+ placeholder={t("common.description")}
+ onChange={(event) => setDescription(event.target.value)}
+ />
+ </div>
+
+ <div className="flex flex-col gap-y-2">
+ <span className="text-sm font-medium text-main">
+ {t("common.expiration")}
+ </span>
+ <ExpirationPicker
+ value={expirationTimestamp}
+ minDate={minDatetime}
+ onChange={setExpirationTimestamp}
+ />
+ {!expirationTimestamp && (
+ <span className="text-sm text-control-light">
+ {t("settings.sensitive-data.never-expires")}
+ </span>
+ )}
+ </div>
+
+ <div className="flex flex-col gap-y-2">
+ <span className="text-sm font-medium text-main">
+ {t("common.members")}
+ </span>
+ <AccountMultiSelect value={memberList} onChange={setMemberList} />
+ </div>
+ </div>
+
+ <div className="mt-6 flex justify-end gap-x-2">
+ <Button variant="outline" onClick={onDismiss}>
+ {t("common.cancel")}
+ </Button>
+ <Button
+ disabled={submitDisabled || processing}
+ onClick={() => void handleSubmit()}
+ >
+ {t("common.confirm")}
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/frontend/src/react/pages/project/database-detail/catalog/SensitiveColumnTable.tsx b/frontend/src/react/pages/project/database-detail/catalog/SensitiveColumnTable.tsx
new file mode 100644
index 0000000000..7dbc4f0db7
--- /dev/null
+++ b/frontend/src/react/pages/project/database-detail/catalog/SensitiveColumnTable.tsx
@@ -0,0 +1,203 @@
+import { Trash2 } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import type { MaskData } from "@/components/SensitiveData/types";
+import { getMaskDataIdentifier } from "@/components/SensitiveData/utils";
+import { Button } from "@/react/components/ui/button";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/react/components/ui/select";
+
+interface Option {
+ label: string;
+ value: string;
+}
+
+export interface SensitiveColumnTableProps {
+ checkedColumnList: MaskData[];
+ columnList: MaskData[];
+ classificationOptions: Option[];
+ rowSelectable: boolean;
+ semanticTypeOptions: Option[];
+ showOperation: boolean;
+ onClassificationChange: (item: MaskData, classificationId: string) => void;
+ onCheckedColumnListChange: (list: MaskData[]) => void;
+ onDelete: (item: MaskData) => void | Promise<void>;
+ onSemanticTypeChange: (item: MaskData, semanticTypeId: string) => void;
+}
+
+export function SensitiveColumnTable({
+ checkedColumnList,
+ columnList,
+ classificationOptions,
+ rowSelectable,
+ semanticTypeOptions,
+ showOperation,
+ onClassificationChange,
+ onCheckedColumnListChange,
+ onDelete,
+ onSemanticTypeChange,
+}: SensitiveColumnTableProps) {
+ const { t } = useTranslation();
+ const checkedSet = new Set(checkedColumnList.map(getMaskDataIdentifier));
+
+ const toggleChecked = (item: MaskData, checked: boolean) => {
+ const key = getMaskDataIdentifier(item);
+ if (checked) {
+ onCheckedColumnListChange(
+ checkedColumnList.some((row) => getMaskDataIdentifier(row) === key)
+ ? checkedColumnList
+ : [...checkedColumnList, item]
+ );
+ return;
+ }
+ onCheckedColumnListChange(
+ checkedColumnList.filter((row) => getMaskDataIdentifier(row) !== key)
+ );
+ };
+
+ const handleDelete = async (item: MaskData) => {
+ if (
+ typeof window !== "undefined" &&
+ typeof window.confirm === "function" &&
+ !window.confirm(t("settings.sensitive-data.remove-sensitive-column-tips"))
+ ) {
+ return;
+ }
+ await onDelete(item);
+ };
+
+ return (
+ <div className="overflow-x-auto rounded-sm border border-control-border">
+ <table className="w-full min-w-[720px] text-sm">
+ <thead>
+ <tr className="border-b border-control-border bg-gray-50 text-left">
+ {rowSelectable && <th className="w-12 px-4 py-2" />}
+ <th className="px-4 py-2 font-medium">{t("common.table")}</th>
+ <th className="px-4 py-2 font-medium">{t("database.column")}</th>
+ <th className="px-4 py-2 font-medium">
+ {t("settings.sensitive-data.semantic-types.table.semantic-type")}
+ </th>
+ <th className="px-4 py-2 font-medium">
+ {t("database.classification.self")}
+ </th>
+ {showOperation && (
+ <th className="w-20 px-4 py-2 font-medium">
+ {t("common.operation")}
+ </th>
+ )}
+ </tr>
+ </thead>
+ <tbody>
+ {columnList.map((item) => {
+ const key = getMaskDataIdentifier(item);
+ const tableName = item.schema
+ ? `${item.schema}.${item.table}`
+ : item.table;
+ return (
+ <tr
+ key={key}
+ className="border-b border-control-border last:border-0"
+ >
+ {rowSelectable && (
+ <td className="px-4 py-3">
+ <input
+ type="checkbox"
+ checked={checkedSet.has(key)}
+ onChange={(event) =>
+ toggleChecked(item, event.target.checked)
+ }
+ />
+ </td>
+ )}
+ <td className="px-4 py-3">{tableName}</td>
+ <td className="px-4 py-3">{item.column || "-"}</td>
+ <td className="px-4 py-3">
+ {showOperation && !item.disableSemanticType ? (
+ <Select
+ value={item.semanticTypeId}
+ onValueChange={(value) =>
+ onSemanticTypeChange(item, value ?? "")
+ }
+ >
+ <SelectTrigger className="w-full min-w-40">
+ <SelectValue placeholder={t("common.empty")} />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="">{t("common.empty")}</SelectItem>
+ {semanticTypeOptions.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ ) : (
+ item.semanticTypeId || "-"
+ )}
+ </td>
+ <td className="px-4 py-3">
+ {showOperation && !item.disableClassification ? (
+ <Select
+ value={item.classificationId}
+ onValueChange={(value) =>
+ onClassificationChange(item, value ?? "")
+ }
+ >
+ <SelectTrigger className="w-full min-w-40">
+ <SelectValue placeholder={t("common.empty")} />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="">{t("common.empty")}</SelectItem>
+ {classificationOptions.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ ) : (
+ item.classificationId || "-"
+ )}
+ </td>
+ {showOperation && (
+ <td className="px-4 py-3">
+ <Button
+ variant="ghost"
+ size="icon"
+ aria-label={t("common.remove")}
+ onClick={() => void handleDelete(item)}
+ >
+ <Trash2 className="h-4 w-4" />
+ </Button>
+ </td>
+ )}
+ </tr>
+ );
+ })}
+ {columnList.length === 0 && (
+ <tr>
+ <td
+ className="px-4 py-6 text-center text-control-light"
+ colSpan={
+ rowSelectable
+ ? showOperation
+ ? 6
+ : 5
+ : showOperation
+ ? 5
+ : 4
+ }
+ >
+ {t("common.no-data")}
+ </td>
+ </tr>
+ )}
+ </tbody>
+ </table>
+ </div>
+ );
+}
diff --git a/frontend/src/react/pages/project/database-detail/changelog/DatabaseChangelogTable.tsx b/frontend/src/react/pages/project/database-detail/changelog/DatabaseChangelogTable.tsx
new file mode 100644
index 0000000000..e18d5548a6
--- /dev/null
+++ b/frontend/src/react/pages/project/database-detail/changelog/DatabaseChangelogTable.tsx
@@ -0,0 +1,61 @@
+import { useTranslation } from "react-i18next";
+import { router } from "@/router";
+import { getDateForPbTimestampProtoEs } from "@/types";
+import type { Changelog } from "@/types/proto-es/v1/database_service_pb";
+import { humanizeDate } from "@/utils";
+import { changelogLink } from "@/utils/v1/changelog";
+
+export function DatabaseChangelogTable({
+ changelogs,
+ loading,
+}: {
+ changelogs: Changelog[];
+ loading: boolean;
+}) {
+ const { t } = useTranslation();
+
+ if (loading) {
+ return (
+ <div className="text-sm text-control-light">{t("common.loading")}</div>
+ );
+ }
+
+ 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">
+ <th className="px-4 py-2 font-medium">{t("common.name")}</th>
+ <th className="px-4 py-2 font-medium">{t("common.created-at")}</th>
+ <th className="px-4 py-2 font-medium">{t("common.rollout")}</th>
+ </tr>
+ </thead>
+ <tbody className="divide-y divide-block-border bg-white">
+ {changelogs.map((changelog) => (
+ <tr key={changelog.name}>
+ <td className="px-4 py-3 text-sm text-main">
+ <button
+ className="cursor-pointer text-left hover:text-accent"
+ type="button"
+ onClick={() => void router.push(changelogLink(changelog))}
+ >
+ {changelog.name}
+ </button>
+ </td>
+ <td className="px-4 py-3 text-sm text-control">
+ {getDateForPbTimestampProtoEs(changelog.createTime)
+ ? humanizeDate(
+ getDateForPbTimestampProtoEs(changelog.createTime) as Date
+ )
+ : "-"}
+ </td>
+ <td className="px-4 py-3 text-sm text-control">
+ {changelog.planTitle || "-"}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ );
+}
diff --git a/frontend/src/react/pages/project/database-detail/legacy/DatabaseObjectExplorerBridge.tsx b/frontend/src/react/pages/project/database-detail/legacy/DatabaseObjectExplorerBridge.tsx
deleted file mode 100644
index bcfb45d97c..0000000000
--- a/frontend/src/react/pages/project/database-detail/legacy/DatabaseObjectExplorerBridge.tsx
+++ /dev/null
@@ -1,71 +0,0 @@
-import { useEffect, useRef } from "react";
-import { createApp, h } from "vue";
-import i18n from "@/plugins/i18n";
-import NaiveUI from "@/plugins/naive-ui";
-import { router } from "@/router";
-import { pinia } from "@/store";
-import type { Database } from "@/types/proto-es/v1/database_service_pb";
-import DatabaseObjectExplorer from "./DatabaseObjectExplorer.vue";
-
-export interface DatabaseObjectExplorerBridgeProps {
- database: Database;
- loading: boolean;
- selectedSchemaName: string;
- tableSearchKeyword: string;
- externalTableSearchKeyword: string;
- onSelectedSchemaNameChange: (value: string) => void;
- onTableSearchKeywordChange: (value: string) => void;
- onExternalTableSearchKeywordChange: (value: string) => void;
-}
-
-export function DatabaseObjectExplorerBridge({
- database,
- loading,
- selectedSchemaName,
- tableSearchKeyword,
- externalTableSearchKeyword,
- onSelectedSchemaNameChange,
- onTableSearchKeywordChange,
- onExternalTableSearchKeywordChange,
-}: DatabaseObjectExplorerBridgeProps) {
- const containerRef = useRef<HTMLDivElement>(null);
-
- useEffect(() => {
- if (!containerRef.current) {
- return;
- }
-
- const app = createApp({
- render() {
- return h(DatabaseObjectExplorer as never, {
- database,
- loading,
- selectedSchemaName,
- tableSearchKeyword,
- externalTableSearchKeyword,
- "onUpdate:selected-schema-name": onSelectedSchemaNameChange,
- "onUpdate:table-search-keyword": onTableSearchKeywordChange,
- "onUpdate:external-table-search-keyword":
- onExternalTableSearchKeywordChange,
- });
- },
- });
- app.use(router).use(pinia).use(i18n).use(NaiveUI);
- app.mount(containerRef.current);
-
- return () => {
- app.unmount();
- };
- }, [
- database,
- externalTableSearchKeyword,
- loading,
- onExternalTableSearchKeywordChange,
- onSelectedSchemaNameChange,
- onTableSearchKeywordChange,
- selectedSchemaName,
- tableSearchKeyword,
- ]);
-
- return <div ref={containerRef} />;
-}
diff --git a/frontend/src/react/pages/project/database-detail/legacy/DatabaseOverviewInfoBridge.tsx b/frontend/src/react/pages/project/database-detail/legacy/DatabaseOverviewInfoBridge.tsx
deleted file mode 100644
index 77ad282da1..0000000000
--- a/frontend/src/react/pages/project/database-detail/legacy/DatabaseOverviewInfoBridge.tsx
+++ /dev/null
@@ -1,40 +0,0 @@
-import { useEffect, useRef } from "react";
-import { createApp, h } from "vue";
-import DatabaseOverviewInfo from "@/components/Database/DatabaseOverviewInfo.vue";
-import i18n from "@/plugins/i18n";
-import NaiveUI from "@/plugins/naive-ui";
-import { router } from "@/router";
-import { pinia } from "@/store";
-import type { Database } from "@/types/proto-es/v1/database_service_pb";
-
-export function DatabaseOverviewInfoBridge({
- database,
- className,
-}: {
- database: Database;
- className?: string;
-}) {
- const containerRef = useRef<HTMLDivElement>(null);
-
- useEffect(() => {
- if (!containerRef.current) {
- return;
- }
-
- const app = createApp({
- render() {
- return h(DatabaseOverviewInfo as never, {
- database,
- });
- },
- });
- app.use(router).use(pinia).use(i18n).use(NaiveUI);
- app.mount(containerRef.current);
-
- return () => {
- app.unmount();
- };
- }, [database]);
-
- return <div className={className} ref={containerRef} />;
-}
diff --git a/frontend/src/react/pages/project/database-detail/legacy/GrantAccessDrawerBridge.tsx b/frontend/src/react/pages/project/database-detail/legacy/GrantAccessDrawerBridge.tsx
deleted file mode 100644
index 41d8d06e57..0000000000
--- a/frontend/src/react/pages/project/database-detail/legacy/GrantAccessDrawerBridge.tsx
+++ /dev/null
@@ -1,53 +0,0 @@
-import { useEffect, useRef } from "react";
-import { createApp, h } from "vue";
-import GrantAccessDrawer from "@/components/SensitiveData/GrantAccessDrawer.vue";
-import type { SensitiveColumn } from "@/components/SensitiveData/types";
-import i18n from "@/plugins/i18n";
-import NaiveUI from "@/plugins/naive-ui";
-import { router } from "@/router";
-import { pinia } from "@/store";
-
-export interface GrantAccessDrawerBridgeProps {
- open: boolean;
- columnList: SensitiveColumn[];
- projectName: string;
- onDismiss: () => void;
-}
-
-export function GrantAccessDrawerBridge({
- open,
- columnList,
- projectName,
- onDismiss,
-}: GrantAccessDrawerBridgeProps) {
- const containerRef = useRef<HTMLDivElement>(null);
-
- useEffect(() => {
- if (!open || !containerRef.current) {
- return;
- }
-
- const app = createApp({
- render() {
- return h(GrantAccessDrawer as never, {
- columnList,
- projectName,
- onDismiss,
- });
- },
- });
-
- app.use(router).use(pinia).use(i18n).use(NaiveUI);
- app.mount(containerRef.current);
-
- return () => {
- app.unmount();
- };
- }, [columnList, onDismiss, open, projectName]);
-
- if (!open) {
- return null;
- }
-
- return <div ref={containerRef} />;
-}
diff --git a/frontend/src/react/pages/project/database-detail/legacy/SensitiveColumnTableBridge.tsx b/frontend/src/react/pages/project/database-detail/legacy/SensitiveColumnTableBridge.tsx
deleted file mode 100644
index c50c306161..0000000000
--- a/frontend/src/react/pages/project/database-detail/legacy/SensitiveColumnTableBridge.tsx
+++ /dev/null
@@ -1,72 +0,0 @@
-import { useEffect, useRef } from "react";
-import { createApp, h } from "vue";
-import SensitiveColumnTable from "@/components/SensitiveData/components/SensitiveColumnTable.vue";
-import type { MaskData } from "@/components/SensitiveData/types";
-import i18n from "@/plugins/i18n";
-import NaiveUI from "@/plugins/naive-ui";
-import { router } from "@/router";
-import { pinia } from "@/store";
-import type { Database } from "@/types/proto-es/v1/database_service_pb";
-
-export interface SensitiveColumnTableBridgeProps {
- database: Database;
- rowClickable: boolean;
- rowSelectable: boolean;
- showOperation: boolean;
- columnList: MaskData[];
- checkedColumnList: MaskData[];
- onCheckedColumnListChange: (list: MaskData[]) => void;
- onDelete: (item: MaskData) => void;
-}
-
-export function SensitiveColumnTableBridge({
- database,
- rowClickable,
- rowSelectable,
- showOperation,
- columnList,
- checkedColumnList,
- onCheckedColumnListChange,
- onDelete,
-}: SensitiveColumnTableBridgeProps) {
- const containerRef = useRef<HTMLDivElement>(null);
-
- useEffect(() => {
- if (!containerRef.current) {
- return;
- }
-
- const app = createApp({
- render() {
- return h(SensitiveColumnTable as never, {
- database,
- rowClickable,
- rowSelectable,
- showOperation,
- columnList,
- checkedColumnList,
- "onUpdate:checkedColumnList": onCheckedColumnListChange,
- onDelete,
- });
- },
- });
-
- app.use(router).use(pinia).use(i18n).use(NaiveUI);
- app.mount(containerRef.current);
-
- return () => {
- app.unmount();
- };
- }, [
- checkedColumnList,
- columnList,
- database,
- onCheckedColumnListChange,
- onDelete,
- rowClickable,
- rowSelectable,
- showOperation,
- ]);
-
- return <div ref={containerRef} />;
-}
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
new file mode 100644
index 0000000000..9d8b967d66
--- /dev/null
+++ b/frontend/src/react/pages/project/database-detail/overview/DatabaseObjectExplorer.test.tsx
@@ -0,0 +1,220 @@
+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(),
+ getTableCatalog: vi.fn(),
+ featureToRef: vi.fn(() => ({ value: true })),
+ useDBSchemaV1Store: vi.fn(),
+ getDatabaseEngine: vi.fn(() => Engine.POSTGRES),
+ hasSchemaProperty: vi.fn(() => true),
+ instanceV1SupportsPackage: vi.fn(() => false),
+ instanceV1SupportsSequence: vi.fn(() => false),
+ bytesToString: vi.fn((size: number) => `${size} B`),
+ 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,
+ getTableCatalog: mocks.getTableCatalog,
+ featureToRef: mocks.featureToRef,
+}));
+
+vi.mock("@/utils", () => ({
+ bytesToString: mocks.bytesToString,
+ getDatabaseEngine: mocks.getDatabaseEngine,
+ hasSchemaProperty: mocks.hasSchemaProperty,
+ instanceV1SupportsPackage: mocks.instanceV1SupportsPackage,
+ instanceV1SupportsSequence: mocks.instanceV1SupportsSequence,
+}));
+
+vi.mock("@/react/components/ui/input", () => ({
+ Input: (props: React.InputHTMLAttributes<HTMLInputElement>) => (
+ <input {...props} />
+ ),
+}));
+
+vi.mock("./TableDetailDialog", () => ({
+ 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`,
+ 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.bytesToString.mockReset();
+ mocks.bytesToString.mockImplementation((size: number) => `${size} B`);
+ 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.getTableCatalog.mockReset();
+ mocks.getTableCatalog.mockReturnValue({
+ classification: "",
+ });
+ mocks.featureToRef.mockReset();
+ mocks.featureToRef.mockReturnValue({ value: true });
+ mocks.useVueState.mockReset();
+ mocks.useVueState.mockImplementation((getter: () => unknown) => getter());
+ 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();
+
+ unmount();
+ });
+});
diff --git a/frontend/src/react/pages/project/database-detail/overview/DatabaseObjectExplorer.tsx b/frontend/src/react/pages/project/database-detail/overview/DatabaseObjectExplorer.tsx
new file mode 100644
index 0000000000..fb374e29ee
--- /dev/null
+++ b/frontend/src/react/pages/project/database-detail/overview/DatabaseObjectExplorer.tsx
@@ -0,0 +1,372 @@
+import { useEffect, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Input } from "@/react/components/ui/input";
+import { useVueState } from "@/react/hooks/useVueState";
+import { router } from "@/router";
+import { useDBSchemaV1Store } from "@/store";
+import { Engine } from "@/types/proto-es/v1/common_pb";
+import type {
+ Database,
+ PackageMetadata,
+ SequenceMetadata,
+ StreamMetadata,
+ TaskMetadata,
+} from "@/types/proto-es/v1/database_service_pb";
+import {
+ bytesToString,
+ getDatabaseEngine,
+ hasSchemaProperty,
+ instanceV1SupportsPackage,
+ instanceV1SupportsSequence,
+} from "@/utils";
+import {
+ type ObjectSectionRow,
+ ObjectSectionTable,
+} from "./ObjectSectionTable";
+import {
+ TableDetailDialog,
+ type TableDetailDialogData,
+} from "./TableDetailDialog";
+import { TableMetadataTable } from "./TableMetadataTable";
+
+function filterByKeyword(name: string, keyword: string) {
+ return name.toLowerCase().includes(keyword.trim().toLowerCase());
+}
+
+export function DatabaseObjectExplorer({
+ database,
+ loading,
+ selectedSchemaName,
+ tableSearchKeyword,
+ externalTableSearchKeyword,
+ onSelectedSchemaNameChange,
+ onTableSearchKeywordChange,
+ onExternalTableSearchKeywordChange,
+}: {
+ database: Database;
+ loading: boolean;
+ selectedSchemaName: string;
+ tableSearchKeyword: string;
+ externalTableSearchKeyword: string;
+ onSelectedSchemaNameChange: (value: string) => void;
+ onTableSearchKeywordChange: (value: string) => void;
+ onExternalTableSearchKeywordChange: (value: string) => void;
+}) {
+ const { t } = useTranslation();
+ const dbSchemaStore = useDBSchemaV1Store();
+ const databaseEngine = getDatabaseEngine(database);
+ const supportsSchema = hasSchemaProperty(databaseEngine);
+ const schemaList = useVueState(() =>
+ dbSchemaStore.getSchemaList(database.name)
+ );
+ const tableList = useVueState(() =>
+ dbSchemaStore.getTableList({
+ database: database.name,
+ schema: selectedSchemaName,
+ })
+ );
+ const viewList = useVueState(() =>
+ dbSchemaStore.getViewList({
+ database: database.name,
+ schema: selectedSchemaName,
+ })
+ );
+ const extensionList = useVueState(() =>
+ dbSchemaStore.getExtensionList(database.name)
+ );
+ const externalTableList = useVueState(() =>
+ dbSchemaStore.getExternalTableList({
+ database: database.name,
+ schema: selectedSchemaName,
+ })
+ );
+ const functionList = useVueState(() =>
+ dbSchemaStore.getFunctionList({
+ database: database.name,
+ schema: selectedSchemaName,
+ })
+ );
+ const routeTable = useVueState(() => {
+ const table = router.currentRoute.value.query.table;
+ return typeof table === "string" ? table : "";
+ });
+ const databaseMetadata = useVueState(() =>
+ dbSchemaStore.getDatabaseMetadata(database.name)
+ );
+ const [selectedTableName, setSelectedTableName] = useState(routeTable);
+
+ const selectedSchemaMetadata = databaseMetadata.schemas.find(
+ (schema) => schema.name === selectedSchemaName
+ );
+ const sequenceList: SequenceMetadata[] = supportsSchema
+ ? (selectedSchemaMetadata?.sequences ?? [])
+ : databaseMetadata.schemas.flatMap((schema) => schema.sequences ?? []);
+ const streamList: StreamMetadata[] = supportsSchema
+ ? (selectedSchemaMetadata?.streams ?? [])
+ : databaseMetadata.schemas.flatMap((schema) => schema.streams ?? []);
+ const taskList: TaskMetadata[] = supportsSchema
+ ? (selectedSchemaMetadata?.tasks ?? [])
+ : databaseMetadata.schemas.flatMap((schema) => schema.tasks ?? []);
+ const packageList: PackageMetadata[] = supportsSchema
+ ? (selectedSchemaMetadata?.packages ?? [])
+ : databaseMetadata.schemas.flatMap((schema) => schema.packages ?? []);
+
+ const selectedTable = tableList.find(
+ (table) => table.name === selectedTableName
+ );
+ const selectedTableDetail: TableDetailDialogData | undefined = selectedTable
+ ? {
+ name: selectedTable.name,
+ rowCount: String(selectedTable.rowCount),
+ dataSize: bytesToString(Number(selectedTable.dataSize)),
+ indexSize: bytesToString(Number(selectedTable.indexSize)),
+ columns: selectedTable.columns.map((column) => ({
+ name: column.name,
+ type: column.type,
+ comment: column.comment,
+ })),
+ }
+ : undefined;
+
+ useEffect(() => {
+ setSelectedTableName((current) =>
+ current === routeTable ? current : routeTable
+ );
+ }, [routeTable]);
+
+ useEffect(() => {
+ if (!selectedTableName || loading || selectedTable) {
+ return;
+ }
+
+ setSelectedTableName("");
+ }, [loading, selectedTable, selectedTableName]);
+
+ useEffect(() => {
+ const currentQuery = router.currentRoute.value.query;
+ const currentTable =
+ typeof currentQuery.table === "string" ? currentQuery.table : "";
+
+ if (currentTable === selectedTableName) {
+ return;
+ }
+
+ void router.replace({
+ query: {
+ ...currentQuery,
+ table: selectedTableName || undefined,
+ },
+ });
+ }, [selectedTableName]);
+
+ const viewRows: ObjectSectionRow[] = viewList.map((view) => ({
+ key: view.name,
+ name: view.name,
+ description: view.definition || "-",
+ comment: view.comment,
+ }));
+
+ const externalTableRows: ObjectSectionRow[] = externalTableList
+ .filter((table) => filterByKeyword(table.name, externalTableSearchKeyword))
+ .map((table) => ({
+ key: table.name,
+ name: table.name,
+ description:
+ [table.externalServerName, table.externalDatabaseName]
+ .filter(Boolean)
+ .join(" / ") || "-",
+ }));
+
+ const extensionRows: ObjectSectionRow[] = extensionList.map((extension) => ({
+ key: extension.name,
+ name: extension.name,
+ description: extension.version || "-",
+ comment: extension.description,
+ }));
+
+ const functionRows: ObjectSectionRow[] = functionList.map((fn) => ({
+ key: fn.signature || fn.name,
+ name: fn.signature || fn.name,
+ description: fn.definition || "-",
+ comment: fn.comment,
+ }));
+
+ const sequenceRows: ObjectSectionRow[] = sequenceList.map((sequence) => ({
+ key: sequence.name,
+ name: sequence.name,
+ description: sequence.dataType || "-",
+ comment: sequence.comment,
+ }));
+
+ const streamRows: ObjectSectionRow[] = streamList.map((stream) => ({
+ key: stream.name,
+ name: stream.name,
+ description: stream.tableName || "-",
+ comment: stream.comment,
+ }));
+
+ const taskRows: ObjectSectionRow[] = taskList.map((task) => ({
+ key: task.name,
+ name: task.name,
+ description: task.schedule || task.id || "-",
+ comment: task.comment,
+ }));
+
+ const packageRows: ObjectSectionRow[] = packageList.map((pkg) => ({
+ key: pkg.name,
+ name: pkg.name,
+ description: pkg.definition || "-",
+ }));
+
+ return (
+ <div className="space-y-6 pt-6">
+ {supportsSchema && (
+ <div className="flex flex-wrap items-center gap-x-2 gap-y-2">
+ <label
+ className="text-lg font-medium text-main"
+ htmlFor="schema-select"
+ >
+ {t("common.schema")}
+ </label>
+ <select
+ id="schema-select"
+ className="min-w-48 rounded-xs border border-control-border bg-white px-3 py-2 text-sm text-main"
+ disabled={loading}
+ value={selectedSchemaName}
+ onChange={(event) =>
+ onSelectedSchemaNameChange(event.target.value.trim())
+ }
+ >
+ {schemaList.map((schema) => (
+ <option key={schema.name} value={schema.name}>
+ {schema.name || t("db.schema.default")}
+ </option>
+ ))}
+ </select>
+ </div>
+ )}
+
+ {databaseEngine !== Engine.REDIS && (
+ <>
+ <section className="space-y-4">
+ <div className="flex flex-wrap items-center justify-between gap-3">
+ <div className="text-lg font-medium text-main">
+ {databaseEngine === Engine.MONGODB
+ ? t("db.collections")
+ : t("db.tables")}
+ </div>
+ <Input
+ className="w-full max-w-sm"
+ disabled={loading}
+ placeholder={t("common.filter-by-name")}
+ value={tableSearchKeyword}
+ onChange={(event) =>
+ onTableSearchKeywordChange(event.target.value)
+ }
+ />
+ </div>
+ <TableMetadataTable
+ database={database}
+ loading={loading}
+ rows={tableList.filter((table) =>
+ filterByKeyword(table.name, tableSearchKeyword)
+ )}
+ schemaName={selectedSchemaName}
+ onRowClick={(table) => setSelectedTableName(table.name)}
+ />
+ </section>
+
+ <section className="space-y-4">
+ <div className="text-lg font-medium text-main">{t("db.views")}</div>
+ <ObjectSectionTable loading={loading} rows={viewRows} />
+ </section>
+
+ {(databaseEngine === Engine.POSTGRES ||
+ databaseEngine === Engine.HIVE) && (
+ <section className="space-y-4">
+ <div className="flex flex-wrap items-center justify-between gap-3">
+ <div className="text-lg font-medium text-main">
+ {t("db.external-tables")}
+ </div>
+ <Input
+ className="w-full max-w-sm"
+ disabled={loading}
+ placeholder={t("common.filter-by-name")}
+ value={externalTableSearchKeyword}
+ onChange={(event) =>
+ onExternalTableSearchKeywordChange(event.target.value)
+ }
+ />
+ </div>
+ <ObjectSectionTable loading={loading} rows={externalTableRows} />
+ </section>
+ )}
+
+ {databaseEngine === Engine.POSTGRES && (
+ <section className="space-y-4">
+ <div className="text-lg font-medium text-main">
+ {t("db.extensions")}
+ </div>
+ <ObjectSectionTable loading={loading} rows={extensionRows} />
+ </section>
+ )}
+
+ {(databaseEngine === Engine.POSTGRES ||
+ databaseEngine === Engine.MSSQL) && (
+ <section className="space-y-4">
+ <div className="text-lg font-medium text-main">
+ {t("db.functions")}
+ </div>
+ <ObjectSectionTable loading={loading} rows={functionRows} />
+ </section>
+ )}
+
+ {instanceV1SupportsSequence(databaseEngine) && (
+ <section className="space-y-4">
+ <div className="text-lg font-medium text-main">
+ {t("db.sequences")}
+ </div>
+ <ObjectSectionTable loading={loading} rows={sequenceRows} />
+ </section>
+ )}
+
+ {databaseEngine === Engine.SNOWFLAKE && (
+ <>
+ <section className="space-y-4">
+ <div className="text-lg font-medium text-main">
+ {t("db.streams")}
+ </div>
+ <ObjectSectionTable loading={loading} rows={streamRows} />
+ </section>
+ <section className="space-y-4">
+ <div className="text-lg font-medium text-main">
+ {t("db.tasks")}
+ </div>
+ <ObjectSectionTable loading={loading} rows={taskRows} />
+ </section>
+ </>
+ )}
+
+ {instanceV1SupportsPackage(databaseEngine) && (
+ <section className="space-y-4">
+ <div className="text-lg font-medium text-main">
+ {t("db.packages")}
+ </div>
+ <ObjectSectionTable loading={loading} rows={packageRows} />
+ </section>
+ )}
+ </>
+ )}
+
+ <TableDetailDialog
+ open={!!selectedTableName}
+ table={selectedTableDetail}
+ onOpenChange={(open) => {
+ if (!open) {
+ setSelectedTableName("");
+ }
+ }}
+ />
+ </div>
+ );
+}
diff --git a/frontend/src/react/pages/project/database-detail/overview/DatabaseOverviewInfo.tsx b/frontend/src/react/pages/project/database-detail/overview/DatabaseOverviewInfo.tsx
new file mode 100644
index 0000000000..94fc08512e
--- /dev/null
+++ b/frontend/src/react/pages/project/database-detail/overview/DatabaseOverviewInfo.tsx
@@ -0,0 +1,90 @@
+import { useTranslation } from "react-i18next";
+import { useVueState } from "@/react/hooks/useVueState";
+import { useDBSchemaV1Store } from "@/store";
+import { Engine, State } from "@/types/proto-es/v1/common_pb";
+import {
+ type Database,
+ SyncStatus,
+} from "@/types/proto-es/v1/database_service_pb";
+import {
+ getDatabaseEngine,
+ humanizeDate,
+ instanceV1HasCollationAndCharacterSet,
+} from "@/utils";
+
+export function DatabaseOverviewInfo({ database }: { database: Database }) {
+ const { t } = useTranslation();
+ const dbSchemaStore = useDBSchemaV1Store();
+ const databaseEngine = getDatabaseEngine(database);
+ const databaseSchemaMetadata = useVueState(() =>
+ dbSchemaStore.getDatabaseMetadata(database.name)
+ );
+ const lastSyncDate = database.successfulSyncTime
+ ? new Date(Number(database.successfulSyncTime.seconds) * 1000)
+ : undefined;
+ const hasLastSyncDate = !!lastSyncDate && lastSyncDate.getTime() !== 0;
+
+ return (
+ <div className="rounded-lg border border-block-border px-5 py-4">
+ <dl
+ className="grid grid-cols-1 gap-x-4 gap-y-4 sm:grid-cols-2"
+ data-label="bb-database-overview-description-list"
+ >
+ {instanceV1HasCollationAndCharacterSet(databaseEngine) && (
+ <>
+ <div className="col-span-1 col-start-1">
+ <dt className="text-sm font-medium text-control-light">
+ {databaseEngine === Engine.POSTGRES
+ ? t("db.encoding")
+ : t("db.character-set")}
+ </dt>
+ <dd className="mt-1 text-sm text-main">
+ {databaseSchemaMetadata.characterSet}
+ </dd>
+ </div>
+
+ <div className="col-span-1">
+ <dt className="text-sm font-medium text-control-light">
+ {t("db.collation")}
+ </dt>
+ <dd className="mt-1 text-sm text-main">
+ {databaseSchemaMetadata.collation}
+ </dd>
+ </div>
+ </>
+ )}
+
+ <div className="col-span-1 col-start-1">
+ <dt className="text-sm font-medium text-control-light">
+ {t("database.sync-status")}
+ </dt>
+ <dd className="mt-1 text-sm text-main">
+ {database.syncStatus === SyncStatus.FAILED ? (
+ <>
+ <span className="text-error">
+ {t("database.sync-status-failed")}
+ </span>
+ <p className="mt-1 text-xs text-gray-500">
+ {database.syncError}
+ </p>
+ </>
+ ) : database.state === State.ACTIVE ? (
+ t("common.ok")
+ ) : (
+ t("error-page.not-found")
+ )}
+ </dd>
+ </div>
+
+ <div className="col-span-1">
+ <dt className="text-sm font-medium text-control-light">
+ {t("database.last-sync")}
+ </dt>
+ <dd className="mt-1 text-sm text-main">
+ {hasLastSyncDate ? humanizeDate(lastSyncDate) : "-"}
+ </dd>
+ </div>
+ </dl>
+ </div>
+ );
+}
diff --git a/frontend/src/react/pages/project/database-detail/overview/ObjectSectionTable.tsx b/frontend/src/react/pages/project/database-detail/overview/ObjectSectionTable.tsx
new file mode 100644
index 0000000000..466520cede
--- /dev/null
+++ b/frontend/src/react/pages/project/database-detail/overview/ObjectSectionTable.tsx
@@ -0,0 +1,83 @@
+import type { ReactNode } from "react";
+import { useTranslation } from "react-i18next";
+
+export interface ObjectSectionRow {
+ key: string;
+ name: string;
+ description?: ReactNode;
+ comment?: string;
+ onClick?: () => void;
+}
+
+export function ObjectSectionTable({
+ rows,
+ emptyText,
+ loading = false,
+}: {
+ rows: ObjectSectionRow[];
+ emptyText?: string;
+ loading?: boolean;
+}) {
+ const { t } = useTranslation();
+
+ if (loading) {
+ return (
+ <div className="rounded-lg border border-dashed border-block-border px-4 py-6 text-sm text-control-light">
+ {t("common.loading")}
+ </div>
+ );
+ }
+
+ if (rows.length === 0) {
+ return (
+ <div className="rounded-lg border border-dashed border-block-border px-4 py-6 text-sm text-control-light">
+ {emptyText || "-"}
+ </div>
+ );
+ }
+
+ 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">
+ <th className="px-4 py-2 font-medium">{t("common.name")}</th>
+ <th className="px-4 py-2 font-medium">{t("common.definition")}</th>
+ <th className="px-4 py-2 font-medium">{t("common.comment")}</th>
+ </tr>
+ </thead>
+ <tbody className="divide-y divide-block-border bg-white">
+ {rows.map((row) => (
+ <tr
+ key={row.key}
+ className={
+ row.onClick ? "cursor-pointer hover:bg-control-bg" : ""
+ }
+ role={row.onClick ? "button" : undefined}
+ tabIndex={row.onClick ? 0 : undefined}
+ onClick={row.onClick}
+ onKeyDown={
+ row.onClick
+ ? (event) => {
+ if (event.key === "Enter" || event.key === " ") {
+ event.preventDefault();
+ row.onClick?.();
+ }
+ }
+ : undefined
+ }
+ >
+ <td className="px-4 py-3 text-sm text-main">{row.name}</td>
+ <td className="px-4 py-3 text-sm text-control">
+ {row.description}
+ </td>
+ <td className="px-4 py-3 text-sm text-control">
+ {row.comment || "-"}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ );
+}
diff --git a/frontend/src/react/pages/project/database-detail/overview/TableDetailDialog.tsx b/frontend/src/react/pages/project/database-detail/overview/TableDetailDialog.tsx
new file mode 100644
index 0000000000..f8f023aa62
--- /dev/null
+++ b/frontend/src/react/pages/project/database-detail/overview/TableDetailDialog.tsx
@@ -0,0 +1,96 @@
+import { useTranslation } from "react-i18next";
+import {
+ Dialog,
+ DialogContent,
+ DialogTitle,
+} from "@/react/components/ui/dialog";
+export interface TableDetailDialogData {
+ columns: {
+ comment?: string;
+ name: string;
+ type: string;
+ }[];
+ dataSize: string;
+ indexSize: string;
+ name: string;
+ rowCount: string;
+}
+
+export function TableDetailDialog({
+ table,
+ open,
+ onOpenChange,
+}: {
+ table?: TableDetailDialogData;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+}) {
+ const { t } = useTranslation();
+
+ if (!table) {
+ return null;
+ }
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="max-w-3xl 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")}
+ </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>
+ <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>
+ </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>
+ </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
new file mode 100644
index 0000000000..d7a598d4d3
--- /dev/null
+++ b/frontend/src/react/pages/project/database-detail/overview/TableMetadataTable.tsx
@@ -0,0 +1,154 @@
+import { useMemo } from "react";
+import { useTranslation } from "react-i18next";
+import { useVueState } from "@/react/hooks/useVueState";
+import { featureToRef, getTableCatalog, useDatabaseCatalog } from "@/store";
+import { Engine } from "@/types/proto-es/v1/common_pb";
+import type {
+ Database,
+ TableMetadata,
+} from "@/types/proto-es/v1/database_service_pb";
+import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
+import { bytesToString, getDatabaseEngine, hasSchemaProperty } from "@/utils";
+
+export function TableMetadataTable({
+ database,
+ schemaName,
+ rows,
+ loading = false,
+ onRowClick,
+}: {
+ database: Database;
+ schemaName: string;
+ rows: TableMetadata[];
+ loading?: boolean;
+ onRowClick?: (table: TableMetadata) => void;
+}) {
+ const { t } = useTranslation();
+ const databaseEngine = getDatabaseEngine(database);
+ const showSchemaColumn = hasSchemaProperty(databaseEngine);
+ const showClassificationColumn = useVueState(
+ () => featureToRef(PlanFeature.FEATURE_DATA_MASKING).value
+ );
+ const databaseCatalog = useDatabaseCatalog(database.name, false);
+ const catalog = useVueState(() => databaseCatalog.value);
+
+ const showPartitionedColumn = databaseEngine === Engine.POSTGRES;
+ const columns = useMemo(
+ () =>
+ [
+ showSchemaColumn
+ ? { key: "schema", label: t("common.schema") }
+ : undefined,
+ { key: "name", label: t("common.name") },
+ showClassificationColumn
+ ? {
+ key: "classification",
+ label: t("database.classification.self"),
+ }
+ : undefined,
+ showPartitionedColumn
+ ? {
+ key: "partitioned",
+ label: t("database.partitioned"),
+ }
+ : undefined,
+ { key: "rowCount", label: t("database.row-count-est") },
+ { key: "dataSize", label: t("database.data-size") },
+ { key: "indexSize", label: t("database.index-size") },
+ { key: "comment", label: t("common.comment") },
+ ].filter((column) => column !== undefined),
+ [showClassificationColumn, showPartitionedColumn, showSchemaColumn, t]
+ );
+
+ if (loading) {
+ return (
+ <div className="rounded-lg border border-dashed border-block-border px-4 py-6 text-sm text-control-light">
+ {t("common.loading")}
+ </div>
+ );
+ }
+
+ if (rows.length === 0) {
+ return (
+ <div className="rounded-lg border border-dashed border-block-border px-4 py-6 text-sm text-control-light">
+ -
+ </div>
+ );
+ }
+
+ 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">
+ {columns.map((column) => (
+ <th key={column.key} className="px-4 py-2 font-medium">
+ {column.label}
+ </th>
+ ))}
+ </tr>
+ </thead>
+ <tbody className="divide-y divide-block-border bg-white">
+ {rows.map((table) => {
+ const tableCatalog = catalog
+ ? getTableCatalog(catalog, schemaName, table.name)
+ : undefined;
+ const classification =
+ tableCatalog?.classification?.trim() || undefined;
+
+ return (
+ <tr
+ key={`${database.name}.${schemaName}.${table.name}`}
+ className={
+ onRowClick ? "cursor-pointer hover:bg-control-bg" : ""
+ }
+ role={onRowClick ? "button" : undefined}
+ tabIndex={onRowClick ? 0 : undefined}
+ onClick={() => onRowClick?.(table)}
+ onKeyDown={
+ onRowClick
+ ? (event) => {
+ if (event.key === "Enter" || event.key === " ") {
+ event.preventDefault();
+ onRowClick(table);
+ }
+ }
+ : undefined
+ }
+ >
+ {showSchemaColumn && (
+ <td className="px-4 py-3 text-sm text-main">
+ {schemaName || t("db.schema.default")}
+ </td>
+ )}
+ <td className="px-4 py-3 text-sm text-main">{table.name}</td>
+ {showClassificationColumn && (
+ <td className="px-4 py-3 text-sm text-control">
+ {classification || "-"}
+ </td>
+ )}
+ {showPartitionedColumn && (
+ <td className="px-4 py-3 text-sm text-control">
+ {(table.partitions?.length ?? 0) > 0 ? "True" : ""}
+ </td>
+ )}
+ <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>
+ );
+ })}
+ </tbody>
+ </table>
+ </div>
+ );
+}
diff --git a/frontend/src/react/pages/project/database-detail/panels/DatabaseCatalogPanel.test.tsx b/frontend/src/react/pages/project/database-detail/panels/DatabaseCatalogPanel.test.tsx
index bc43ae38ea..4d037e3f9a 100644
--- a/frontend/src/react/pages/project/database-detail/panels/DatabaseCatalogPanel.test.tsx
+++ b/frontend/src/react/pages/project/database-detail/panels/DatabaseCatalogPanel.test.tsx
@@ -2,63 +2,100 @@ import { act, createElement } from "react";
import { createRoot } from "react-dom/client";
import { beforeEach, describe, expect, test, vi } from "vitest";
import type { Database } from "@/types/proto-es/v1/database_service_pb";
+import { Setting_SettingName } from "@/types/proto-es/v1/setting_service_pb";
(
globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
).IS_REACT_ACT_ENVIRONMENT = true;
const mocks = vi.hoisted(() => ({
+ confirm: vi.fn(() => true),
+ localStorage: {
+ clear: vi.fn(),
+ getItem: vi.fn(() => null),
+ removeItem: vi.fn(),
+ setItem: vi.fn(),
+ },
useTranslation: vi.fn(() => ({
t: (key: string) => key,
})),
useVueState: vi.fn((getter: () => unknown) => getter()),
featureToRef: vi.fn(() => ({ value: true })),
useDatabaseCatalog: vi.fn(() => ({
- value: { schemas: [] } as { schemas: unknown[] } | undefined,
+ value: {
+ schemas: [
+ {
+ name: "public",
+ tables: [
+ {
+ name: "book",
+ kind: {
+ case: "columns",
+ value: {
+ columns: [
+ {
+ name: "email",
+ semanticType: "EMAIL",
+ classification: "",
+ },
+ ],
+ },
+ },
+ classification: "",
+ },
+ ],
+ },
+ ],
+ } as unknown,
})),
usePolicyV1Store: vi.fn(() => ({
getOrFetchPolicyByParentAndType: vi.fn(),
upsertPolicy: vi.fn(),
})),
+ useDatabaseCatalogV1Store: vi.fn(() => ({
+ updateDatabaseCatalog: vi.fn(),
+ })),
+ useSettingV1Store: vi.fn(() => ({
+ getOrFetchSettingByName: vi.fn(),
+ getProjectClassification: vi.fn(() => ({
+ id: "classification-config",
+ classification: {
+ PII: {
+ id: "PII",
+ title: "PII",
+ },
+ },
+ })),
+ getSettingByName: vi.fn(() => ({
+ value: {
+ value: {
+ case: "semanticType",
+ value: {
+ types: [
+ {
+ id: "EMAIL",
+ title: "Email",
+ },
+ {
+ id: "PHONE",
+ title: "Phone",
+ },
+ ],
+ },
+ },
+ },
+ })),
+ })),
+ pushNotification: vi.fn(),
hasProjectPermissionV2: vi.fn(
(_project?: unknown, _permission?: string) => true
),
getDatabaseProject: vi.fn((database: { project: string }) => ({
name: database.project,
+ dataClassificationConfigId: "classification-config",
})),
getInstanceResource: vi.fn(() => ({ name: "instances/inst1", engine: 1 })),
instanceV1MaskingForNoSQL: vi.fn(() => false),
- SensitiveColumnTableBridge: vi.fn(
- ({
- onCheckedColumnListChange,
- }: {
- onCheckedColumnListChange: (list: unknown[]) => void;
- }) => (
- <div data-testid="sensitive-column-table-bridge">
- <button
- type="button"
- data-testid="select-sensitive-row"
- onClick={() =>
- onCheckedColumnListChange([
- {
- schema: "public",
- table: "book",
- column: "email",
- semanticTypeId: "EMAIL",
- classificationId: "",
- target: {},
- },
- ])
- }
- >
- select
- </button>
- </div>
- )
- ),
- GrantAccessDrawerBridge: vi.fn(() => (
- <div data-testid="grant-access-drawer" />
- )),
FeatureAttention: vi.fn(() => <div data-testid="feature-attention" />),
FeatureBadge: vi.fn(() => <div data-testid="feature-badge" />),
PermissionGuard: vi.fn(
@@ -68,6 +105,8 @@ const mocks = vi.hoisted(() => ({
let DatabaseCatalogPanel: typeof import("./DatabaseCatalogPanel").DatabaseCatalogPanel;
+vi.stubGlobal("confirm", mocks.confirm);
+
vi.mock("react-i18next", () => ({
useTranslation: mocks.useTranslation,
}));
@@ -78,8 +117,11 @@ vi.mock("@/react/hooks/useVueState", () => ({
vi.mock("@/store", () => ({
featureToRef: mocks.featureToRef,
+ pushNotification: mocks.pushNotification,
useDatabaseCatalog: mocks.useDatabaseCatalog,
+ useDatabaseCatalogV1Store: mocks.useDatabaseCatalogV1Store,
usePolicyV1Store: mocks.usePolicyV1Store,
+ useSettingV1Store: mocks.useSettingV1Store,
}));
vi.mock("@/utils", () => ({
@@ -113,6 +155,37 @@ vi.mock("@/react/components/ui/input", () => ({
),
}));
+vi.mock("@/react/components/ui/select", () => ({
+ Select: ({
+ value,
+ onValueChange,
+ children,
+ }: {
+ value?: string;
+ onValueChange?: (value: string) => void;
+ children: React.ReactNode;
+ }) => (
+ <select
+ value={value}
+ onChange={(event) => onValueChange?.(event.target.value)}
+ >
+ {children}
+ </select>
+ ),
+ SelectTrigger: ({ children }: { children: React.ReactNode }) => children,
+ SelectValue: ({ placeholder }: { placeholder?: string }) => (
+ <option value="">{placeholder}</option>
+ ),
+ SelectContent: ({ children }: { children: React.ReactNode }) => children,
+ SelectItem: ({
+ value,
+ children,
+ }: {
+ value: string;
+ children: React.ReactNode;
+ }) => <option value={value}>{children}</option>,
+}));
+
vi.mock("@/react/components/ui/dialog", () => ({
Dialog: ({ open, children }: { open: boolean; children: React.ReactNode }) =>
open ? <div data-testid="dialog-root">{children}</div> : null,
@@ -124,12 +197,56 @@ vi.mock("@/react/components/ui/dialog", () => ({
),
}));
-vi.mock("../legacy/SensitiveColumnTableBridge", () => ({
- SensitiveColumnTableBridge: mocks.SensitiveColumnTableBridge,
+vi.mock("@/react/components/AccountMultiSelect", () => ({
+ AccountMultiSelect: ({
+ value,
+ onChange,
+ }: {
+ value: string[];
+ onChange: (value: string[]) => void;
+ }) => (
+ <button
+ type="button"
+ data-testid="member-select"
+ onClick={() => onChange([...value, "user:[email protected]"])}
+ >
+ member-select
+ </button>
+ ),
}));
-vi.mock("../legacy/GrantAccessDrawerBridge", () => ({
- GrantAccessDrawerBridge: mocks.GrantAccessDrawerBridge,
+vi.mock("@/react/components/DatabaseResourceSelector", () => ({
+ DatabaseResourceSelector: ({
+ value,
+ onChange,
+ }: {
+ value: unknown[];
+ onChange: (value: unknown[]) => void;
+ }) => (
+ <button
+ type="button"
+ data-testid="resource-select"
+ onClick={() => onChange(value)}
+ >
+ resource-select
+ </button>
+ ),
+}));
+
+vi.mock("@/react/components/ui/expiration-picker", () => ({
+ ExpirationPicker: ({
+ value,
+ onChange,
+ }: {
+ value: string | undefined;
+ onChange: (value: string | undefined) => void;
+ }) => (
+ <input
+ data-testid="expiration-picker"
+ value={value ?? ""}
+ onChange={(event) => onChange(event.target.value || undefined)}
+ />
+ ),
}));
const renderIntoContainer = (element: ReturnType<typeof createElement>) => {
@@ -171,6 +288,9 @@ const makeDatabase = (): Database =>
}) as Database;
beforeEach(async () => {
+ mocks.confirm.mockReset();
+ mocks.confirm.mockReturnValue(true);
+ vi.stubGlobal("localStorage", mocks.localStorage);
mocks.useTranslation.mockReset();
mocks.useTranslation.mockReturnValue({
t: (key: string) => key,
@@ -181,19 +301,81 @@ beforeEach(async () => {
mocks.featureToRef.mockReturnValue({ value: true });
mocks.useDatabaseCatalog.mockReset();
mocks.useDatabaseCatalog.mockReturnValue({
- value: { schemas: [] } as { schemas: unknown[] } | undefined,
+ value: {
+ schemas: [
+ {
+ name: "public",
+ tables: [
+ {
+ name: "book",
+ kind: {
+ case: "columns",
+ value: {
+ columns: [
+ {
+ name: "email",
+ semanticType: "EMAIL",
+ classification: "",
+ },
+ ],
+ },
+ },
+ classification: "",
+ },
+ ],
+ },
+ ],
+ } as unknown,
});
mocks.usePolicyV1Store.mockReset();
mocks.usePolicyV1Store.mockReturnValue({
getOrFetchPolicyByParentAndType: vi.fn(),
upsertPolicy: vi.fn(),
});
+ mocks.useDatabaseCatalogV1Store.mockReset();
+ mocks.useDatabaseCatalogV1Store.mockReturnValue({
+ updateDatabaseCatalog: vi.fn(),
+ });
+ mocks.useSettingV1Store.mockReset();
+ mocks.useSettingV1Store.mockReturnValue({
+ getOrFetchSettingByName: vi.fn(),
+ getProjectClassification: vi.fn(() => ({
+ id: "classification-config",
+ classification: {
+ PII: {
+ id: "PII",
+ title: "PII",
+ },
+ },
+ })),
+ getSettingByName: vi.fn(() => ({
+ value: {
+ value: {
+ case: "semanticType",
+ value: {
+ types: [
+ {
+ id: "EMAIL",
+ title: "Email",
+ },
+ {
+ id: "PHONE",
+ title: "Phone",
+ },
+ ],
+ },
+ },
+ },
+ })),
+ });
+ mocks.pushNotification.mockReset();
mocks.hasProjectPermissionV2.mockReset();
mocks.hasProjectPermissionV2.mockReturnValue(true);
mocks.getDatabaseProject.mockReset();
mocks.getDatabaseProject.mockImplementation(
(database: { project: string }) => ({
name: database.project,
+ dataClassificationConfigId: "classification-config",
})
);
mocks.getInstanceResource.mockReset();
@@ -203,8 +385,6 @@ beforeEach(async () => {
});
mocks.instanceV1MaskingForNoSQL.mockReset();
mocks.instanceV1MaskingForNoSQL.mockReturnValue(false);
- mocks.SensitiveColumnTableBridge.mockClear();
- mocks.GrantAccessDrawerBridge.mockClear();
mocks.FeatureAttention.mockClear();
mocks.FeatureBadge.mockClear();
mocks.PermissionGuard.mockClear();
@@ -214,7 +394,7 @@ beforeEach(async () => {
});
describe("DatabaseCatalogPanel", () => {
- test("keeps grant access disabled until at least one row is selected", async () => {
+ test("renders catalog rows and opens the react grant-access dialog after selection", async () => {
const { container, render, unmount } = renderIntoContainer(
createElement(DatabaseCatalogPanel, {
database: makeDatabase(),
@@ -223,6 +403,9 @@ describe("DatabaseCatalogPanel", () => {
render();
await flush();
+ expect(container.textContent).toContain("public.book");
+ expect(container.textContent).toContain("email");
+
const grantAccessButton = Array.from(
container.querySelectorAll("button")
).find(
@@ -231,52 +414,35 @@ describe("DatabaseCatalogPanel", () => {
expect(grantAccessButton).toBeDefined();
expect(grantAccessButton?.hasAttribute("disabled")).toBe(true);
- const selectRowButton = container.querySelector(
- '[data-testid="select-sensitive-row"]'
- );
- expect(selectRowButton).not.toBeNull();
- click(selectRowButton as HTMLElement);
+ const checkbox = container.querySelector('input[type="checkbox"]');
+ expect(checkbox).not.toBeNull();
+ click(checkbox as HTMLElement);
await flush();
- const updatedGrantAccessButton = Array.from(
+ const enabledGrantAccessButton = Array.from(
container.querySelectorAll("button")
).find(
(button) => button.textContent === "settings.sensitive-data.grant-access"
);
- expect(updatedGrantAccessButton?.hasAttribute("disabled")).toBe(false);
+ expect(enabledGrantAccessButton?.hasAttribute("disabled")).toBe(false);
- unmount();
- });
-
- test("passes the database instance into feature attention", async () => {
- const { render, unmount } = renderIntoContainer(
- createElement(DatabaseCatalogPanel, {
- database: makeDatabase(),
- })
- );
- render();
+ click(enabledGrantAccessButton as HTMLElement);
await flush();
- expect(mocks.FeatureAttention).toHaveBeenCalledWith(
- expect.objectContaining({
- feature: expect.any(Number),
- instance: expect.objectContaining({
- name: "instances/inst1",
- }),
- }),
- undefined
+ expect(
+ container.querySelector('[data-testid="dialog-root"]')
+ ).not.toBeNull();
+ expect(container.textContent).toContain(
+ "settings.sensitive-data.grant-access"
);
unmount();
});
- test("passes showOperation=false when catalog update permission is missing", async () => {
- mocks.hasProjectPermissionV2.mockImplementation(
- (_project?: unknown, permission?: string) =>
- permission !== "bb.databaseCatalogs.update"
- );
+ test("opens the feature dialog instead of grant access when masking feature is missing", async () => {
+ mocks.featureToRef.mockReturnValue({ value: false });
- const { render, unmount } = renderIntoContainer(
+ const { container, render, unmount } = renderIntoContainer(
createElement(DatabaseCatalogPanel, {
database: makeDatabase(),
})
@@ -284,9 +450,27 @@ describe("DatabaseCatalogPanel", () => {
render();
await flush();
- expect(mocks.SensitiveColumnTableBridge).toHaveBeenCalledWith(
+ const checkbox = container.querySelector('input[type="checkbox"]');
+ expect(checkbox).not.toBeNull();
+ click(checkbox as HTMLElement);
+ await flush();
+
+ const grantAccessButton = Array.from(
+ container.querySelectorAll("button")
+ ).find(
+ (button) => button.textContent === "settings.sensitive-data.grant-access"
+ );
+ expect(grantAccessButton?.hasAttribute("disabled")).toBe(false);
+
+ click(grantAccessButton as HTMLElement);
+ await flush();
+
+ expect(
+ container.querySelector('[data-testid="dialog-root"]')
+ ).not.toBeNull();
+ expect(mocks.FeatureBadge).toHaveBeenCalledWith(
expect.objectContaining({
- showOperation: false,
+ clickable: false,
}),
undefined
);
@@ -320,10 +504,13 @@ describe("DatabaseCatalogPanel", () => {
unmount();
});
- test("handles undefined catalog state before data is loaded", async () => {
- mocks.useDatabaseCatalog.mockReturnValue({ value: undefined });
+ test("clears deleted columns from the checked selection", async () => {
+ const updateDatabaseCatalog = vi.fn().mockResolvedValue(undefined);
+ mocks.useDatabaseCatalogV1Store.mockReturnValue({
+ updateDatabaseCatalog,
+ });
- const { render, unmount } = renderIntoContainer(
+ const { container, render, unmount } = renderIntoContainer(
createElement(DatabaseCatalogPanel, {
database: makeDatabase(),
})
@@ -331,20 +518,80 @@ describe("DatabaseCatalogPanel", () => {
render();
await flush();
- expect(mocks.SensitiveColumnTableBridge).toHaveBeenCalledWith(
- expect.objectContaining({
- columnList: [],
- }),
- undefined
+ const checkbox = container.querySelector('input[type="checkbox"]');
+ expect(checkbox).not.toBeNull();
+ click(checkbox as HTMLElement);
+ await flush();
+
+ const grantAccessButtonBeforeDelete = Array.from(
+ container.querySelectorAll("button")
+ ).find(
+ (button) => button.textContent === "settings.sensitive-data.grant-access"
+ );
+ expect(grantAccessButtonBeforeDelete?.hasAttribute("disabled")).toBe(false);
+
+ const deleteButton = container.querySelector(
+ 'button[aria-label="common.remove"]'
);
+ expect(deleteButton).not.toBeNull();
+ click(deleteButton as HTMLElement);
+ await flush();
+
+ expect(updateDatabaseCatalog).toHaveBeenCalledTimes(1);
+
+ const grantAccessButtonAfterDelete = Array.from(
+ container.querySelectorAll("button")
+ ).find(
+ (button) => button.textContent === "settings.sensitive-data.grant-access"
+ );
+ expect(grantAccessButtonAfterDelete?.hasAttribute("disabled")).toBe(true);
unmount();
});
- test("renders feature badge as non-clickable icon when feature is missing", async () => {
- mocks.featureToRef.mockReturnValue({ value: false });
+ test("updates semantic type and classification inline", async () => {
+ const updateDatabaseCatalog = vi.fn().mockResolvedValue(undefined);
+ const getOrFetchSettingByName = vi.fn();
+ mocks.useDatabaseCatalogV1Store.mockReturnValue({
+ updateDatabaseCatalog,
+ });
+ mocks.useSettingV1Store.mockReturnValue({
+ getOrFetchSettingByName,
+ getProjectClassification: vi.fn(() => ({
+ id: "classification-config",
+ classification: {
+ PII: {
+ id: "PII",
+ title: "PII",
+ },
+ CONFIDENTIAL: {
+ id: "CONFIDENTIAL",
+ title: "Confidential",
+ },
+ },
+ })),
+ getSettingByName: vi.fn(() => ({
+ value: {
+ value: {
+ case: "semanticType",
+ value: {
+ types: [
+ {
+ id: "EMAIL",
+ title: "Email",
+ },
+ {
+ id: "PHONE",
+ title: "Phone",
+ },
+ ],
+ },
+ },
+ },
+ })),
+ });
- const { render, unmount } = renderIntoContainer(
+ const { container, render, unmount } = renderIntoContainer(
createElement(DatabaseCatalogPanel, {
database: makeDatabase(),
})
@@ -352,12 +599,62 @@ describe("DatabaseCatalogPanel", () => {
render();
await flush();
- expect(mocks.FeatureBadge).toHaveBeenCalledWith(
+ expect(getOrFetchSettingByName).toHaveBeenCalledWith(
+ Setting_SettingName.SEMANTIC_TYPES,
+ true
+ );
+ expect(getOrFetchSettingByName).toHaveBeenCalledWith(
+ Setting_SettingName.DATA_CLASSIFICATION,
+ true
+ );
+
+ const selects = Array.from(container.querySelectorAll("select"));
+ expect(selects).toHaveLength(2);
+
+ act(() => {
+ const descriptor = Object.getOwnPropertyDescriptor(
+ HTMLSelectElement.prototype,
+ "value"
+ );
+ descriptor?.set?.call(selects[0], "PHONE");
+ selects[0].dispatchEvent(new Event("change", { bubbles: true }));
+ });
+ await flush();
+
+ act(() => {
+ const descriptor = Object.getOwnPropertyDescriptor(
+ HTMLSelectElement.prototype,
+ "value"
+ );
+ descriptor?.set?.call(selects[1], "CONFIDENTIAL");
+ selects[1].dispatchEvent(new Event("change", { bubbles: true }));
+ });
+ await flush();
+
+ expect(updateDatabaseCatalog).toHaveBeenCalledTimes(2);
+ expect(mocks.pushNotification).toHaveBeenCalledWith(
expect.objectContaining({
- clickable: false,
- }),
- undefined
+ style: "SUCCESS",
+ title: "common.updated",
+ })
+ );
+
+ unmount();
+ });
+
+ test("handles undefined catalog state before data is loaded", async () => {
+ mocks.useDatabaseCatalog.mockReturnValue({ value: undefined as unknown });
+
+ const { container, render, unmount } = renderIntoContainer(
+ createElement(DatabaseCatalogPanel, {
+ database: makeDatabase(),
+ })
);
+ render();
+ await flush();
+
+ expect(container.textContent).not.toContain("public.book");
+ expect(container.textContent).not.toContain("email");
unmount();
});
diff --git a/frontend/src/react/pages/project/database-detail/panels/DatabaseCatalogPanel.tsx b/frontend/src/react/pages/project/database-detail/panels/DatabaseCatalogPanel.tsx
index 242262e928..51986da1c9 100644
--- a/frontend/src/react/pages/project/database-detail/panels/DatabaseCatalogPanel.tsx
+++ b/frontend/src/react/pages/project/database-detail/panels/DatabaseCatalogPanel.tsx
@@ -2,8 +2,14 @@ import { create } from "@bufbuild/protobuf";
import { ShieldCheck } from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
-import type { MaskData } from "@/components/SensitiveData/types";
-import { isCurrentColumnException } from "@/components/SensitiveData/utils";
+import type {
+ MaskData,
+ MaskDataTarget,
+} from "@/components/SensitiveData/types";
+import {
+ getMaskDataIdentifier,
+ isCurrentColumnException,
+} from "@/components/SensitiveData/utils";
import { FeatureAttention } from "@/react/components/FeatureAttention";
import { FeatureBadge } from "@/react/components/FeatureBadge";
import { PermissionGuard } from "@/react/components/PermissionGuard";
@@ -15,11 +21,20 @@ import {
} from "@/react/components/ui/dialog";
import { Input } from "@/react/components/ui/input";
import { useVueState } from "@/react/hooks/useVueState";
-import { featureToRef, useDatabaseCatalog, usePolicyV1Store } from "@/store";
+import {
+ featureToRef,
+ pushNotification,
+ useDatabaseCatalog,
+ useDatabaseCatalogV1Store,
+ usePolicyV1Store,
+ useSettingV1Store,
+} from "@/store";
import type { Permission } from "@/types";
import type {
+ ColumnCatalog,
DatabaseCatalog,
ObjectSchema,
+ TableCatalog,
} from "@/types/proto-es/v1/database_catalog_service_pb";
import { ObjectSchema_Type } from "@/types/proto-es/v1/database_catalog_service_pb";
import type { Database } from "@/types/proto-es/v1/database_service_pb";
@@ -27,6 +42,10 @@ import {
MaskingExemptionPolicySchema,
PolicyType,
} from "@/types/proto-es/v1/org_policy_service_pb";
+import {
+ type SemanticTypeSetting_SemanticType,
+ Setting_SettingName,
+} from "@/types/proto-es/v1/setting_service_pb";
import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
import {
getDatabaseProject,
@@ -34,8 +53,8 @@ import {
hasProjectPermissionV2,
instanceV1MaskingForNoSQL,
} from "@/utils";
-import { GrantAccessDrawerBridge } from "../legacy/GrantAccessDrawerBridge";
-import { SensitiveColumnTableBridge } from "../legacy/SensitiveColumnTableBridge";
+import { GrantAccessDialog } from "../catalog/GrantAccessDialog";
+import { SensitiveColumnTable } from "../catalog/SensitiveColumnTable";
const GRANT_ACCESS_PERMISSIONS: Permission[] = [
"bb.policies.createMaskingExemptionPolicy",
@@ -142,12 +161,35 @@ const flattenSensitiveColumnList = (catalog?: DatabaseCatalog): MaskData[] => {
return sensitiveList;
};
+const hasSemanticType = (
+ target: MaskDataTarget
+): target is ColumnCatalog | ObjectSchema => {
+ return "semanticType" in target;
+};
+
+const hasClassificationType = (
+ target: MaskDataTarget
+): target is ColumnCatalog | TableCatalog => {
+ return "classification" in target;
+};
+
export function DatabaseCatalogPanel({ database }: { database: Database }) {
const { t } = useTranslation();
const policyStore = usePolicyV1Store();
+ const databaseCatalogStore = useDatabaseCatalogV1Store();
+ const settingStore = useSettingV1Store();
const databaseCatalog = useDatabaseCatalog(database.name, false);
const catalog = useVueState(() => databaseCatalog.value);
+ 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(
() => featureToRef(PlanFeature.FEATURE_DATA_MASKING).value
);
@@ -160,6 +202,11 @@ export function DatabaseCatalogPanel({ database }: { database: Database }) {
const instance = getInstanceResource(database);
const isMaskingForNoSQL = instanceV1MaskingForNoSQL(instance);
const project = getDatabaseProject(database);
+ const classificationConfig = useVueState(() =>
+ settingStore.getProjectClassification(
+ project.dataClassificationConfigId ?? ""
+ )
+ );
const hasUpdateCatalogPermission = hasProjectPermissionV2(
project,
"bb.databaseCatalogs.update"
@@ -179,9 +226,9 @@ export function DatabaseCatalogPanel({ database }: { database: Database }) {
}
return columnList.filter((item) => {
return (
- item.schema.includes(normalizedSearchText) ||
- item.table.includes(normalizedSearchText) ||
- item.column.includes(normalizedSearchText)
+ item.schema.toLowerCase().includes(normalizedSearchText) ||
+ item.table.toLowerCase().includes(normalizedSearchText) ||
+ item.column.toLowerCase().includes(normalizedSearchText)
);
});
}, [columnList, normalizedSearchText]);
@@ -189,6 +236,25 @@ export function DatabaseCatalogPanel({ database }: { database: Database }) {
const openGrantAccessDrawer =
showGrantAccessDrawer && checkedColumnList.length > 0;
+ const semanticTypeOptions = useMemo(
+ () =>
+ semanticTypeList.map((semanticType) => ({
+ label: semanticType.title || semanticType.id,
+ value: semanticType.id,
+ })),
+ [semanticTypeList]
+ );
+ const classificationOptions = useMemo(
+ () =>
+ Object.values(classificationConfig?.classification ?? {}).map(
+ (classification) => ({
+ label: classification.title || classification.id,
+ value: classification.id,
+ })
+ ),
+ [classificationConfig]
+ );
+
useEffect(() => {
setSearchText("");
setCheckedColumnList([]);
@@ -196,6 +262,17 @@ export function DatabaseCatalogPanel({ database }: { database: Database }) {
setShowGrantAccessDrawer(false);
}, [database.name]);
+ useEffect(() => {
+ void settingStore.getOrFetchSettingByName(
+ Setting_SettingName.SEMANTIC_TYPES,
+ true
+ );
+ void settingStore.getOrFetchSettingByName(
+ Setting_SettingName.DATA_CLASSIFICATION,
+ true
+ );
+ }, [settingStore]);
+
const removeMaskingExceptions = async (sensitiveColumn: MaskData) => {
const policy = await policyStore.getOrFetchPolicyByParentAndType({
parentPath: database.project,
@@ -231,9 +308,64 @@ export function DatabaseCatalogPanel({ database }: { database: Database }) {
};
const handleDelete = async (item: MaskData) => {
+ const deletedColumnId = getMaskDataIdentifier(item);
+ setCheckedColumnList((current) =>
+ current.filter(
+ (selectedColumn) =>
+ getMaskDataIdentifier(selectedColumn) !== deletedColumnId
+ )
+ );
+ if (hasSemanticType(item.target)) {
+ item.target.semanticType = "";
+ }
+ if (hasClassificationType(item.target)) {
+ item.target.classification = "";
+ }
+ if (databaseCatalog.value) {
+ await databaseCatalogStore.updateDatabaseCatalog(databaseCatalog.value);
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.removed"),
+ });
+ }
await removeMaskingExceptions(item);
};
+ const handleSemanticTypeChange = async (
+ item: MaskData,
+ semanticTypeId: string
+ ) => {
+ if (!hasSemanticType(item.target) || !databaseCatalog.value) {
+ return;
+ }
+ item.target.semanticType = semanticTypeId;
+ item.semanticTypeId = semanticTypeId;
+ await databaseCatalogStore.updateDatabaseCatalog(databaseCatalog.value);
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.updated"),
+ });
+ };
+
+ const handleClassificationChange = async (
+ item: MaskData,
+ classificationId: string
+ ) => {
+ if (!hasClassificationType(item.target) || !databaseCatalog.value) {
+ return;
+ }
+ item.target.classification = classificationId;
+ item.classificationId = classificationId;
+ await databaseCatalogStore.updateDatabaseCatalog(databaseCatalog.value);
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.updated"),
+ });
+ };
+
const handleGrantAccessClick = () => {
if (!hasSensitiveDataFeature) {
setShowFeatureDialog(true);
@@ -284,15 +416,17 @@ export function DatabaseCatalogPanel({ database }: { database: Database }) {
)}
</div>
- <SensitiveColumnTableBridge
- database={database}
- rowClickable={false}
+ <SensitiveColumnTable
+ classificationOptions={classificationOptions}
rowSelectable={!isMaskingForNoSQL}
+ semanticTypeOptions={semanticTypeOptions}
showOperation={hasUpdateCatalogPermission && hasSensitiveDataFeature}
columnList={filteredColumnList}
checkedColumnList={checkedColumnList}
+ onClassificationChange={handleClassificationChange}
onCheckedColumnListChange={setCheckedColumnList}
onDelete={handleDelete}
+ onSemanticTypeChange={handleSemanticTypeChange}
/>
<Dialog open={showFeatureDialog} onOpenChange={setShowFeatureDialog}>
@@ -316,7 +450,7 @@ export function DatabaseCatalogPanel({ database }: { database: Database }) {
</Dialog>
{openGrantAccessDrawer && (
- <GrantAccessDrawerBridge
+ <GrantAccessDialog
open={openGrantAccessDrawer}
columnList={checkedColumnList.map((maskData) => ({
database,
diff --git a/frontend/src/react/pages/project/database-detail/panels/DatabaseChangelogPanel.test.tsx b/frontend/src/react/pages/project/database-detail/panels/DatabaseChangelogPanel.test.tsx
index 018d11a2cc..e657d16408 100644
--- a/frontend/src/react/pages/project/database-detail/panels/DatabaseChangelogPanel.test.tsx
+++ b/frontend/src/react/pages/project/database-detail/panels/DatabaseChangelogPanel.test.tsx
@@ -11,6 +11,12 @@ import type {
).IS_REACT_ACT_ENVIRONMENT = true;
const mocks = vi.hoisted(() => ({
+ localStorage: {
+ clear: vi.fn(),
+ getItem: vi.fn(() => null),
+ removeItem: vi.fn(),
+ setItem: vi.fn(),
+ },
useTranslation: vi.fn(() => ({
t: (key: string) => key,
})),
@@ -29,6 +35,8 @@ const mocks = vi.hoisted(() => ({
let DatabaseChangelogPanel: typeof import("./DatabaseChangelogPanel").DatabaseChangelogPanel;
+vi.stubGlobal("localStorage", mocks.localStorage);
+
vi.mock("react-i18next", () => ({
useTranslation: mocks.useTranslation,
}));
@@ -60,8 +68,8 @@ vi.mock("@/plugins/naive-ui", () => ({
vi.mock("@/router", () => ({
router: {
- install: vi.fn(),
push: vi.fn(),
+ install: vi.fn(),
},
}));
@@ -71,10 +79,6 @@ vi.mock("@/react/components/ui/button", () => ({
),
}));
-vi.mock("@/react/hooks/useVueState", () => ({
- useVueState: <T,>(getter: () => T) => getter(),
-}));
-
vi.mock("@/store", () => ({
pinia: {
install: vi.fn(),
@@ -85,6 +89,11 @@ vi.mock("@/store", () => ({
}),
}));
+vi.mock("@/utils/v1/changelog", () => ({
+ changelogLink: (changelog: { name: string }) =>
+ `/changelogs/${changelog.name}`,
+}));
+
const renderIntoContainer = (element: ReturnType<typeof createElement>) => {
const container = document.createElement("div");
const root = createRoot(container);
@@ -121,30 +130,27 @@ beforeEach(async () => {
mocks.useTranslation.mockReturnValue({
t: (key: string) => key,
});
+ mocks.localStorage.clear.mockReset();
+ mocks.localStorage.getItem.mockReset();
+ mocks.localStorage.getItem.mockReturnValue(null);
+ mocks.localStorage.removeItem.mockReset();
+ mocks.localStorage.setItem.mockReset();
mocks.fetchChangelogList.mockReset();
mocks.fetchChangelogList.mockResolvedValue({
nextPageToken: "",
changelogs: [
{
name: "instances/inst1/databases/db1/changelogs/1",
+ planTitle: "Release 1",
} as Changelog,
],
});
mocks.createApp.mockReset();
- mocks.createApp.mockImplementation((options: { render: () => unknown }) => ({
+ mocks.createApp.mockImplementation(() => ({
use() {
return this;
},
- mount(element: Element) {
- const vnode = options.render() as {
- props?: {
- changelogs?: Changelog[];
- };
- };
- element.innerHTML = (vnode.props?.changelogs ?? [])
- .map((changelog) => `<div>${changelog.name}</div>`)
- .join("");
- },
+ mount() {},
unmount: vi.fn(),
}));
@@ -153,7 +159,7 @@ beforeEach(async () => {
});
describe("DatabaseChangelogPanel", () => {
- test("loads changelog rows through the paged fetcher", async () => {
+ test("renders changelog rows in a React table", async () => {
const { container, render, unmount } = renderIntoContainer(
createElement(DatabaseChangelogPanel, {
database: makeDatabase(),
@@ -168,9 +174,11 @@ describe("DatabaseChangelogPanel", () => {
pageSize: expect.any(Number),
pageToken: "",
});
+ expect(container.querySelector("table")).not.toBeNull();
expect(container.textContent).toContain(
"instances/inst1/databases/db1/changelogs/1"
);
+ expect(container.textContent).toContain("Release 1");
unmount();
});
diff --git a/frontend/src/react/pages/project/database-detail/panels/DatabaseChangelogPanel.tsx b/frontend/src/react/pages/project/database-detail/panels/DatabaseChangelogPanel.tsx
index 620b9a2cdf..69a01ca7bf 100644
--- a/frontend/src/react/pages/project/database-detail/panels/DatabaseChangelogPanel.tsx
+++ b/frontend/src/react/pages/project/database-detail/panels/DatabaseChangelogPanel.tsx
@@ -1,52 +1,11 @@
-import { useCallback, useEffect, useRef } from "react";
-import { createApp, h } from "vue";
-import { ChangelogDataTable } from "@/components/Changelog";
-import i18n from "@/plugins/i18n";
-import NaiveUI from "@/plugins/naive-ui";
+import { useCallback } from "react";
import { PagedTableFooter, usePagedData } from "@/react/hooks/usePagedData";
-import { router } from "@/router";
-import { pinia, useChangelogStore } from "@/store";
+import { useChangelogStore } from "@/store";
import type {
Changelog,
Database,
} from "@/types/proto-es/v1/database_service_pb";
-
-function VueChangelogTableMount({
- changelogs,
- loading,
-}: {
- changelogs: Changelog[];
- loading: boolean;
-}) {
- const containerRef = useRef<HTMLDivElement>(null);
-
- useEffect(() => {
- if (!containerRef.current) {
- return;
- }
-
- const app = createApp({
- render() {
- return h(ChangelogDataTable as never, {
- key: `changelog-table.${changelogs
- .map((changelog) => changelog.name)
- .join(",")}`,
- changelogs,
- loading,
- showSelection: false,
- });
- },
- });
- app.use(router).use(pinia).use(i18n).use(NaiveUI);
- app.mount(containerRef.current);
-
- return () => {
- app.unmount();
- };
- }, [changelogs, loading]);
-
- return <div ref={containerRef} />;
-}
+import { DatabaseChangelogTable } from "../changelog/DatabaseChangelogTable";
export function DatabaseChangelogPanel({ database }: { database: Database }) {
const changelogStore = useChangelogStore();
@@ -78,7 +37,7 @@ export function DatabaseChangelogPanel({ database }: { database: Database }) {
return (
<div className="flex flex-col gap-y-4">
- <VueChangelogTableMount
+ <DatabaseChangelogTable
changelogs={paged.dataList}
loading={paged.isLoading}
/>
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 d2e780c3bf..f1af1daa6e 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
@@ -1,61 +1,66 @@
import { act, createElement } from "react";
import { createRoot } from "react-dom/client";
import { beforeEach, describe, expect, test, vi } from "vitest";
-import type { Database } from "@/types/proto-es/v1/database_service_pb";
+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(() => ({
- localStorage: {
- clear: vi.fn(),
- getItem: vi.fn(() => null),
- removeItem: vi.fn(),
- setItem: vi.fn(),
- },
- schemaList: [{ name: "public" }, { name: "sales" }],
- routerReplace: vi.fn(),
- overviewInfoBridge: vi.fn(() => <div data-testid="overview-info-bridge" />),
- objectExplorerBridge: vi.fn(
- ({
- selectedSchemaName,
- tableSearchKeyword,
- onSelectedSchemaNameChange,
- onTableSearchKeywordChange,
- }: {
- selectedSchemaName: string;
- tableSearchKeyword: string;
- onSelectedSchemaNameChange: (value: string) => void;
- onTableSearchKeywordChange: (value: string) => void;
- }) => (
- <div data-testid="object-explorer-bridge">
- <select
- value={selectedSchemaName}
- onChange={(event) => onSelectedSchemaNameChange(event.target.value)}
- >
- {mocks.schemaList.map((schema) => (
- <option key={schema.name} value={schema.name}>
- {schema.name}
- </option>
- ))}
- </select>
- <input
- placeholder="common.filter-by-name"
- value={tableSearchKeyword}
- onChange={(event) => onTableSearchKeywordChange(event.target.value)}
- />
- </div>
- )
- ),
- useVueState: vi.fn(),
- useDBSchemaV1Store: vi.fn(),
-}));
+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(),
+ getTableCatalog: vi.fn(),
+ featureToRef: vi.fn(() => ({ value: true })),
+ getDatabaseProject: vi.fn((database: { project: string }) => ({
+ name: database.project,
+ dataClassificationConfigId: "classification-config",
+ })),
+ hasProjectPermissionV2: vi.fn(
+ (_project?: unknown, _permission?: string) => true
+ ),
+ getDatabaseEngine: vi.fn(() => Engine.POSTGRES),
+ hasSchemaProperty: vi.fn(() => true),
+ instanceV1HasCollationAndCharacterSet: vi.fn(() => true),
+ instanceV1SupportsPackage: vi.fn(() => false),
+ instanceV1SupportsSequence: 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,
}));
@@ -63,36 +68,60 @@ vi.mock("@/react/hooks/useVueState", () => ({
vi.mock("@/router", () => ({
router: {
replace: mocks.routerReplace,
- currentRoute: {
- value: {
- query: {},
- },
- },
- },
-}));
-
-vi.mock("@/plugins/i18n", () => ({
- default: {
- install: vi.fn(),
- },
-}));
-
-vi.mock("@/plugins/naive-ui", () => ({
- default: {
- install: vi.fn(),
+ currentRoute: mocks.currentRoute,
},
}));
vi.mock("@/store", () => ({
useDBSchemaV1Store: mocks.useDBSchemaV1Store,
+ useDatabaseCatalog: mocks.useDatabaseCatalog,
+ getTableCatalog: mocks.getTableCatalog,
+ featureToRef: mocks.featureToRef,
}));
-vi.mock("../legacy/DatabaseOverviewInfoBridge", () => ({
- DatabaseOverviewInfoBridge: mocks.overviewInfoBridge,
+vi.mock("@/utils", () => ({
+ bytesToString: mocks.bytesToString,
+ getDatabaseEngine: mocks.getDatabaseEngine,
+ getDatabaseProject: mocks.getDatabaseProject,
+ humanizeDate: mocks.humanizeDate,
+ hasProjectPermissionV2: mocks.hasProjectPermissionV2,
+ hasSchemaProperty: mocks.hasSchemaProperty,
+ instanceV1HasCollationAndCharacterSet:
+ mocks.instanceV1HasCollationAndCharacterSet,
+ instanceV1SupportsPackage: mocks.instanceV1SupportsPackage,
+ instanceV1SupportsSequence: mocks.instanceV1SupportsSequence,
}));
-vi.mock("../legacy/DatabaseObjectExplorerBridge", () => ({
- DatabaseObjectExplorerBridge: mocks.objectExplorerBridge,
+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>) => {
@@ -120,18 +149,6 @@ const flush = async () => {
});
};
-const setInputValue = (input: HTMLInputElement, value: string) => {
- act(() => {
- const descriptor = Object.getOwnPropertyDescriptor(
- HTMLInputElement.prototype,
- "value"
- );
- descriptor?.set?.call(input, value);
- input.dispatchEvent(new Event("input", { bubbles: true }));
- input.dispatchEvent(new Event("change", { bubbles: true }));
- });
-};
-
const setSelectValue = (select: HTMLSelectElement, value: string) => {
act(() => {
const descriptor = Object.getOwnPropertyDescriptor(
@@ -139,28 +156,116 @@ const setSelectValue = (select: HTMLSelectElement, value: string) => {
"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/db1",
+ 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.overviewInfoBridge.mockClear();
- mocks.objectExplorerBridge.mockClear();
+ mocks.routerReplace.mockImplementation(() => Promise.resolve());
+ mocks.getDatabaseProject.mockReset();
+ mocks.getDatabaseProject.mockImplementation(
+ (database: { project: string }) => ({
+ name: database.project,
+ dataClassificationConfigId: "classification-config",
+ })
+ );
+ mocks.hasProjectPermissionV2.mockReset();
+ mocks.hasProjectPermissionV2.mockReturnValue(true);
+ mocks.getDatabaseEngine.mockReset();
+ mocks.getDatabaseEngine.mockReturnValue(Engine.POSTGRES);
+ mocks.hasSchemaProperty.mockReset();
+ mocks.hasSchemaProperty.mockReturnValue(true);
+ mocks.instanceV1HasCollationAndCharacterSet.mockReset();
+ mocks.instanceV1HasCollationAndCharacterSet.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.getTableCatalog.mockReset();
+ mocks.getTableCatalog.mockReturnValue({
+ classification: "",
+ });
+ mocks.featureToRef.mockReset();
+ mocks.featureToRef.mockReturnValue({
+ value: true,
});
mocks.useVueState.mockReset();
mocks.useVueState.mockImplementation((getter: () => unknown) => getter());
@@ -170,7 +275,108 @@ beforeEach(async () => {
});
describe("DatabaseOverviewPanel", () => {
- test("keeps schema selection and search state in React", async () => {
+ 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("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(),
@@ -185,22 +391,73 @@ describe("DatabaseOverviewPanel", () => {
"select"
) as HTMLSelectElement | null;
expect(select).not.toBeNull();
- setSelectValue(select as HTMLSelectElement, "sales");
- const input = container.querySelector("input") as HTMLInputElement | null;
- expect(input).not.toBeNull();
- setInputValue(input as HTMLInputElement, "book");
+ 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.querySelector("select") as HTMLSelectElement).value).toBe(
- "sales"
+ 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,
+ }),
+ })
);
- expect((container.querySelector("input") as HTMLInputElement).value).toBe(
- "book"
+ 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 () => {
@@ -214,16 +471,76 @@ describe("DatabaseOverviewPanel", () => {
render();
await flush();
- expect(
- container.querySelector('[data-testid="overview-info-bridge"]')
- ).not.toBeNull();
- expect(
- container.querySelector('[data-testid="object-explorer-bridge"]')
- ).toBeNull();
+ 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" };
@@ -250,4 +567,318 @@ describe("DatabaseOverviewPanel", () => {
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 = {};
+ });
});
diff --git a/frontend/src/react/pages/project/database-detail/panels/DatabaseOverviewPanel.tsx b/frontend/src/react/pages/project/database-detail/panels/DatabaseOverviewPanel.tsx
index a49d9139b3..ae6b209238 100644
--- a/frontend/src/react/pages/project/database-detail/panels/DatabaseOverviewPanel.tsx
+++ b/frontend/src/react/pages/project/database-detail/panels/DatabaseOverviewPanel.tsx
@@ -4,8 +4,8 @@ import { router } from "@/router";
import { useDBSchemaV1Store } from "@/store";
import type { Database } from "@/types/proto-es/v1/database_service_pb";
import { getDatabaseProject, hasProjectPermissionV2 } from "@/utils";
-import { DatabaseObjectExplorerBridge } from "../legacy/DatabaseObjectExplorerBridge";
-import { DatabaseOverviewInfoBridge } from "../legacy/DatabaseOverviewInfoBridge";
+import { DatabaseObjectExplorer } from "../overview/DatabaseObjectExplorer";
+import { DatabaseOverviewInfo } from "../overview/DatabaseOverviewInfo";
export function DatabaseOverviewPanel({
database,
@@ -87,13 +87,13 @@ export function DatabaseOverviewPanel({
return (
<div>
- <DatabaseOverviewInfoBridge database={database} className="pb-6" />
+ <DatabaseOverviewInfo database={database} />
{allowViewSchema && (
<div className="border-t border-block-border pt-6">
- <DatabaseObjectExplorerBridge
+ <DatabaseObjectExplorer
database={database}
- loading={schemaList.length > 0 && !selectedSchemaName}
+ loading={schemaList.length > 0 && !schemaSelectionReady}
selectedSchemaName={selectedSchemaName}
tableSearchKeyword={tableSearchKeyword}
externalTableSearchKeyword={externalTableSearchKeyword}
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 dc63d8b24a..4124e9482d 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
@@ -2,17 +2,31 @@ import { act, createElement } from "react";
import { createRoot } from "react-dom/client";
import { beforeEach, describe, expect, test, vi } from "vitest";
import type { Database } from "@/types/proto-es/v1/database_service_pb";
-import type { Revision } from "@/types/proto-es/v1/revision_service_pb";
+import {
+ type Revision,
+ Revision_Type,
+} from "@/types/proto-es/v1/revision_service_pb";
(
globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
).IS_REACT_ACT_ENVIRONMENT = true;
const mocks = vi.hoisted(() => ({
+ confirm: vi.fn(() => true),
+ localStorage: {
+ clear: vi.fn(),
+ getItem: vi.fn(() => null),
+ removeItem: vi.fn(),
+ setItem: vi.fn(),
+ },
useTranslation: vi.fn(() => ({
t: (key: string) => key,
})),
listRevisions: vi.fn(),
+ batchCreateRevisions: vi.fn(),
+ createSheet: vi.fn(),
+ deleteRevision: vi.fn(),
+ pushNotification: vi.fn(),
currentUser: {
value: {
@@ -27,6 +41,9 @@ const mocks = vi.hoisted(() => ({
let DatabaseRevisionPanel: typeof import("./DatabaseRevisionPanel").DatabaseRevisionPanel;
+vi.stubGlobal("localStorage", mocks.localStorage);
+vi.stubGlobal("confirm", mocks.confirm);
+
vi.mock("react-i18next", () => ({
useTranslation: mocks.useTranslation,
}));
@@ -60,6 +77,12 @@ vi.mock("@/plugins/naive-ui", () => ({
},
}));
+vi.mock("@/react/components/ui/button", () => ({
+ Button: (props: React.ButtonHTMLAttributes<HTMLButtonElement>) => (
+ <button {...props} />
+ ),
+}));
+
vi.mock("@/router", () => ({
router: {
install: vi.fn(),
@@ -67,27 +90,41 @@ vi.mock("@/router", () => ({
},
}));
-vi.mock("@/react/components/ui/button", () => ({
- Button: (props: React.ButtonHTMLAttributes<HTMLButtonElement>) => (
- <button {...props} />
+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/hooks/useVueState", () => ({
- useVueState: <T,>(getter: () => T) => getter(),
+vi.mock("@/connect", () => ({
+ revisionServiceClientConnect: {
+ listRevisions: mocks.listRevisions,
+ batchCreateRevisions: mocks.batchCreateRevisions,
+ },
}));
vi.mock("@/store", () => ({
pinia: {
install: vi.fn(),
},
+ pushNotification: mocks.pushNotification,
useCurrentUserV1: () => mocks.currentUser,
+ useRevisionStore: () => ({
+ deleteRevision: mocks.deleteRevision,
+ }),
+ useSheetV1Store: () => ({
+ createSheet: mocks.createSheet,
+ }),
}));
-vi.mock("@/connect", () => ({
- revisionServiceClientConnect: {
- listRevisions: mocks.listRevisions,
- },
+vi.mock("@/utils/v1/revision", () => ({
+ getRevisionType: (type: number) => `type-${type}`,
+ revisionLink: (revision: { name: string }) => `/revisions/${revision.name}`,
}));
const renderIntoContainer = (element: ReturnType<typeof createElement>) => {
@@ -123,6 +160,21 @@ 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",
@@ -134,53 +186,47 @@ beforeEach(async () => {
mocks.useTranslation.mockReturnValue({
t: (key: string) => key,
});
+ mocks.confirm.mockReset();
+ mocks.confirm.mockReturnValue(true);
+ mocks.localStorage.clear.mockReset();
+ mocks.localStorage.getItem.mockReset();
+ mocks.localStorage.getItem.mockReturnValue(null);
+ mocks.localStorage.removeItem.mockReset();
+ mocks.localStorage.setItem.mockReset();
mocks.listRevisions.mockReset();
mocks.listRevisions.mockResolvedValue({
nextPageToken: "",
revisions: [
{
name: "instances/inst1/databases/db1/revisions/1",
+ version: "1.0.0",
+ type: Revision_Type.VERSIONED,
+ } 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.createApp.mockReset();
- mocks.createApp.mockImplementation((options: { render: () => unknown }) => ({
+ mocks.createApp.mockImplementation(() => ({
use() {
return this;
},
- mount(element: Element) {
- const vnode = options.render() as {
- props?: Record<string, unknown>;
- };
- if (Array.isArray(vnode.props?.revisions)) {
- const deleteButton = document.createElement("button");
- deleteButton.dataset.testid = "revision-delete";
- deleteButton.addEventListener("click", () => {
- (vnode.props?.onDelete as (() => void) | undefined)?.();
- });
- element.replaceChildren(deleteButton);
- return;
- }
- if (vnode.props?.show) {
- const drawer = document.createElement("div");
- drawer.dataset.testid = "create-revision-drawer";
- const createButton = document.createElement("button");
- createButton.dataset.testid = "create-revision-created";
- createButton.addEventListener("click", () => {
- (
- vnode.props?.onCreated as
- | ((revisions: Revision[]) => void)
- | undefined
- )?.([
- { name: "instances/inst1/databases/db1/revisions/2" } as Revision,
- ]);
- });
- drawer.appendChild(createButton);
- element.replaceChildren(drawer);
- return;
- }
- element.replaceChildren();
- },
+ mount() {},
unmount: vi.fn(),
}));
@@ -189,7 +235,7 @@ beforeEach(async () => {
});
describe("DatabaseRevisionPanel", () => {
- test("opens the revision import flow and refreshes after create", async () => {
+ test("opens the revision import dialog and refreshes after create", async () => {
const { container, render, unmount } = renderIntoContainer(
createElement(DatabaseRevisionPanel, {
database: makeDatabase(),
@@ -207,15 +253,33 @@ describe("DatabaseRevisionPanel", () => {
click(importButton as HTMLButtonElement);
await flush();
- const createButton = container.querySelector(
- '[data-testid="create-revision-created"]'
- ) as HTMLButtonElement | null;
- expect(createButton).not.toBeNull();
+ 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;");
+
+ const createButton = Array.from(container.querySelectorAll("button")).find(
+ (button) => button.textContent === "common.create"
+ ) as HTMLButtonElement | undefined;
+ expect(createButton).toBeDefined();
click(createButton as HTMLButtonElement);
await flush();
- expect(mocks.listRevisions).toHaveBeenCalledTimes(2);
+ expect(mocks.createSheet).toHaveBeenCalledTimes(1);
+ expect(mocks.batchCreateRevisions).toHaveBeenCalledTimes(1);
+ expect(mocks.listRevisions).toHaveBeenCalledTimes(3);
unmount();
});
@@ -230,16 +294,103 @@ describe("DatabaseRevisionPanel", () => {
render();
await flush();
- const deleteButton = container.querySelector(
- '[data-testid="revision-delete"]'
- ) as HTMLButtonElement | null;
- expect(deleteButton).not.toBeNull();
+ expect(container.querySelector("table")).not.toBeNull();
+ expect(container.textContent).toContain("1.0.0");
+
+ const deleteButton = Array.from(container.querySelectorAll("button")).find(
+ (button) =>
+ button.dataset.name === "instances/inst1/databases/db1/revisions/1"
+ ) as HTMLButtonElement | undefined;
+ expect(deleteButton).toBeDefined();
click(deleteButton as HTMLButtonElement);
await flush();
+ expect(mocks.confirm).toHaveBeenCalledWith(
+ "database.revision.delete-confirm-dialog"
+ );
+ expect(mocks.deleteRevision).toHaveBeenCalledWith(
+ "instances/inst1/databases/db1/revisions/1"
+ );
expect(mocks.listRevisions).toHaveBeenCalledTimes(2);
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 d096d3724f..40d26a692b 100644
--- a/frontend/src/react/pages/project/database-detail/panels/DatabaseRevisionPanel.tsx
+++ b/frontend/src/react/pages/project/database-detail/panels/DatabaseRevisionPanel.tsx
@@ -1,106 +1,27 @@
import { create } from "@bufbuild/protobuf";
-import { useCallback, useEffect, useRef, useState } from "react";
+import { useCallback, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
-import { createApp, h } from "vue";
-import { RevisionDataTable } from "@/components/Revision";
-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 { router } from "@/router";
-import { pinia } from "@/store";
+import { 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";
-
-function VueRevisionTableMount({
- revisions,
- loading,
- onDelete,
-}: {
- revisions: Revision[];
- loading: boolean;
- onDelete: () => void;
-}) {
- const containerRef = useRef<HTMLDivElement>(null);
-
- useEffect(() => {
- if (!containerRef.current) {
- return;
- }
-
- const app = createApp({
- render() {
- return h(RevisionDataTable as never, {
- key: `revision-table.${revisions
- .map((revision) => revision.name)
- .join(",")}`,
- revisions,
- loading,
- showSelection: true,
- onDelete,
- });
- },
- });
- app.use(router).use(pinia).use(i18n).use(NaiveUI);
- app.mount(containerRef.current);
-
- return () => {
- app.unmount();
- };
- }, [loading, onDelete, revisions]);
-
- return <div ref={containerRef} />;
-}
-
-function VueCreateRevisionDrawerMount({
- databaseName,
- open,
- onOpenChange,
- onCreated,
-}: {
- databaseName: string;
- open: boolean;
- onOpenChange: (open: boolean) => void;
- onCreated: (revisions: RevisionMessage[]) => void;
-}) {
- const containerRef = useRef<HTMLDivElement>(null);
-
- useEffect(() => {
- if (!containerRef.current) {
- return;
- }
-
- const app = createApp({
- render() {
- return h(CreateRevisionDrawer as never, {
- database: databaseName,
- show: open,
- "onUpdate:show": onOpenChange,
- onCreated,
- });
- },
- });
- app.use(router).use(pinia).use(i18n).use(NaiveUI);
- app.mount(containerRef.current);
-
- return () => {
- app.unmount();
- };
- }, [databaseName, onCreated, onOpenChange, open]);
-
- return <div ref={containerRef} />;
-}
+import { CreateRevisionDialog } from "../revision/CreateRevisionDialog";
+import { DatabaseRevisionTable } from "../revision/DatabaseRevisionTable";
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,
@@ -123,11 +44,59 @@ 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[]) => {
setShowCreateRevisionDrawer(false);
@@ -140,6 +109,17 @@ export function DatabaseRevisionPanel({ database }: { database: Database }) {
paged.refresh();
}, [paged.refresh]);
+ const handleDelete = useCallback(
+ async (name: string) => {
+ if (!window.confirm(t("database.revision.delete-confirm-dialog"))) {
+ return;
+ }
+ await revisionStore.deleteRevision(name);
+ handleRevisionDeleted();
+ },
+ [handleRevisionDeleted, revisionStore, t]
+ );
+
return (
<>
<div className="flex flex-col gap-y-2">
@@ -149,10 +129,10 @@ export function DatabaseRevisionPanel({ database }: { database: Database }) {
{t("common.import")}
</Button>
</div>
- <VueRevisionTableMount
+ <DatabaseRevisionTable
revisions={paged.dataList}
loading={paged.isLoading}
- onDelete={handleRevisionDeleted}
+ onDelete={handleDelete}
/>
<PagedTableFooter
pageSize={paged.pageSize}
@@ -163,9 +143,12 @@ export function DatabaseRevisionPanel({ database }: { database: Database }) {
onLoadMore={paged.loadMore}
/>
</div>
- <VueCreateRevisionDrawerMount
+ <CreateRevisionDialog
databaseName={database.name}
+ existingVersions={existingVersions}
+ isCheckingExistingVersions={isLoadingExistingVersions}
open={showCreateRevisionDrawer}
+ projectName={database.project}
onOpenChange={setShowCreateRevisionDrawer}
onCreated={handleRevisionCreated}
/>
diff --git a/frontend/src/react/pages/project/database-detail/revision/CreateRevisionDialog.tsx b/frontend/src/react/pages/project/database-detail/revision/CreateRevisionDialog.tsx
new file mode 100644
index 0000000000..9210026e01
--- /dev/null
+++ b/frontend/src/react/pages/project/database-detail/revision/CreateRevisionDialog.tsx
@@ -0,0 +1,198 @@
+import { create } from "@bufbuild/protobuf";
+import { useState } from "react";
+import { useTranslation } from "react-i18next";
+import { revisionServiceClientConnect } from "@/connect";
+import { Button } from "@/react/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogTitle,
+} from "@/react/components/ui/dialog";
+import { pushNotification, useSheetV1Store } from "@/store";
+import {
+ BatchCreateRevisionsRequestSchema,
+ CreateRevisionRequestSchema,
+ type Revision,
+ Revision_Type,
+} from "@/types/proto-es/v1/revision_service_pb";
+
+export function CreateRevisionDialog({
+ databaseName,
+ existingVersions,
+ isCheckingExistingVersions,
+ open,
+ projectName,
+ onCreated,
+ onOpenChange,
+}: {
+ databaseName: string;
+ existingVersions: string[];
+ isCheckingExistingVersions: boolean;
+ open: boolean;
+ projectName: string;
+ onCreated: (revisions: Revision[]) => void;
+ onOpenChange: (open: boolean) => void;
+}) {
+ const { t } = useTranslation();
+ const sheetStore = useSheetV1Store();
+ const [version, setVersion] = useState("");
+ const [statement, setStatement] = useState("");
+ const [type, setType] = useState(Revision_Type.VERSIONED);
+ const [isCreating, setIsCreating] = useState(false);
+ const normalizedVersion = version.trim();
+ const isDuplicateVersion = existingVersions.includes(normalizedVersion);
+ const isValidVersion = /^(\d+)(\.(\d+))*$/.test(normalizedVersion);
+
+ const reset = () => {
+ setVersion("");
+ setStatement("");
+ setType(Revision_Type.VERSIONED);
+ };
+
+ const handleOpenChange = (nextOpen: boolean) => {
+ if (!nextOpen) {
+ reset();
+ }
+ onOpenChange(nextOpen);
+ };
+
+ const canCreate =
+ normalizedVersion.length > 0 &&
+ statement.trim().length > 0 &&
+ !isCheckingExistingVersions &&
+ isValidVersion &&
+ !isDuplicateVersion;
+
+ const handleCreate = async () => {
+ if (!canCreate || isCreating) {
+ return;
+ }
+
+ setIsCreating(true);
+ try {
+ const sheet = await sheetStore.createSheet(projectName, {
+ content: new TextEncoder().encode(statement),
+ });
+ const response = await revisionServiceClientConnect.batchCreateRevisions(
+ create(BatchCreateRevisionsRequestSchema, {
+ parent: databaseName,
+ requests: [
+ create(CreateRevisionRequestSchema, {
+ parent: databaseName,
+ revision: {
+ sheet: sheet.name,
+ type,
+ version: normalizedVersion,
+ },
+ }),
+ ],
+ })
+ );
+ onCreated(response.revisions);
+ handleOpenChange(false);
+ } catch (error) {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("common.error"),
+ description: error instanceof Error ? error.message : String(error),
+ });
+ } finally {
+ setIsCreating(false);
+ }
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={handleOpenChange}>
+ <DialogContent className="max-w-3xl p-6">
+ <DialogTitle>{t("database.revision.import-revision")}</DialogTitle>
+ <div className="mt-4 space-y-4">
+ <div className="space-y-2">
+ <label
+ className="block text-sm font-medium text-control"
+ htmlFor="revision-version"
+ >
+ {t("common.version")}
+ </label>
+ <input
+ id="revision-version"
+ className="w-full rounded-xs border border-control-border px-3 py-2 text-sm text-main"
+ name="version"
+ value={version}
+ onChange={(event) => setVersion(event.target.value)}
+ />
+ {normalizedVersion.length > 0 && !isValidVersion && (
+ <p className="text-sm text-error">
+ {t("database.revision.invalid-version-format")}
+ </p>
+ )}
+ {isDuplicateVersion && (
+ <p className="text-sm text-error">
+ {t("database.revision.version-already-exists")}
+ </p>
+ )}
+ {isCheckingExistingVersions && (
+ <p className="text-sm text-control-light">
+ {t("common.loading")}...
+ </p>
+ )}
+ </div>
+ <div className="space-y-2">
+ <label
+ className="block text-sm font-medium text-control"
+ htmlFor="revision-type"
+ >
+ {t("common.type")}
+ </label>
+ <select
+ id="revision-type"
+ className="w-full rounded-xs border border-control-border px-3 py-2 text-sm text-main"
+ value={String(type)}
+ onChange={(event) =>
+ setType(Number(event.target.value) as Revision_Type)
+ }
+ >
+ <option value={String(Revision_Type.VERSIONED)}>
+ {t("database.revision.type-versioned")}
+ </option>
+ <option value={String(Revision_Type.DECLARATIVE)}>
+ {t("database.revision.type-declarative")}
+ </option>
+ </select>
+ </div>
+ <div className="space-y-2">
+ <label
+ className="block text-sm font-medium text-control"
+ htmlFor="revision-statement"
+ >
+ {t("common.statement")}
+ </label>
+ <textarea
+ id="revision-statement"
+ className="min-h-48 w-full rounded-xs border border-control-border px-3 py-2 text-sm text-main"
+ name="statement"
+ value={statement}
+ onChange={(event) => setStatement(event.target.value)}
+ />
+ </div>
+ <div className="flex items-center justify-end gap-x-2">
+ <Button
+ type="button"
+ variant="ghost"
+ onClick={() => handleOpenChange(false)}
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button
+ disabled={!canCreate || isCreating}
+ type="button"
+ onClick={() => void handleCreate()}
+ >
+ {isCreating ? t("common.loading") : t("common.create")}
+ </Button>
+ </div>
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/frontend/src/react/pages/project/database-detail/revision/DatabaseRevisionTable.tsx b/frontend/src/react/pages/project/database-detail/revision/DatabaseRevisionTable.tsx
new file mode 100644
index 0000000000..d48e1cef2e
--- /dev/null
+++ b/frontend/src/react/pages/project/database-detail/revision/DatabaseRevisionTable.tsx
@@ -0,0 +1,76 @@
+import { useTranslation } from "react-i18next";
+import { Button } from "@/react/components/ui/button";
+import { router } from "@/router";
+import { getDateForPbTimestampProtoEs } from "@/types";
+import type { Revision } from "@/types/proto-es/v1/revision_service_pb";
+import { humanizeDate } from "@/utils";
+import { getRevisionType, revisionLink } from "@/utils/v1/revision";
+
+export function DatabaseRevisionTable({
+ loading,
+ revisions,
+ onDelete,
+}: {
+ loading: boolean;
+ revisions: Revision[];
+ onDelete: (name: string) => void | Promise<void>;
+}) {
+ const { t } = useTranslation();
+
+ if (loading) {
+ return (
+ <div className="text-sm text-control-light">{t("common.loading")}</div>
+ );
+ }
+
+ 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">
+ <th className="px-4 py-2 font-medium">{t("common.version")}</th>
+ <th className="px-4 py-2 font-medium">{t("common.type")}</th>
+ <th className="px-4 py-2 font-medium">{t("common.created-at")}</th>
+ <th className="px-4 py-2 font-medium">{t("common.operations")}</th>
+ </tr>
+ </thead>
+ <tbody className="divide-y divide-block-border bg-white">
+ {revisions.map((revision) => (
+ <tr key={revision.name}>
+ <td className="px-4 py-3 text-sm text-main">
+ <button
+ className="cursor-pointer text-left hover:text-accent"
+ type="button"
+ onClick={() => void router.push(revisionLink(revision))}
+ >
+ {revision.version || revision.name}
+ </button>
+ </td>
+ <td className="px-4 py-3 text-sm text-control">
+ {getRevisionType(revision.type)}
+ </td>
+ <td className="px-4 py-3 text-sm text-control">
+ {getDateForPbTimestampProtoEs(revision.createTime)
+ ? humanizeDate(
+ getDateForPbTimestampProtoEs(revision.createTime) as Date
+ )
+ : "-"}
+ </td>
+ <td className="px-4 py-3 text-sm text-control">
+ <Button
+ data-name={revision.name}
+ size="sm"
+ type="button"
+ variant="ghost"
+ onClick={() => void onDelete(revision.name)}
+ >
+ {t("common.delete")}
+ </Button>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ );
+}
diff --git a/frontend/src/react/pages/project/database-detail/schema-browser/SchemaBrowserButton.tsx b/frontend/src/react/pages/project/database-detail/schema-browser/SchemaBrowserButton.tsx
new file mode 100644
index 0000000000..0cd1a3a308
--- /dev/null
+++ b/frontend/src/react/pages/project/database-detail/schema-browser/SchemaBrowserButton.tsx
@@ -0,0 +1,50 @@
+import { Workflow } from "lucide-react";
+import { useCallback, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Button } from "@/react/components/ui/button";
+import { useDBSchemaV1Store } from "@/store";
+import type { Database } from "@/types/proto-es/v1/database_service_pb";
+import { SchemaBrowserDialog } from "./SchemaBrowserDialog";
+
+export function SchemaBrowserButton({
+ database,
+ disabled = false,
+}: {
+ database: Database;
+ disabled?: boolean;
+}) {
+ const { t } = useTranslation();
+ const dbSchemaStore = useDBSchemaV1Store();
+ const [open, setOpen] = useState(false);
+
+ const handleOpen = useCallback(async () => {
+ if (disabled) {
+ return;
+ }
+
+ await dbSchemaStore.getOrFetchDatabaseMetadata({
+ database: database.name,
+ skipCache: false,
+ });
+ setOpen(true);
+ }, [database.name, dbSchemaStore, disabled]);
+
+ return (
+ <>
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={disabled}
+ onClick={() => void handleOpen()}
+ >
+ <Workflow className="h-4 w-4" />
+ {t("schema-diagram.self")}
+ </Button>
+ <SchemaBrowserDialog
+ database={database}
+ open={open}
+ onOpenChange={setOpen}
+ />
+ </>
+ );
+}
diff --git a/frontend/src/react/pages/project/database-detail/schema-browser/SchemaBrowserDialog.tsx b/frontend/src/react/pages/project/database-detail/schema-browser/SchemaBrowserDialog.tsx
new file mode 100644
index 0000000000..c34fc5491a
--- /dev/null
+++ b/frontend/src/react/pages/project/database-detail/schema-browser/SchemaBrowserDialog.tsx
@@ -0,0 +1,127 @@
+import { 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 { useVueState } from "@/react/hooks/useVueState";
+import { useDBSchemaV1Store } from "@/store";
+import type { Database } from "@/types/proto-es/v1/database_service_pb";
+
+export function SchemaBrowserDialog({
+ database,
+ open,
+ onOpenChange,
+}: {
+ database: Database;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+}) {
+ const { t } = useTranslation();
+ const dbSchemaStore = useDBSchemaV1Store();
+ const [searchText, setSearchText] = useState("");
+
+ const schemaList = useVueState(() =>
+ dbSchemaStore.getSchemaList(database.name)
+ );
+ const databaseMetadata = useVueState(() =>
+ dbSchemaStore.getDatabaseMetadata(database.name)
+ );
+ const metadataSchemas = databaseMetadata?.schemas ?? [];
+
+ const normalizedSearchText = searchText.trim().toLowerCase();
+ const schemaEntries = useMemo(() => {
+ const fallbackSchemas = metadataSchemas.map((schema) => ({
+ name: schema.name,
+ }));
+ const sourceSchemas =
+ schemaList.length > 0
+ ? schemaList
+ : (fallbackSchemas as typeof schemaList);
+
+ return sourceSchemas
+ .map((schema) => {
+ const schemaName = schema.name;
+ const schemaLabel = schemaName || t("db.schema.default");
+ const tableList = dbSchemaStore.getTableList({
+ database: database.name,
+ schema: schemaName,
+ });
+ const filteredTables = tableList.filter((table) =>
+ table.name.toLowerCase().includes(normalizedSearchText)
+ );
+ const matchesSchema =
+ normalizedSearchText.length === 0 ||
+ schemaLabel.toLowerCase().includes(normalizedSearchText);
+
+ if (!matchesSchema && filteredTables.length === 0) {
+ return undefined;
+ }
+
+ return {
+ schemaLabel,
+ tables:
+ matchesSchema && normalizedSearchText.length === 0
+ ? tableList
+ : filteredTables,
+ };
+ })
+ .filter((entry) => entry !== undefined);
+ }, [
+ database.name,
+ metadataSchemas,
+ dbSchemaStore,
+ normalizedSearchText,
+ schemaList,
+ t,
+ ]);
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="max-w-4xl p-6">
+ <DialogTitle>{t("schema-diagram.self")}</DialogTitle>
+ <div className="mt-4 flex flex-col gap-y-4">
+ <Input
+ value={searchText}
+ placeholder={t("common.search")}
+ onChange={(event) => setSearchText(event.target.value)}
+ />
+
+ <div className="max-h-[70vh] space-y-4 overflow-y-auto pr-1">
+ {schemaEntries.map((entry) => (
+ <section
+ key={entry.schemaLabel}
+ className="rounded-sm border border-control-border"
+ >
+ <div className="border-b border-control-border bg-gray-50 px-4 py-2 text-sm font-medium text-main">
+ {entry.schemaLabel}
+ </div>
+ <div className="px-4 py-3">
+ {entry.tables.length > 0 ? (
+ <ul className="space-y-2 text-sm text-main">
+ {entry.tables.map((table) => (
+ <li key={table.name}>{table.name}</li>
+ ))}
+ </ul>
+ ) : (
+ <div className="text-sm text-control-light">
+ {t("common.no-data")}
+ </div>
+ )}
+ </div>
+ </section>
+ ))}
+
+ {schemaEntries.length === 0 && (
+ <div className="rounded-sm border border-dashed border-control-border px-4 py-6 text-center text-sm text-control-light">
+ {t("common.no-data")}
+ </div>
+ )}
+ </div>
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+}