Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
fix(sql-editor): stop schema-tree rows remounting so the hover panel shows (#21632)
zchpeter596cdd25b73a
diff --git a/frontend/scripts/run-gate.mjs b/frontend/scripts/run-gate.mjsindex 5690fc9cc3..9ece3d4fcd 100644--- a/frontend/scripts/run-gate.mjs+++ b/frontend/scripts/run-gate.mjs@@ -5,11 +5,13 @@// other three are largely single-core, so overlapping them costs little and// takes the gate from ~92s to ~70s.//-// Each stage's output is buffered and printed in a fixed order once every stage-// has finished, so a failure reads the same as it did serially -- interleaved-// live output from four concurrent stages would not.+// Each stage's output is buffered and printed once every stage has finished, so+// a failure reads the same as it did serially -- interleaved live output from+// four concurrent stages would not.import { spawn } from "node:child_process";import { readdirSync } from "node:fs";+import { resolve } from "node:path";+import { fileURLToPath } from "node:url";// Every scripts/check-*.mjs runs, so a new check cannot be left out of the gate.const GUARDS = readdirSync(new URL(".", import.meta.url))@@ -62,24 +64,36 @@ function run({ name, argv, env }) {});}-// Every stage reads the generated sources copied from the backend, so this one-// runs first and on its own.-const prepare = await run({ name: "prepare", argv: ["pnpm", "run", "prepare"] });-if (prepare.code !== 0) {- process.stdout.write(prepare.output);- process.exit(prepare.code);-}+// Prints passing stages, then failing ones, then the failure summary, so the+// failure sits at the end of the log where CI viewers and truncation keep it.+// Sets `process.exitCode` rather than calling `process.exit()`: stdout is a+// pipe on CI, its writes are asynchronous, and exiting early drops their tail.+export function finish(results) {+ const failed = results.filter((r) => r.code !== 0);+ const passed = results.filter((r) => r.code === 0);+ for (const { name, output } of [...passed, ...failed]) {+ process.stdout.write(`\n${"=".repeat(60)}\n${name}\n${"=".repeat(60)}\n${output}`);+ }-const results = await Promise.all(STAGES.map(run));+ // Each stage already reported itself as it finished, so only restate things+ // when something failed and the list is worth having next to the exit.+ if (failed.length > 0) {+ process.stdout.write(`\n${failed.length} stage(s) failed: ${failed.map((r) => r.name).join(", ")}\n`);+ process.exitCode = 1;+ }+}-for (const { name, output } of results) {- process.stdout.write(`\n${"=".repeat(60)}\n${name}\n${"=".repeat(60)}\n${output}`);+async function main() {+ // Every stage reads the generated sources copied from the backend, so this one+ // runs first and on its own.+ const prepare = await run({ name: "prepare", argv: ["pnpm", "run", "prepare"] });+ if (prepare.code !== 0) {+ finish([prepare]);+ return;+ }+ finish(await Promise.all(STAGES.map(run)));}-// Each stage already reported itself as it finished, so only restate things-// when something failed and the list is worth having next to the exit.-const failed = results.filter((r) => r.code !== 0);-if (failed.length > 0) {- process.stdout.write(`\n${failed.length} stage(s) failed: ${failed.map((r) => r.name).join(", ")}\n`);- process.exit(1);+if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {+ await main();}diff --git a/frontend/scripts/run-gate.test.mjs b/frontend/scripts/run-gate.test.mjsnew file mode 100644index 0000000000..eb19149292--- /dev/null+++ b/frontend/scripts/run-gate.test.mjs@@ -0,0 +1,61 @@+// @vitest-environment node+import { spawn } from "node:child_process";+import { fileURLToPath } from "node:url";+import { describe, expect, test } from "vitest";++const GATE = fileURLToPath(new URL("./run-gate.mjs", import.meta.url));++// Runs `finish` in a child whose stdout is a pipe, as it is on CI. A stage's+// `padBytes` is expanded in the child, ahead of its output, to exceed the pipe+// buffer without hitting the argv size limit.+function finishThroughPipe(results) {+ const script = `+ import { finish } from ${JSON.stringify(GATE)};+ const results = ${JSON.stringify(results)}.map(({ padBytes = 0, ...r }) => ({+ ...r,+ output: "x".repeat(padBytes) + r.output,+ }));+ finish(results);+ `;+ return new Promise((done, fail) => {+ const child = spawn(process.execPath, ["--input-type=module", "-e", script], {+ stdio: ["ignore", "pipe", "inherit"],+ });+ const chunks = [];+ child.stdout.on("data", (c) => chunks.push(c));+ child.on("error", fail);+ child.on("close", (code) => done({ code, stdout: Buffer.concat(chunks).toString() }));+ });+}++describe("run-gate finish", () => {+ test("a failing stage's full output reaches a piped stdout, last, before the summary", async () => {+ const { code, stdout } = await finishThroughPipe([+ { name: "biome", code: 0, output: "biome ok\n" },+ {+ name: "vitest",+ code: 1,+ padBytes: 4 * 1024 * 1024,+ output: "\nFAIL src/example.test.tsx > the failing case\n",+ },+ { name: "tsc", code: 0, output: "tsc ok\n" },+ ]);++ expect(code).toBe(1);+ expect(stdout).toContain("FAIL src/example.test.tsx > the failing case");+ expect(stdout.indexOf("tsc ok")).toBeLessThan(stdout.indexOf("\nvitest\n"));+ expect(stdout.endsWith("\n1 stage(s) failed: vitest\n")).toBe(true);+ });++ test("a passing gate exits 0 and prints every stage", async () => {+ const { code, stdout } = await finishThroughPipe([+ { name: "biome", code: 0, output: "biome ok\n" },+ { name: "tsc", code: 0, output: "tsc ok\n" },+ ]);++ expect(code).toBe(0);+ expect(stdout).toContain("biome ok");+ expect(stdout).toContain("tsc ok");+ expect(stdout).not.toContain("stage(s) failed");+ });+});diff --git a/frontend/src/components/ui/tree.test.tsx b/frontend/src/components/ui/tree.test.tsxindex c49e0e3e5b..c47c2e830c 100644--- a/frontend/src/components/ui/tree.test.tsx+++ b/frontend/src/components/ui/tree.test.tsx@@ -1,4 +1,4 @@-import { act } from "react";+import { act, useEffect } from "react";import { createRoot } from "react-dom/client";import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";import type { TreeDataNode } from "./tree";@@ -314,4 +314,63 @@ describe("Tree", () => {expect(container.textContent).not.toContain("audit");expect(container.textContent).not.toContain("log_entry");});+ describe("row identity across parent re-renders", () => {+ const nodes = [+ makeNode("a", "Alpha"),+ makeNode("b", "Beta"),+ makeNode("c", "Gamma"),+ ];+ let mounts: string[];++ function CountedRow({ id, label }: { id: string; label: string }) {+ useEffect(() => {+ mounts.push(id);+ }, [id]);+ return <span data-testid={`row-${id}`}>{label}</span>;+ }++ // Each call builds a fresh renderNode closure, as a consumer does+ // when it passes renderNode inline.+ const renderTree = (suffix: string) =>+ root.render(+ <Tree+ data={nodes}+ renderNode={({ node, style }) => (+ <div style={style}>+ <CountedRow+ id={node.id}+ label={`${node.data.data.label}${suffix}`}+ />+ </div>+ )}+ height={200}+ />+ );++ beforeEach(() => {+ mounts = [];+ });++ test("does not remount rows when the parent re-renders", async () => {+ await act(async () => renderTree(""));+ expect(mounts).toEqual(["a", "b", "c"]);+ const rowBefore = container.querySelector('[data-testid="row-a"]');++ for (let i = 0; i < 5; i++) {+ await act(async () => renderTree(""));+ }++ expect(mounts).toEqual(["a", "b", "c"]);+ expect(container.querySelector('[data-testid="row-a"]')).toBe(rowBefore);+ });++ test("rows render the latest renderNode output", async () => {+ await act(async () => renderTree(""));+ await act(async () => renderTree(" (new)"));++ expect(container.textContent).toContain("Alpha (new)");+ expect(container.textContent).toContain("Gamma (new)");+ expect(mounts).toEqual(["a", "b", "c"]);+ });+ });});diff --git a/frontend/src/components/ui/tree.tsx b/frontend/src/components/ui/tree.tsxindex c3c23fc4e9..6c331a58f7 100644--- a/frontend/src/components/ui/tree.tsx+++ b/frontend/src/components/ui/tree.tsx@@ -1,9 +1,10 @@import type { CSSProperties, ElementType, ReactNode } from "react";-import { useLayoutEffect, useRef } from "react";+import { createContext, useContext, useLayoutEffect, useRef } from "react";import type {CursorProps,MoveHandler,NodeApi,+ NodeRendererProps,TreeApi,} from "react-arborist";import { Tree as ArboristTree } from "react-arborist";@@ -54,6 +55,22 @@ export interface TreeProps<T> {readonly className?: string;}+type RenderNode = TreeProps<unknown>["renderNode"];++const RenderNodeContext = createContext<RenderNode | null>(null);++// react-arborist uses its `children` prop as the row component type, so it+// must keep one identity for the Tree's lifetime: a new function per render+// remounts every row. The per-render `renderNode` reaches rows via context.+function TreeRow({+ node,+ style,+ dragHandle,+}: NodeRendererProps<TreeDataNode<unknown>>) {+ const renderNode = useContext(RenderNodeContext);+ return renderNode?.({ node, style, dragHandle }) ?? null;+}+export function Tree<T>({data,renderNode,@@ -193,31 +210,31 @@ export function Tree<T>({console.error("[Tree] failed to render tree data:", error);}}>- <ArboristTree<TreeDataNode<T>>- ref={treeRef}- data={data as TreeDataNode<T>[]}- idAccessor="id"- childrenAccessor="children"- selection={selectedIds?.[0]}- onSelect={handleSelect}- onToggle={handleArboristToggle}- onMove={onMove}- searchTerm={searchTerm}- searchMatch={resolvedSearchMatch}- openByDefault={false}- disableDrag={disableDrag}- disableDrop={disableDrop}- disableEdit- height={height}- rowHeight={rowHeight}- indent={indent}- width="100%"- renderCursor={renderCursor}- >- {({ node, style, dragHandle }) =>- renderNode({ node, style, dragHandle })- }- </ArboristTree>+ <RenderNodeContext.Provider value={renderNode as RenderNode}>+ <ArboristTree<TreeDataNode<T>>+ ref={treeRef}+ data={data as TreeDataNode<T>[]}+ idAccessor="id"+ childrenAccessor="children"+ selection={selectedIds?.[0]}+ onSelect={handleSelect}+ onToggle={handleArboristToggle}+ onMove={onMove}+ searchTerm={searchTerm}+ searchMatch={resolvedSearchMatch}+ openByDefault={false}+ disableDrag={disableDrag}+ disableDrop={disableDrop}+ disableEdit+ height={height}+ rowHeight={rowHeight}+ indent={indent}+ width="100%"+ renderCursor={renderCursor}+ >+ {TreeRow as ElementType<NodeRendererProps<TreeDataNode<T>>>}+ </ArboristTree>+ </RenderNodeContext.Provider></ErrorBoundary></div>);diff --git a/frontend/src/modules/sql-editor/components/SchemaPane/HoverPanel/HoverPanel.tsx b/frontend/src/modules/sql-editor/components/SchemaPane/HoverPanel/HoverPanel.tsxindex f959e899d3..e64c6ced6a 100644--- a/frontend/src/modules/sql-editor/components/SchemaPane/HoverPanel/HoverPanel.tsx+++ b/frontend/src/modules/sql-editor/components/SchemaPane/HoverPanel/HoverPanel.tsx@@ -137,6 +137,7 @@ export function HoverPanel({const panel = (<divref={popoverRef}+ data-testid="schema-hover-panel"className={cn("fixed border border-block-border rounded-sm bg-background p-2 shadow-sm transition-[top] text-sm",LAYER_SURFACE_CLASS,diff --git a/frontend/src/modules/sql-editor/components/SchemaPane/SchemaPane.tsx b/frontend/src/modules/sql-editor/components/SchemaPane/SchemaPane.tsxindex 575226f09d..fa2754b947 100644--- a/frontend/src/modules/sql-editor/components/SchemaPane/SchemaPane.tsx+++ b/frontend/src/modules/sql-editor/components/SchemaPane/SchemaPane.tsx@@ -38,7 +38,11 @@ import { useAvailableActions } from "./availableActions";import { useClickEvents } from "./click";import { FlatTableList } from "./FlatTableList";import { HoverPanel } from "./HoverPanel/HoverPanel";-import { HoverStateProvider, useHoverState } from "./hover-state";+import {+ type HoverActions,+ HoverStateProvider,+ useHoverActions,+} from "./hover-state";import {SchemaContextMenu,type SchemaContextMenuHandle,@@ -75,7 +79,7 @@ function SchemaPaneInner() {const getOrFetchDatabaseMetadata = useAppStore((s) => s.getOrFetchDatabaseMetadata);- const hoverState = useHoverState();+ const hover = useHoverActions();const currentTabId = useSQLEditorTabState((s) => s.currentTabId);const currentTab = useSQLEditorTabState((s) =>@@ -412,7 +416,7 @@ function SchemaPaneInner() {// the cursor exits through whitespace where no row handler fires// — or crosses through the floating panel itself which keeps// itself alive on hover — the panel can otherwise linger.- onMouseLeave={() => hoverState.update(undefined, "after")}+ onMouseLeave={() => hover.update(undefined, "after")}><div className="px-1 flex flex-row gap-1"><div className="flex-1 overflow-hidden">@@ -476,9 +480,7 @@ function SchemaPaneInner() {}keyword={searchKeyword}selected={selectedKeys.includes(node.data.data.key)}- hoverUpdate={hoverState.update}- hoverHasState={hoverState.state !== undefined}- hoverSetPosition={hoverState.setPosition}+ hover={hover}databaseName={database.name}onClickNode={handleClick}onContextMenu={(n, e) => contextMenuRef.current?.show(n, e)}@@ -621,9 +623,7 @@ function SchemaTreeRow({hasChildren,keyword,selected,- hoverUpdate,- hoverHasState,- hoverSetPosition,+ hover,databaseName,onClickNode,onContextMenu,@@ -634,9 +634,7 @@ function SchemaTreeRow({hasChildren: boolean;keyword: string;selected: boolean;- hoverUpdate: ReturnType<typeof useHoverState>["update"];- hoverHasState: boolean;- hoverSetPosition: ReturnType<typeof useHoverState>["setPosition"];+ hover: HoverActions;databaseName: string;onClickNode: (node: SchemaTreeNode) => void;onContextMenu: (node: SchemaTreeNode, e: React.MouseEvent) => void;@@ -678,8 +676,8 @@ function SchemaTreeRow({if ("column" in target) state.column = target.column as string;if ("partition" in target) state.partition = target.partition as string;- const delay = hoverHasState ? 150 : undefined;- hoverUpdate(state, "before", delay);+ const delay = hover.isActive() ? 150 : undefined;+ hover.update(state, "before", delay);// Compute position from the row's bounding rect.const wrapper = findAncestor(@@ -687,15 +685,15 @@ function SchemaTreeRow({".bb-schema-tree-row");if (!wrapper) {- hoverUpdate(undefined, "after", 150);+ hover.update(undefined, "after", 150);return;}const rect = wrapper.getBoundingClientRect();- hoverSetPosition({ x: e.clientX, y: rect.bottom });+ hover.setPosition({ x: e.clientX, y: rect.bottom });};const handleMouseLeave = () => {- hoverUpdate(undefined, "after");+ hover.update(undefined, "after");};return (diff --git a/frontend/src/modules/sql-editor/components/SchemaPane/hover-state.test.tsx b/frontend/src/modules/sql-editor/components/SchemaPane/hover-state.test.tsxindex 014c2b7e57..021aacf3a3 100644--- a/frontend/src/modules/sql-editor/components/SchemaPane/hover-state.test.tsx+++ b/frontend/src/modules/sql-editor/components/SchemaPane/hover-state.test.tsx@@ -2,8 +2,10 @@ import { act } from "react";import { createRoot, type Root } from "react-dom/client";import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";import {+ type HoverActions,type HoverStateContextValue,HoverStateProvider,+ useHoverActions,useHoverState,} from "./hover-state";@@ -20,6 +22,15 @@ function Probe({return null;}+let actionRenders: number;+let actions: HoverActions | null;++function ActionsProbe() {+ actionRenders++;+ actions = useHoverActions();+ return null;+}+let container: HTMLDivElement;let root: Root;let handle: { current: HoverStateContextValue | null };@@ -29,10 +40,13 @@ function mount() {document.body.appendChild(container);root = createRoot(container);handle = { current: null };+ actionRenders = 0;+ actions = null;act(() => {root.render(<HoverStateProvider><Probe handleRef={handle} />+ <ActionsProbe /></HoverStateProvider>);});@@ -77,4 +91,26 @@ describe("HoverStateProvider", () => {expect(handle.current!.state).toBeUndefined();});++ test("position and state changes do not re-render action-only consumers", () => {+ expect(actionRenders).toBe(1);+ expect(actions!.isActive()).toBe(false);++ act(() => {+ actions!.setPosition({ x: 10, y: 20 });+ actions!.update(+ { database: "instances/i/databases/db", table: "users" },+ "before",+ 0+ );+ });++ expect(handle.current!.position).toEqual({ x: 10, y: 20 });+ expect(handle.current!.state).toEqual({+ database: "instances/i/databases/db",+ table: "users",+ });+ expect(actions!.isActive()).toBe(true);+ expect(actionRenders).toBe(1);+ });});diff --git a/frontend/src/modules/sql-editor/components/SchemaPane/hover-state.tsx b/frontend/src/modules/sql-editor/components/SchemaPane/hover-state.tsxindex a89fde12f1..db172ff607 100644--- a/frontend/src/modules/sql-editor/components/SchemaPane/hover-state.tsx+++ b/frontend/src/modules/sql-editor/components/SchemaPane/hover-state.tsx@@ -4,7 +4,9 @@ import {useCallback,useContext,useEffect,+ useLayoutEffect,useMemo,+ useRef,useState,} from "react";import {@@ -40,7 +42,20 @@ export type HoverStateContextValue = {const DELAY_BEFORE = 1000;const DELAY_AFTER = 100;+/**+ * The stable half of the hover context: identities never change, so tree+ * rows and the pane can call these without re-rendering on every hover.+ */+export type HoverActions = {+ setPosition: (position: Position) => void;+ update: DelayedValueUpdate<HoverState | undefined>;+ cancel: () => void;+ /** Whether a hover state is committed, read at call time. */+ isActive: () => boolean;+};+const HoverStateContext = createContext<HoverStateContextValue | null>(null);+const HoverActionsContext = createContext<HoverActions | null>(null);/*** Mount under SchemaPane to provide hover-state to descendant `HoverPanel`@@ -73,18 +88,31 @@ export function HoverStateProvider({ children }: { children: ReactNode }) {};}, [update]);+ const stateRef = useRef(state);+ useLayoutEffect(() => {+ stateRef.current = state;+ }, [state]);+ const isActive = useCallback(() => stateRef.current !== undefined, []);++ const actions = useMemo<HoverActions>(+ () => ({ setPosition, update, cancel, isActive }),+ [setPosition, update, cancel, isActive]+ );const value = useMemo<HoverStateContextValue>(() => ({ state, position, setPosition, update, cancel }),[state, position, setPosition, update, cancel]);return (- <HoverStateContext.Provider value={value}>- {children}- </HoverStateContext.Provider>+ <HoverActionsContext.Provider value={actions}>+ <HoverStateContext.Provider value={value}>+ {children}+ </HoverStateContext.Provider>+ </HoverActionsContext.Provider>);}+/** Subscribes to the hover state and pointer position; for the panel only. */export function useHoverState(): HoverStateContextValue {const value = useContext(HoverStateContext);if (!value) {@@ -92,3 +120,11 @@ export function useHoverState(): HoverStateContextValue {}return value;}++export function useHoverActions(): HoverActions {+ const value = useContext(HoverActionsContext);+ if (!value) {+ throw new Error("useHoverActions must be used inside <HoverStateProvider>");+ }+ return value;+}diff --git a/frontend/tests/e2e/sql-editor/sql-editor-schema.spec.ts b/frontend/tests/e2e/sql-editor/sql-editor-schema.spec.tsindex 1641ead43e..f2dcb36e49 100644--- a/frontend/tests/e2e/sql-editor/sql-editor-schema.spec.ts+++ b/frontend/tests/e2e/sql-editor/sql-editor-schema.spec.ts@@ -9,6 +9,7 @@import { test, expect, type BrowserContext, type Page } from "@playwright/test";import { loadTestEnv, type TestEnv } from "../framework/env";import type { BytebaseApiClient } from "../framework/api-client";+import { getInstancePgPort, execSql } from "../framework/psql";import { SqlEditorPage } from "./sql-editor.page";let env: TestEnv & { api: BytebaseApiClient };@@ -357,6 +358,63 @@ test.describe("Right-click on a table opens its detail in a new tab", () => {});});+test.describe("Resting the pointer on a table row shows its hover panel", () => {+ // The hover panel opens after a 1s delay. Each row remount under a resting+ // pointer re-fires mouseenter and restarts that delay, so a tree that+ // remounts rows on hover never shows the panel (BYT-10343).+ const TEST_SCHEMA = "e2e_schema_hover";+ const TEST_TABLE = "hover_probe";++ test.beforeAll(async () => {+ const port = await getInstancePgPort(env);+ execSql(env.databaseId, port, `DROP SCHEMA IF EXISTS ${TEST_SCHEMA} CASCADE`);+ execSql(env.databaseId, port, `CREATE SCHEMA ${TEST_SCHEMA}`);+ execSql(+ env.databaseId,+ port,+ `CREATE TABLE ${TEST_SCHEMA}.${TEST_TABLE} (id INT PRIMARY KEY)`,+ );+ await env.api.syncDatabase(env.database);+ });++ test.afterAll(async () => {+ const port = await getInstancePgPort(env);+ execSql(env.databaseId, port, `DROP SCHEMA IF EXISTS ${TEST_SCHEMA} CASCADE`);+ await env.api.syncDatabase(env.database);+ });++ test("the panel appears for a table and stays while the pointer rests", async ({+ page,+ }) => {+ test.setTimeout(120_000);+ const editor = new SqlEditorPage(page, env.baseURL);++ const projectId = env.project.split("/").pop()!;+ await editor.gotoWithDb(projectId, env.instanceId, env.databaseId);+ await editor.gutterSchemaTab.click();++ const search = page.getByPlaceholder("Search").first();+ await expect(search).toBeVisible({ timeout: 10_000 });+ await search.fill(TEST_TABLE);++ const tableRow = page+ .locator('.bb-schema-tree-row[data-node-meta-type="table"]')+ .filter({ hasText: new RegExp(`^${TEST_TABLE}$`) })+ .first();+ await expect(tableRow).toBeVisible({ timeout: 10_000 });+ await tableRow.hover({ position: { x: 40, y: 8 } });++ const panel = page.getByTestId("schema-hover-panel");+ await expect(panel).toBeVisible({ timeout: 5000 });+ await expect(panel).toContainText("Row count estimate");+ await expect(panel).toContainText(TEST_TABLE);++ // Still shown a second later: the panel is not flickering off.+ await page.waitForTimeout(1000);+ await expect(panel).toBeVisible();+ });+});+test.describe("Schema Diagram menuitem opens the diagram canvas", () => {// The "Schema Diagram" menu item on a schema row routes to the// DiagramPanel, which mounts the SchemaDiagram canvas with one