Skip to content

The IDE you know, rebuilt in Rust. IntelliJ IDEA–style keymap, tool windows and search-everywhere in a fast native app: editor, code insight, debugger, Git, terminal, database and HTTP clients for 60+ languages.

feat(database): boolean and enum cell editors with Set NULL / Set DEFAULT (#2415)

Vadim Lazuk329f0b13306a
diff --git a/src/features/database/DataView.tsx b/src/features/database/DataView.tsx
index 9a8ab407c..c54d8c525 100644
--- a/src/features/database/DataView.tsx
+++ b/src/features/database/DataView.tsx
@@ -90,7 +90,7 @@ interface Shaping {
export interface DataViewProps extends Pick<
GridProps,
- "rowState" | "isModified" | "editable" | "onEdit" | "sort" | "onSort" | "rowMenu"
+ "rowState" | "isModified" | "editable" | "onEdit" | "onResetCell" | "driver" | "sort" | "onSort" | "rowMenu"
> {
columns: readonly GridColumn[];
rowCount: number;
@@ -225,7 +225,9 @@ export function DataView(props: DataViewProps) {
rowState={props.rowState && ((r) => props.rowState!(at(r)))}
isModified={props.isModified && ((r, c) => props.isModified!(at(r), c))}
editable={props.editable}
+ onResetCell={props.onResetCell && ((r, c) => props.onResetCell!(at(r), c))}
onEdit={props.onEdit && ((r, c, v) => props.onEdit!(at(r), c, v))}
+ driver={props.driver}
sort={sort}
onSort={onSort}
rowMenu={props.rowMenu && ((rows) => props.rowMenu!(rows.map(at)))}
diff --git a/src/features/database/Database.module.css b/src/features/database/Database.module.css
index 37ba7524d..34638a18a 100644
--- a/src/features/database/Database.module.css
+++ b/src/features/database/Database.module.css
@@ -121,6 +121,11 @@
outline: none;
}
+.cellCheckbox {
+ flex-shrink: 0;
+ margin: 0 6px 0 0;
+}
+
/* ---- Tool windows ------------------------------------------------------------ */
.view {
height: 100%;
diff --git a/src/features/database/Grid.test.tsx b/src/features/database/Grid.test.tsx
index fdf5002f0..9d76c41af 100644
--- a/src/features/database/Grid.test.tsx
+++ b/src/features/database/Grid.test.tsx
@@ -1,14 +1,28 @@
import { installKeyboardDispatcher, useKeymap } from "@/platform/keymap";
import { registerActions } from "@/platform/actions";
import { act, fireEvent, render, screen } from "@testing-library/react";
-import { afterEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { useState } from "react";
+import { ContextMenuHost } from "@/ui";
import { within } from "@testing-library/react";
import { EditorView } from "@codemirror/view";
import { DataView } from "./DataView";
import { Grid } from "./Grid";
import { CELL_PREVIEW_LIMIT, cellPreview } from "./cellPreview";
import { exportData } from "./export";
+import { installCellActions } from "./cellActions";
+
+let disposeCellActions: () => void;
+beforeEach(() => {
+ useKeymap.setState({ preset: "intellij-macos", overrides: {} });
+ const disposeActions = installCellActions();
+ const disposeKeys = installKeyboardDispatcher();
+ disposeCellActions = () => {
+ disposeKeys();
+ disposeActions();
+ };
+});
+afterEach(() => disposeCellActions());
vi.mock("@tanstack/react-virtual", () => ({
useVirtualizer: ({ count }: { count: number }) => ({
@@ -508,3 +522,358 @@ describe("result grid search", () => {
expect(screen.getAllByRole("row").length - 1).toBe(4);
});
});
+
+describe("boolean cells (issue #2331, phase 1)", () => {
+ const values = [null, "t", "f"];
+
+ it("shows a checkbox on editable boolean cells and toggles it, writing the driver's literals", () => {
+ const onEdit = vi.fn();
+ render(
+ <Grid
+ columns={[{ name: "ok", type: "boolean" }]}
+ rowCount={3}
+ value={(r) => values[r] ?? null}
+ editable
+ onEdit={onEdit}
+ driver="postgres"
+ />,
+ );
+ const boxes = screen.getAllByRole("checkbox") as HTMLInputElement[];
+ expect(boxes.map((b) => b.checked)).toEqual([false, true, false]);
+ expect(boxes[0]!.indeterminate).toBe(true); // NULL
+ fireEvent.click(boxes[2]!);
+ expect(onEdit).toHaveBeenCalledWith(2, 0, "t");
+ expect(onEdit).toHaveBeenCalledTimes(1); // the click toggles only, it doesn't open an editor
+ });
+
+ it("keeps read-only and deleted boolean cells as text without a checkbox", () => {
+ render(<Grid columns={[{ name: "ok", type: "boolean" }]} rowCount={1} value={() => "t"} />);
+ expect(screen.queryByRole("checkbox")).toBeNull();
+ expect(screen.getByRole("gridcell").textContent).toBe("t");
+ const onEdit = vi.fn();
+ render(
+ <Grid
+ columns={[{ name: "ok", type: "boolean" }]}
+ rowCount={2}
+ value={() => "f"}
+ editable
+ onEdit={onEdit}
+ rowState={(r) => (r === 0 ? "deleted" : null)}
+ />,
+ );
+ expect(screen.getAllByRole("checkbox").length).toBe(1);
+ });
+
+ it("toggles the lead boolean cell with Space", () => {
+ const onEdit = vi.fn();
+ render(
+ <Grid
+ columns={[{ name: "ok", type: "boolean" }]}
+ rowCount={3}
+ value={(r) => values[r] ?? null}
+ editable
+ onEdit={onEdit}
+ driver="postgres"
+ />,
+ );
+ // NULL flips to true, false flips back to true.
+ fireEvent.mouseDown(screen.getAllByRole("gridcell")[0]!, { button: 0 });
+ fireEvent.keyDown(screen.getByRole("grid"), { key: " ", code: "Space" });
+ expect(onEdit).toHaveBeenCalledWith(0, 0, "t");
+ fireEvent.mouseDown(screen.getAllByRole("gridcell")[2]!, { button: 0 });
+ fireEvent.keyDown(screen.getByRole("grid"), { key: " ", code: "Space" });
+ expect(onEdit).toHaveBeenCalledWith(2, 0, "t");
+ expect(onEdit).toHaveBeenCalledTimes(2);
+ });
+
+ it("edits a boolean cell in a true / false / NULL drop-down", () => {
+ const onEdit = vi.fn();
+ render(
+ <Grid
+ columns={[{ name: "ok", type: "boolean" }]}
+ rowCount={1}
+ value={() => "f"}
+ editable
+ onEdit={onEdit}
+ driver="postgres"
+ />,
+ );
+ fireEvent.doubleClick(screen.getByRole("gridcell"));
+ const select = screen.getByRole("listbox", { name: "Edit ok" });
+ expect(
+ within(select)
+ .getAllByRole("option")
+ .map((o) => o.textContent),
+ ).toEqual(["true", "false", "NULL"]);
+ fireEvent.keyDown(select, { key: "Escape" });
+ expect(onEdit).not.toHaveBeenCalled();
+ expect(screen.queryByRole("listbox")).toBeNull();
+ fireEvent.doubleClick(screen.getByRole("gridcell"));
+ fireEvent.click(screen.getByRole("option", { name: "NULL" }));
+ expect(onEdit).toHaveBeenCalledWith(0, 0, null);
+ expect(screen.queryByRole("listbox")).toBeNull();
+ });
+
+ it("omits the NULL option for a NOT NULL boolean column", () => {
+ render(
+ <Grid
+ columns={[{ name: "ok", type: "tinyint(1)", nullable: false }]}
+ rowCount={1}
+ value={() => "0"}
+ editable
+ onEdit={vi.fn()}
+ driver="mysql"
+ />,
+ );
+ fireEvent.doubleClick(screen.getByRole("gridcell"));
+ const select = screen.getByRole("listbox", { name: "Edit ok" });
+ expect(
+ within(select)
+ .getAllByRole("option")
+ .map((o) => o.textContent),
+ ).toEqual(["true", "false"]);
+ });
+});
+
+describe("enum cells (issue #2331, phase 1)", () => {
+ it("offers the type's values in a drop-down and commits the pick", () => {
+ const onEdit = vi.fn();
+ render(
+ <Grid
+ columns={[{ name: "mood", type: "enum('sad','ok','happy')" }]}
+ rowCount={1}
+ value={() => "sad"}
+ editable
+ onEdit={onEdit}
+ />,
+ );
+ fireEvent.doubleClick(screen.getByRole("gridcell"));
+ const select = screen.getByRole("listbox", { name: "Edit mood" });
+ expect(
+ within(select)
+ .getAllByRole("option")
+ .map((o) => o.textContent),
+ ).toEqual(["sad", "ok", "happy", "NULL"]);
+ expect(screen.getByRole("option", { name: "sad" }).getAttribute("aria-selected")).toBe("true");
+ fireEvent.click(screen.getByRole("option", { name: "happy" }));
+ expect(onEdit).toHaveBeenCalledWith(0, 0, "happy");
+ expect(screen.queryByRole("listbox")).toBeNull();
+ });
+
+ it("keeps a value the drop-down doesn't know selectable and prefers explicit enumValues", () => {
+ const onEdit = vi.fn();
+ render(
+ <Grid
+ columns={[{ name: "mood", type: "mood", enumValues: ["calm", "angry"] }]}
+ rowCount={1}
+ value={() => "moody"}
+ editable
+ onEdit={onEdit}
+ />,
+ );
+ fireEvent.doubleClick(screen.getByRole("gridcell"));
+ const select = screen.getByRole("listbox", { name: "Edit mood" });
+ expect(
+ within(select)
+ .getAllByRole("option")
+ .map((o) => o.textContent),
+ ).toEqual(["moody", "calm", "angry", "NULL"]);
+ expect(screen.getByRole("option", { name: "moody" }).getAttribute("aria-selected")).toBe("true");
+ fireEvent.keyDown(select, { key: "Escape" });
+ expect(onEdit).not.toHaveBeenCalled();
+ });
+
+ it("falls back to the text editor for a value-less type", () => {
+ render(
+ <Grid columns={[{ name: "mood", type: "mood" }]} rowCount={1} value={() => "ok"} editable onEdit={vi.fn()} />,
+ );
+ fireEvent.doubleClick(screen.getByRole("gridcell"));
+ expect(screen.getByRole("textbox").tagName).toBe("INPUT");
+ });
+});
+
+describe("Set NULL / Set DEFAULT (issue #2331, phase 1)", () => {
+ const columns = [
+ { name: "a", type: "text", default: "'x'::text" },
+ { name: "b", type: "int", nullable: false },
+ { name: "c", type: "text", default: "now()" },
+ ];
+
+ it("sets NULL on the selection from the context menu and ⌘⌫, skipping NOT NULL columns", async () => {
+ const onEdit = vi.fn();
+ render(
+ <>
+ <Grid columns={columns} rowCount={1} value={() => "old"} editable onEdit={onEdit} />
+ <ContextMenuHost />
+ </>,
+ );
+ const cells = screen.getAllByRole("gridcell");
+ fireEvent.mouseDown(cells[0]!, { button: 0 });
+ fireEvent.keyDown(screen.getByRole("grid"), { key: "Backspace", metaKey: true });
+ expect(onEdit).toHaveBeenCalledTimes(1); // only column a; b is NOT NULL
+ expect(onEdit).toHaveBeenCalledWith(0, 0, null);
+
+ fireEvent.mouseDown(cells[1]!, { button: 0 }); // column b, NOT NULL
+ fireEvent.contextMenu(screen.getByRole("grid"), { clientX: 5, clientY: 5 });
+ const entry = screen.getByRole("menuitem", { name: /Set NULL/ });
+ expect(entry.getAttribute("aria-disabled")).toBe("true");
+ await act(async () => void fireEvent.click(entry));
+ expect(onEdit).toHaveBeenCalledTimes(1); // the disabled item changes nothing
+ });
+
+ it("sets DEFAULT from the context menu and ⇧⌘⌫: literals, added rows, never expressions", async () => {
+ const onEdit = vi.fn();
+ const onResetCell = vi.fn();
+ render(
+ <>
+ <Grid
+ columns={columns}
+ rowCount={2}
+ value={() => "old"}
+ editable
+ onEdit={onEdit}
+ rowState={(r) => (r === 1 ? "inserted" : null)}
+ onResetCell={onResetCell}
+ />
+ <ContextMenuHost />
+ </>,
+ );
+ const cells = screen.getAllByRole("gridcell");
+ // Row 1 is an added row: its cells drop their value so the DB default applies.
+ fireEvent.mouseDown(cells[4]!, { button: 0 }); // row 1, column b (no default of its own)
+ fireEvent.keyDown(screen.getByRole("grid"), { key: "Backspace", metaKey: true, shiftKey: true });
+ expect(onResetCell).toHaveBeenCalledWith(1, 1);
+ expect(onEdit).not.toHaveBeenCalled();
+
+ // Row 0: column a's default is a literal; column c's is an expression and stays.
+ fireEvent.mouseDown(cells[0]!, { button: 0 });
+ fireEvent.contextMenu(screen.getByRole("grid"), { clientX: 5, clientY: 5 });
+ await act(async () => void fireEvent.click(screen.getByRole("menuitem", { name: /Set DEFAULT/ })));
+ expect(onEdit).toHaveBeenCalledWith(0, 0, "x");
+ expect(onEdit).toHaveBeenCalledTimes(1);
+ });
+
+ it("disables Set DEFAULT when no selected column has a usable default", async () => {
+ const onEdit = vi.fn();
+ render(
+ <>
+ <Grid columns={[columns[2]!]} rowCount={1} value={() => "old"} editable onEdit={onEdit} />
+ <ContextMenuHost />
+ </>,
+ );
+ fireEvent.mouseDown(screen.getByRole("gridcell"), { button: 0 });
+ fireEvent.contextMenu(screen.getByRole("grid"), { clientX: 5, clientY: 5 });
+ const entry = screen.getByRole("menuitem", { name: /Set DEFAULT/ });
+ expect(entry.getAttribute("aria-disabled")).toBe("true");
+ await act(async () => void fireEvent.click(entry));
+ expect(onEdit).not.toHaveBeenCalled();
+ });
+});
+
+describe("cell action routing", () => {
+ it.each(["intellij-macos", "vscode-macos", "intellij-windows"] as const)(
+ "uses %s bindings and leaves text editing alone",
+ (preset) => {
+ useKeymap.setState({ preset, overrides: {} });
+ const onEdit = vi.fn();
+ render(
+ <Grid
+ columns={[{ name: "text", type: "text", default: "'reset'" }]}
+ rowCount={1}
+ value={() => "words"}
+ editable
+ onEdit={onEdit}
+ />,
+ );
+ const cell = screen.getByRole("gridcell");
+ fireEvent.mouseDown(cell, { button: 0 });
+ const modifiers = preset === "intellij-windows" ? { ctrlKey: true } : { metaKey: true };
+ fireEvent.keyDown(screen.getByRole("grid"), { key: "Backspace", ...modifiers });
+ expect(onEdit).toHaveBeenLastCalledWith(0, 0, null);
+ fireEvent.keyDown(screen.getByRole("grid"), { key: "Backspace", shiftKey: true, ...modifiers });
+ expect(onEdit).toHaveBeenLastCalledWith(0, 0, "reset");
+ onEdit.mockClear();
+ fireEvent.doubleClick(cell);
+ const input = screen.getByRole("textbox");
+ expect(fireEvent.keyDown(input, { key: "Backspace", ...modifiers })).toBe(true);
+ expect(fireEvent.keyDown(input, { key: " ", code: "Space" })).toBe(true);
+ expect(onEdit).not.toHaveBeenCalled();
+ },
+ );
+
+ it("disables DEFAULT for a mixed literal/expression range without partially applying it", () => {
+ const onEdit = vi.fn();
+ render(
+ <>
+ <Grid
+ columns={[
+ { name: "a", type: "text", default: "'x'" },
+ { name: "b", type: "text", default: "now()" },
+ ]}
+ rowCount={1}
+ value={() => "old"}
+ editable
+ onEdit={onEdit}
+ />
+ <ContextMenuHost />
+ </>,
+ );
+ const cells = screen.getAllByRole("gridcell");
+ fireEvent.mouseDown(cells[0]!, { button: 0 });
+ fireEvent.mouseEnter(cells[1]!);
+ fireEvent.mouseUp(window);
+ fireEvent.keyDown(screen.getByRole("grid"), { key: "Backspace", metaKey: true, shiftKey: true });
+ expect(onEdit).not.toHaveBeenCalled();
+ fireEvent.contextMenu(screen.getByRole("grid"));
+ expect(screen.getByRole("menuitem", { name: /Set DEFAULT/ })).toHaveAttribute("aria-disabled", "true");
+ });
+
+ it("refreshes boolean metadata when columns arrive with unchanged names", () => {
+ const onEdit = vi.fn();
+ const props = { rowCount: 1, value: () => "0", editable: true, onEdit, driver: "sqlite" as const };
+ const { rerender } = render(<Grid {...props} columns={[{ name: "enabled", type: "unknown" }]} />);
+ expect(screen.queryByRole("checkbox")).toBeNull();
+ rerender(<Grid {...props} columns={[{ name: "enabled", type: "boolean" }]} />);
+ expect(screen.getByRole("checkbox")).not.toBeChecked();
+ fireEvent.click(screen.getByRole("checkbox"));
+ expect(onEdit).toHaveBeenCalledWith(0, 0, "1");
+ });
+});
+
+it.each([
+ ["postgres", "boolean", "t", "f"],
+ ["sqlite", "boolean", "1", "0"],
+ ["mysql", "tinyint(1)", "1", "0"],
+ ["sqlServer", "bit", "true", "false"],
+] as const)("toggles and resets %s booleans using its rendered literals", (driver, type, t, f) => {
+ const onEdit = vi.fn();
+ render(
+ <Grid
+ columns={[{ name: "enabled", type, default: "((1))" }]}
+ rowCount={1}
+ value={() => f}
+ editable
+ onEdit={onEdit}
+ driver={driver}
+ />,
+ );
+ fireEvent.mouseDown(screen.getByRole("gridcell"), { button: 0 });
+ fireEvent.keyDown(screen.getByRole("grid"), { key: " ", code: "Space" });
+ expect(onEdit).toHaveBeenLastCalledWith(0, 0, t);
+ fireEvent.keyDown(screen.getByRole("grid"), { key: "Backspace", metaKey: true, shiftKey: true });
+ expect(onEdit).toHaveBeenLastCalledWith(0, 0, t);
+});
+
+it.each(["Escape", "Enter"])("%s closes the inline text editor without a second blur commit", (key) => {
+ const onEdit = vi.fn();
+ render(
+ <Grid columns={[{ name: "state", type: "text" }]} rowCount={1} value={() => "old"} editable onEdit={onEdit} />,
+ );
+ fireEvent.doubleClick(screen.getByRole("gridcell"));
+ const input = screen.getByRole("textbox");
+ fireEvent.change(input, { target: { value: "changed" } });
+ fireEvent.keyDown(input, { key });
+ expect(screen.queryByRole("textbox")).toBeNull();
+ if (key === "Escape") expect(onEdit).not.toHaveBeenCalled();
+ else expect(onEdit).toHaveBeenCalledExactlyOnceWith(0, 0, "changed");
+});
diff --git a/src/features/database/Grid.tsx b/src/features/database/Grid.tsx
index c46b7b68a..479006099 100644
--- a/src/features/database/Grid.tsx
+++ b/src/features/database/Grid.tsx
@@ -1,25 +1,51 @@
/**
* Result / table data grid: virtualised rows, resizable columns, rectangular
* cell selection (click, ⇧-click, arrows, ⌘A), copy as TSV / CSV / One-Row,
- * `<null>` rendering, sortable headers and in-place editing (table editor).
+ * `<null>` rendering, sortable headers and type-aware in-place editing
+ * (booleans toggle, enums pick from their values, Set NULL / Set DEFAULT).
*/
import { writeClipboardText } from "@/platform/clipboard";
-import { useEffect, useMemo, useRef, useState, type ClipboardEvent, type KeyboardEvent, type MouseEvent } from "react";
+import {
+ useEffect,
+ useLayoutEffect,
+ useMemo,
+ useRef,
+ useState,
+ type ClipboardEvent,
+ type KeyboardEvent,
+ type MouseEvent,
+} from "react";
import { useVirtualizer } from "@tanstack/react-virtual";
import clsx from "clsx";
-import { Dialog, Icon, showContextMenu, type MenuItem } from "@/ui";
+import { Checkbox, Dialog, Icon, Popup, SelectListbox, showContextMenu, type MenuItem } from "@/ui";
import { parseDelimited, toCsv, toOneRow, toTsv, type Cell } from "./model";
import { initialJsonText, isJsonColumn, isJsonValue } from "./jsonValue";
import { JsonValueWindow } from "./JsonValueEditor";
import styles from "./Database.module.css";
import { tx } from "@/platform/i18n";
import { CELL_PREVIEW_LIMIT, cellPreview, hasLineBreak } from "./cellPreview";
+import {
+ booleanLiterals,
+ defaultLiteralOf,
+ enumValuesOfType,
+ isBooleanType,
+ NULL_INPUT,
+ type BooleanLiterals,
+} from "./cellEditors";
+import { registerCellGrid, type CellActions } from "./cellActions";
+import type { DbDriver } from "@/platform/ipc";
export interface GridColumn {
name: string;
type: string;
primaryKey?: boolean;
foreignKey?: boolean;
+ /** Whether the column accepts SQL NULL (`undefined`: unknown — the editor assumes it does). */
+ nullable?: boolean;
+ /** The column's introspected default expression (Set DEFAULT); `null` when it has none. */
+ default?: string | null;
+ /** The column's allowed values (a caller that knows them; else parsed from the type string). */
+ enumValues?: readonly string[];
}
const NUMERIC_TYPE = /int|num|dec|real|float|double|money|serial|^bit$/i;
@@ -46,6 +72,10 @@ export interface GridProps {
isModified?: (row: number, col: number) => boolean;
editable?: boolean;
onEdit?: (row: number, col: number, value: Cell) => void;
+ /** The data source's driver: which literals boolean editors write (`t`/`f`, `1`/`0`…). */
+ driver?: DbDriver;
+ /** Omit an inserted cell from the INSERT, so its database default applies. */
+ onResetCell?: (row: number, col: number) => void;
sort?: ReadonlyArray<{ column: string; descending: boolean }>;
onSort?: (column: string, add: boolean) => void;
/** Extra context menu items for the selected rows. */
@@ -154,14 +184,17 @@ export function Grid(props: GridProps) {
json: boolean;
dialog: boolean;
} | null>(null);
- /** The inline editor is being swapped for the multi-line one: its blur must not commit. */
- const maximizing = useRef(false);
+ /** The inline editor is being replaced or closed: its blur must not commit again. */
+ const skipBlurCommit = useRef(false);
useEffect(() => {
- if (!editing?.dialog) maximizing.current = false;
+ if (!editing?.dialog) skipBlurCommit.current = false;
}, [editing?.dialog]);
const columnKey = columns.map((c) => c.name).join("\u0000");
const [widths, setWidths] = useState<number[]>([]);
const [numeric, setNumeric] = useState<boolean[]>([]);
+ /** Boolean columns edit as a checkbox; enum columns offer their allowed values. */
+ const bools = columns.map((c) => isBooleanType(c.type, props.driver));
+ const enums = columns.map((c) => c.enumValues ?? enumValuesOfType(c.type));
useEffect(() => {
const sampleRows = Math.min(rowCount, 50);
const samples = columns.map((_, ci) => Array.from({ length: sampleRows }, (_, r) => value(r, ci)));
@@ -252,6 +285,7 @@ export function Grid(props: GridProps) {
const commit = () => {
if (!editing) return;
+ skipBlurCommit.current = true;
const prev = value(editing.row, editing.col);
// A textarea turns CRLF into LF; a value that used CRLF throughout keeps it.
const text =
@@ -283,8 +317,95 @@ export function Grid(props: GridProps) {
setEditing({ row, col, text, json, dialog: maximized || text.length > CELL_PREVIEW_LIMIT || hasLineBreak(text) });
};
+ /** The select editor's pick: values are final, so it commits at once (Escape still cancels). */
+ const pickSelect = (v: string) => {
+ if (!editing) return;
+ onEdit?.(editing.row, editing.col, v === NULL_INPUT ? null : v);
+ setEditing(null);
+ scrollRef.current?.focus();
+ };
+
+ const toggleBoolean = (r: number, c: number, lit: BooleanLiterals) => {
+ if (!onEdit || props.rowState?.(r) === "deleted") return;
+ onEdit(r, c, value(r, c) === lit.t ? lit.f : lit.t);
+ };
+
+ /** Set NULL over a range, unless a column is known to reject it. */
+ const nullOk = (n: { left: number; right: number }) =>
+ Array.from({ length: n.right - n.left + 1 }, (_, i) => columns[n.left + i]!).every((c) => c.nullable !== false);
+
+ /** Set DEFAULT over a range: added rows drop the cell's value (the DB default applies); */
+ /** otherwise the column's default is used, when introspected as a plain literal. */
+ const defaultable = (n: { top: number; bottom: number; left: number; right: number }): boolean => {
+ let usable = false;
+ for (let r = n.top; r <= n.bottom; r++) {
+ if (props.rowState?.(r) === "deleted") continue;
+ usable = true;
+ if (props.rowState?.(r) === "inserted") {
+ if (!props.onResetCell) return false;
+ continue;
+ }
+ for (let c = n.left; c <= n.right; c++) {
+ const d = columns[c]!.default;
+ if (d == null || defaultLiteralOf(d) === null) return false;
+ }
+ }
+ return usable;
+ };
+ const setNulls = (n: { top: number; bottom: number; left: number; right: number }) => {
+ if (!onEdit || !nullOk(n)) return;
+ for (let r = n.top; r <= n.bottom; r++)
+ for (let c = n.left; c <= n.right; c++) if (props.rowState?.(r) !== "deleted") onEdit(r, c, null);
+ };
+ const setDefaults = (n: { top: number; bottom: number; left: number; right: number }) => {
+ if (!onEdit || !defaultable(n)) return;
+ for (let r = n.top; r <= n.bottom; r++) {
+ if (props.rowState?.(r) === "deleted") continue;
+ for (let c = n.left; c <= n.right; c++) {
+ if (props.rowState?.(r) === "inserted") {
+ // An added row's untouched cells are omitted from the INSERT: the DB default applies.
+ props.onResetCell?.(r, c);
+ continue;
+ }
+ const d = columns[c]!.default;
+ const literal = d != null ? defaultLiteralOf(d) : null;
+ if (literal !== null) {
+ const lit = booleanLiterals(props.driver);
+ const text =
+ bools[c] && /^(true|false|t|f|1|0)$/i.test(literal)
+ ? /^(true|t|1)$/i.test(literal)
+ ? lit.t
+ : lit.f
+ : literal;
+ onEdit(r, c, text);
+ }
+ }
+ }
+ };
const jsonWindowChanged = editing?.dialog && editing.json && editing.text !== (value(editing.row, editing.col) ?? "");
+ const cellActions = useRef<CellActions>(null!);
+ useLayoutEffect(() => {
+ const canEdit = () =>
+ !!editable && !!onEdit && !!sel && !editing && selectedRows().some((r) => props.rowState?.(r) !== "deleted");
+ const actions: CellActions = {
+ canToggle: () => canEdit() && !!bools[sel!.c1] && props.rowState?.(sel!.r1) !== "deleted",
+ canSetNull: () => canEdit() && nullOk(norm(sel!)),
+ canSetDefault: () => canEdit() && defaultable(norm(sel!)),
+ toggle: () => {
+ if (actions.canToggle()) toggleBoolean(sel!.r1, sel!.c1, booleanLiterals(props.driver));
+ },
+ setNull: () => {
+ if (actions.canSetNull()) setNulls(norm(sel!));
+ },
+ setDefault: () => {
+ if (actions.canSetDefault()) setDefaults(norm(sel!));
+ },
+ };
+ Object.assign((cellActions.current ??= {} as CellActions), actions);
+ });
+ useEffect(() => registerCellGrid(scrollRef.current!, cellActions.current), []);
+
const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
if (editing) return;
const mod = e.metaKey || e.ctrlKey;
@@ -387,12 +508,8 @@ export function Grid(props: GridProps) {
items.push(
{ kind: "separator" },
{ label: "Edit Cell", disabled: n.top !== n.bottom || n.left !== n.right, run: () => startEdit(n.top, n.left) },
- {
- label: "Set NULL",
- run: () => {
- for (let r = n.top; r <= n.bottom; r++) for (let c = n.left; c <= n.right; c++) onEdit(r, c, null);
- },
- },
+ { kind: "action", action: "db.setCellNull", arg: cellActions.current },
+ { kind: "action", action: "db.setCellDefault", arg: cellActions.current },
);
}
const extra = rowMenu?.(selectedRows()) ?? [];
@@ -423,6 +540,7 @@ export function Grid(props: GridProps) {
className={styles.grid}
tabIndex={0}
role="grid"
+ data-db-cell-grid=""
aria-label={props["aria-label"] ?? "Results"}
aria-rowcount={rowCount}
onKeyDown={onKeyDown}
@@ -540,6 +658,33 @@ export function Grid(props: GridProps) {
</div>
{columns.map((_, c) => {
if (editing && !editing.dialog && editing.row === r && editing.col === c) {
+ const col = columns[c]!;
+ const lit = bools[c] ? booleanLiterals(props.driver) : null;
+ const values = enums[c];
+ const cell = value(editing.row, editing.col);
+ // A cell that is NULL in a NOT NULL column (a pending edit) is anomalous: plain editor.
+ if ((lit || values) && !(cell === null && col.nullable === false)) {
+ const options: Array<{ value: string; label: string }> = [];
+ const known = (v: string) => options.some((o) => o.value === v);
+ if (lit) options.push({ value: lit.t, label: tx("true") }, { value: lit.f, label: tx("false") });
+ else for (const v of values!) if (!known(v)) options.push({ value: v, label: v });
+ // A value the editor doesn't offer stays selectable instead of silently changing on commit.
+ if (cell !== null && !known(cell)) options.unshift({ value: cell, label: cell });
+ if (col.nullable !== false) options.push({ value: NULL_INPUT, label: "NULL" });
+ return (
+ <CellSelect
+ key={c}
+ label={tx`Edit ${col.name}`}
+ value={cell === null ? NULL_INPUT : cell}
+ options={options}
+ onChoose={pickSelect}
+ onClose={() => {
+ setEditing(null);
+ scrollRef.current?.focus();
+ }}
+ />
+ );
+ }
return (
<input
key={c}
@@ -550,19 +695,20 @@ export function Grid(props: GridProps) {
value={editing.text}
onChange={(e) => setEditing({ ...editing, text: e.target.value })}
onBlur={() => {
- if (!maximizing.current) commit();
+ if (!skipBlurCommit.current) commit();
}}
onKeyDown={(e) => {
e.stopPropagation();
if (e.key === "Enter" && e.shiftKey) {
// A line break can't be typed in a single-line field: continue in the multi-line editor.
e.preventDefault();
- maximizing.current = true;
+ skipBlurCommit.current = true;
setEditing({ ...editing, dialog: true });
return;
}
if (e.key === "Enter") commit();
if (e.key === "Escape") {
+ skipBlurCommit.current = true;
setEditing(null);
scrollRef.current?.focus();
}
@@ -571,6 +717,9 @@ export function Grid(props: GridProps) {
);
}
const val = value(r, c);
+ // Boolean cells show a checkbox while the grid is editable (DataGrip); Space toggles too.
+ const lit =
+ editable && onEdit && bools[c] && state !== "deleted" ? booleanLiterals(props.driver) : null;
return (
<div
key={c}
@@ -590,7 +739,33 @@ export function Grid(props: GridProps) {
onDoubleClick={() => startEdit(r, c)}
title={val != null && val.length > 40 ? val.slice(0, 2000) : undefined}
>
- {val === null ? (
+ {lit ? (
+ <>
+ <span
+ onMouseDown={(e) => {
+ e.stopPropagation();
+ setSel({ r0: r, c0: c, r1: r, c1: c });
+ }}
+ onDoubleClick={(e) => e.stopPropagation()}
+ >
+ <Checkbox
+ className={styles.cellCheckbox}
+ aria-label={tx`Toggle ${columns[c]!.name}`}
+ checked={val === lit.t}
+ indeterminate={val === null}
+ onChange={() => {
+ toggleBoolean(r, c, lit);
+ scrollRef.current?.focus();
+ }}
+ />
+ </span>
+ {val === null ? (
+ <span className={styles.null}>&lt;null&gt;</span>
+ ) : (
+ cellText(displayed(val, !!numeric[c]))
+ )}
+ </>
+ ) : val === null ? (
<span className={styles.null}>&lt;null&gt;</span>
) : (
cellText(displayed(val, !!numeric[c]))
@@ -605,3 +780,32 @@ export function Grid(props: GridProps) {
</div>
);
}
+
+function CellSelect({
+ label,
+ value,
+ options,
+ onChoose,
+ onClose,
+}: {
+ label: string;
+ value: string;
+ options: Array<{ value: string; label: string }>;
+ onChoose(value: string): void;
+ onClose(): void;
+}) {
+ const anchor = useRef<HTMLDivElement>(null);
+ return (
+ <div ref={anchor} role="gridcell" className={styles.cellEditor}>
+ {options.find((o) => o.value === value)?.label}
+ <Popup open anchor={anchor} onClose={onClose} matchWidth role="presentation">
+ <SelectListbox
+ value={value}
+ options={options.map((o) => ({ ...o, verbatim: true }))}
+ onChoose={onChoose}
+ aria-label={label}
+ />
+ </Popup>
+ </div>
+ );
+}
diff --git a/src/features/database/ResultsView.tsx b/src/features/database/ResultsView.tsx
index 893c2c666..f88b5d058 100644
--- a/src/features/database/ResultsView.tsx
+++ b/src/features/database/ResultsView.tsx
@@ -248,6 +248,21 @@ function Result({ tab }: { tab: ResultTab }) {
eq,
);
}, [detailsValue, sources, resultNames, eq]);
+ // Nullability and defaults follow the table's details once they load (they gate Set NULL / Set DEFAULT).
+ const gridColumns = useMemo(
+ () =>
+ columns.map((c) => {
+ const d = detailsValue?.columns.find((x) => eq(x.name, c.name));
+ return {
+ ...c,
+ type: d?.dataType ?? c.type,
+ primaryKey: !!pk?.includes(c.name),
+ nullable: d?.nullable,
+ default: d?.default ?? null,
+ };
+ }),
+ [columns, pk, detailsValue, eq],
+ );
const readOnlySource = source?.readOnly ?? false;
const editable =
editability.kind === "editable" &&
@@ -299,6 +314,16 @@ function Result({ tab }: { tab: ResultTab }) {
});
};
+ const onResetCell = (row: number, col: number) => {
+ setEdits((e) => {
+ const inserts = [...e.inserts];
+ const ins = new Map(inserts[row - loaded]);
+ ins.delete(resultNames[col]!);
+ inserts[row - loaded] = ins;
+ return { ...e, inserts };
+ });
+ };
+
const deleteRows = (rows: number[]) =>
setEdits((e) => {
const deletes = new Set(e.deletes);
@@ -463,9 +488,10 @@ function Result({ tab }: { tab: ResultTab }) {
)}
<div className={clsx(styles.fill, styles.gridHost)}>
<DataView
- columns={columns.map((c) => ({ ...c, primaryKey: !!pk?.includes(c.name) }))}
+ columns={gridColumns}
rowCount={rowCount}
fixedRows={loaded}
+ driver={driver}
value={value}
panel={panel}
onPanelChange={setPanel}
@@ -478,6 +504,7 @@ function Result({ tab }: { tab: ResultTab }) {
isModified={(row, col) => !!edits.updates.get(row)?.has(resultNames[col]!)}
editable={editable && !busy}
onEdit={onEdit}
+ onResetCell={onResetCell}
revealColumn={revealColumn}
rowMenu={(rows) =>
editable && !busy
diff --git a/src/features/database/TableEditor.tsx b/src/features/database/TableEditor.tsx
index c3545059a..acda0c11c 100644
--- a/src/features/database/TableEditor.tsx
+++ b/src/features/database/TableEditor.tsx
@@ -99,12 +99,17 @@ export function TableEditor({ input }: { input: EditorInput }) {
const rowCount = loaded + edits.inserts.length;
const gridColumns = useMemo(
() =>
- columns.map((c) => ({
- name: c.name,
- type: c.typeName,
- primaryKey: pk.includes(c.name),
- foreignKey: fkColumns.has(c.name),
- })),
+ columns.map((c) => {
+ const d = page?.details.columns.find((x) => x.name === c.name);
+ return {
+ name: c.name,
+ type: d?.dataType ?? c.typeName,
+ primaryKey: pk.includes(c.name),
+ foreignKey: fkColumns.has(c.name),
+ nullable: d?.nullable,
+ default: d?.default ?? null,
+ };
+ }),
// `pk` / `fkColumns` derive from `page`.
// eslint-disable-next-line react-hooks/exhaustive-deps
[page],
@@ -145,6 +150,16 @@ export function TableEditor({ input }: { input: EditorInput }) {
});
};
+ const onResetCell = (row: number, col: number) => {
+ setEdits((e) => {
+ const inserts = [...e.inserts];
+ const ins = new Map(inserts[row - loaded]);
+ ins.delete(names[col]!);
+ inserts[row - loaded] = ins;
+ return { ...e, inserts };
+ });
+ };
+
const deleteRows = (rows: number[]) =>
setEdits((e) => {
const deletes = new Set(e.deletes);
@@ -374,6 +389,8 @@ export function TableEditor({ input }: { input: EditorInput }) {
isModified={(r, c) => !!edits.updates.get(r)?.has(names[c]!)}
editable={editable}
onEdit={onEdit}
+ onResetCell={onResetCell}
+ driver={source?.driver}
sort={sort}
onSort={onSort}
rowMenu={(rows) =>
diff --git a/src/features/database/cellActions.ts b/src/features/database/cellActions.ts
new file mode 100644
index 000000000..01d6b3cac
--- /dev/null
+++ b/src/features/database/cellActions.ts
@@ -0,0 +1,69 @@
+import { registerActions, type ActionContext } from "@/platform/actions";
+import { setContext } from "@/platform/context";
+
+export interface CellActions {
+ canToggle(): boolean;
+ canSetNull(): boolean;
+ canSetDefault(): boolean;
+ toggle(): void;
+ setNull(): void;
+ setDefault(): void;
+}
+
+const grids = new WeakMap<Element, CellActions>();
+let active: CellActions | null = null;
+
+export function registerCellGrid(root: Element, actions: CellActions): () => void {
+ grids.set(root, actions);
+ return () => {
+ grids.delete(root);
+ if (active === actions) {
+ active = null;
+ setContext("dbCellGridFocus", false);
+ }
+ };
+}
+
+export function installCellActions(): () => void {
+ const onFocus = (event: FocusEvent) => {
+ const target = event.target instanceof Element ? event.target : null;
+ const root = target?.closest("[data-db-cell-grid]");
+ active =
+ root && !target?.closest("input, textarea, select, [contenteditable='true']") ? (grids.get(root) ?? null) : null;
+ setContext("dbCellGridFocus", !!active);
+ };
+ document.addEventListener("focusin", onFocus);
+ const handle = ({ arg }: ActionContext) => (arg as CellActions | undefined) ?? active;
+ const dispose = registerActions([
+ {
+ id: "db.toggleBooleanCell",
+ title: "Toggle Boolean Cell",
+ category: "Database",
+ keyWhen: "dbCellGridFocus",
+ enabled: (c) => handle(c)?.canToggle() ?? false,
+ run: (c) => handle(c)?.toggle(),
+ },
+ {
+ id: "db.setCellNull",
+ title: "Set NULL",
+ category: "Database",
+ keyWhen: "dbCellGridFocus",
+ enabled: (c) => handle(c)?.canSetNull() ?? false,
+ run: (c) => handle(c)?.setNull(),
+ },
+ {
+ id: "db.setCellDefault",
+ title: "Set DEFAULT",
+ category: "Database",
+ keyWhen: "dbCellGridFocus",
+ enabled: (c) => handle(c)?.canSetDefault() ?? false,
+ run: (c) => handle(c)?.setDefault(),
+ },
+ ]);
+ return () => {
+ dispose();
+ document.removeEventListener("focusin", onFocus);
+ active = null;
+ setContext("dbCellGridFocus", false);
+ };
+}
diff --git a/src/features/database/cellEditors.test.ts b/src/features/database/cellEditors.test.ts
new file mode 100644
index 000000000..0470eced1
--- /dev/null
+++ b/src/features/database/cellEditors.test.ts
@@ -0,0 +1,87 @@
+import { describe, expect, it } from "vitest";
+import { booleanLiterals, defaultLiteralOf, enumValuesOfType, isBooleanType, NULL_INPUT } from "./cellEditors";
+
+describe("boolean cell editing", () => {
+ it("detects the column types that edit as a boolean", () => {
+ for (const type of ["boolean", "BOOLEAN", "bool", "tinyint(1)", "TINYINT(1)", "bit", "Bit"])
+ expect(isBooleanType(type), type).toBe(true);
+ for (const type of ["tinyint", "tinyint(4)", "int", "text", "bit varying", ""])
+ expect(isBooleanType(type), type).toBe(false);
+ });
+
+ it("does not treat PostgreSQL and MySQL bit strings as booleans", () => {
+ expect(isBooleanType("bit", "postgres")).toBe(false);
+ expect(isBooleanType("bit", "mysql")).toBe(false);
+ expect(isBooleanType("bit", "sqlServer")).toBe(true);
+ });
+
+ it("writes the literals the driver renders booleans with", () => {
+ expect(booleanLiterals("postgres")).toEqual({ t: "t", f: "f" });
+ expect(booleanLiterals("mysql")).toEqual({ t: "1", f: "0" });
+ expect(booleanLiterals("sqlite")).toEqual({ t: "1", f: "0" });
+ expect(booleanLiterals("sqlServer")).toEqual({ t: "true", f: "false" });
+ expect(booleanLiterals("oracle")).toEqual({ t: "true", f: "false" });
+ expect(booleanLiterals(undefined)).toEqual({ t: "true", f: "false" });
+ });
+
+ it("keeps the select editor's NULL option value off the cell alphabet", () => {
+ expect(NULL_INPUT).not.toBe("");
+ expect(NULL_INPUT.startsWith("\u0000")).toBe(true);
+ });
+});
+
+describe("enum cell editing", () => {
+ it("lists a MySQL ENUM type's values in definition order", () => {
+ expect(enumValuesOfType("enum('a','b','c')")).toEqual(["a", "b", "c"]);
+ expect(enumValuesOfType("ENUM( 'x' , 'y' )")).toEqual(["x", "y"]);
+ expect(enumValuesOfType("enum('it''s','say \"hi\"','a,b')")).toEqual(["it's", 'say "hi"', "a,b"]);
+ expect(enumValuesOfType("enum('')")).toEqual([""]);
+ expect(enumValuesOfType(String.raw`enum('it\'s','a\\b','line\nbreak')`)).toEqual(["it's", "a\\b", "line\nbreak"]);
+ });
+
+ it("rejects types that don't carry a value list", () => {
+ for (const type of [
+ "varchar(10)",
+ "ENUM",
+ "mood",
+ "USER-DEFINED",
+ "enum()",
+ "enum('a',)",
+ "enum(a)",
+ "enum('a'",
+ "enum('a','b",
+ ])
+ expect(enumValuesOfType(type), type).toBeNull();
+ });
+});
+
+describe("Set DEFAULT", () => {
+ it("uses plain string and number defaults as the cell's literal", () => {
+ expect(defaultLiteralOf("'active'")).toBe("active");
+ expect(defaultLiteralOf("'active'::character varying")).toBe("active");
+ expect(defaultLiteralOf("''::text")).toBe("");
+ expect(defaultLiteralOf("'it''s'")).toBe("it's");
+ expect(defaultLiteralOf("42")).toBe("42");
+ expect(defaultLiteralOf("((1))")).toBe("1");
+ expect(defaultLiteralOf("('ready')")).toBe("ready");
+ expect(defaultLiteralOf("-1.5")).toBe("-1.5");
+ expect(defaultLiteralOf("+7")).toBe("+7");
+ expect(defaultLiteralOf("true")).toBe("true");
+ expect(defaultLiteralOf("FALSE")).toBe("false");
+ });
+
+ it("rejects expression defaults the grid's pending edits cannot send", () => {
+ for (const d of [
+ "now()",
+ "nextval('ids'::regclass)",
+ "CURRENT_TIMESTAMP",
+ "b'0'",
+ "'a' || 'b'",
+ "'a'::text || 'b'",
+ "'a'::text; SELECT 1",
+ "",
+ " ",
+ ])
+ expect(defaultLiteralOf(d), d).toBeNull();
+ });
+});
diff --git a/src/features/database/cellEditors.ts b/src/features/database/cellEditors.ts
new file mode 100644
index 000000000..b02e77f09
--- /dev/null
+++ b/src/features/database/cellEditors.ts
@@ -0,0 +1,134 @@
+/**
+ * Type-aware cell editing (issue #2331, phase 1): which editor a column's SQL
+ * type gets and the values it writes. Values come from the column metadata the
+ * database introspection already returns — the type string itself (MySQL's
+ * `ENUM('a','b')`, the table details' column default) — so no new backend
+ * support is needed. Date / time pickers, foreign-key lookups and enum value
+ * lists for types that don't carry them (PostgreSQL) are follow-ups.
+ */
+import type { DbDriver } from "@/platform/ipc";
+
+/** The select editor's option that writes SQL NULL (not a possible cell value). */
+export const NULL_INPUT = "\u0000null";
+
+export interface BooleanLiterals {
+ /** What the driver renders `true` / `false` as (the values the editor writes back). */
+ t: string;
+ f: string;
+}
+
+/**
+ * The column's SQL type edits as a boolean: a real `BOOLEAN`, MySQL / SQLite's
+ * `TINYINT(1)` alias or SQL Server's one-bit `BIT`.
+ */
+export function isBooleanType(type: string, driver?: DbDriver): boolean {
+ if (/^bit$/i.test(type.trim()) && (driver === "postgres" || driver === "mysql")) return false;
+ return /^(boolean|bool|tinyint\(1\)|bit)$/i.test(type.trim());
+}
+
+/** The literals the editor writes, matching what the driver renders (`t`/`f` on PostgreSQL, `1`/`0` on MySQL). */
+export function booleanLiterals(driver: DbDriver | undefined): BooleanLiterals {
+ switch (driver) {
+ case "postgres":
+ return { t: "t", f: "f" };
+ case "mysql":
+ case "sqlite":
+ return { t: "1", f: "0" };
+ default:
+ return { t: "true", f: "false" };
+ }
+}
+
+/**
+ * The allowed values of a MySQL `ENUM('a','b')` type, in definition order;
+ * `null` when the type string doesn't list them (other drivers, or the driver's
+ * own short name like the console results' `ENUM`). `''` is a doubled quote.
+ */
+export function enumValuesOfType(type: string): readonly string[] | null {
+ const m = /^enum\s*\(([\s\S]*)\)$/i.exec(type.trim());
+ if (!m) return null;
+ const body = m[1]!;
+ const values: string[] = [];
+ let at = 0;
+ for (;;) {
+ while (at < body.length && /\s/.test(body[at]!)) at++;
+ if (body[at] !== "'") return null; // every value is a quoted string
+ at++;
+ let value = "";
+ for (;;) {
+ if (at >= body.length) return null; // unterminated string
+ const ch = body[at]!;
+ if (ch === "\\") {
+ const escaped = body[++at];
+ if (escaped === undefined) return null;
+ const escapes: Record<string, string> = { "0": "\0", b: "\b", n: "\n", r: "\r", t: "\t", Z: "\x1a" };
+ value += escapes[escaped] ?? escaped;
+ at++;
+ continue;
+ }
+ if (ch === "'") {
+ if (body[at + 1] === "'") {
+ value += "'";
+ at += 2;
+ continue;
+ }
+ at++;
+ break;
+ }
+ value += ch;
+ at++;
+ }
+ values.push(value);
+ while (at < body.length && /\s/.test(body[at]!)) at++;
+ if (at >= body.length) return values;
+ if (body[at] !== ",") return null;
+ at++;
+ }
+}
+
+/**
+ * The literal a Set DEFAULT action puts in the cell: the column's introspected
+ * default when it is a plain value — a quoted string (with an optional
+ * `::type` cast) or a bare number. `null` for anything else (`now()`,
+ * `nextval('…')`, `CURRENT_TIMESTAMP`): the grid's pending edits send text or
+ * SQL NULL only, so an expression default can't be applied from here.
+ */
+export function defaultLiteralOf(defaultExpr: string): string | null {
+ let s = defaultExpr.trim();
+ while (s.startsWith("(") && s.endsWith(")")) s = s.slice(1, -1).trim();
+ if (/^(true|false)$/i.test(s)) return s.toLowerCase();
+ const quoted = quotedLiteral(s);
+ if (quoted !== null) return quoted;
+ return /^[-+]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/.test(s) ? s : null;
+}
+
+/** The text of one SQL quoted string at the start of `s`, with an optional trailing `::type` cast. */
+function quotedLiteral(s: string): string | null {
+ if (!s.startsWith("'")) return null;
+ let value = "";
+ let at = 1;
+ for (;;) {
+ if (at >= s.length) return null; // unterminated string
+ const ch = s[at]!;
+ if (ch === "'") {
+ if (s[at + 1] === "'") {
+ value += "'";
+ at += 2;
+ continue;
+ }
+ at++;
+ break;
+ }
+ value += ch;
+ at++;
+ }
+ const rest = s.slice(at).trim();
+ if (
+ rest &&
+ !/^::\s*(?:[\w]+|"[^"]+")(?:\s*\.\s*(?:[\w]+|"[^"]+"))*(?:\s+(?:varying|precision|with(?:out)?\s+time\s+zone))?(?:\s*\(\d+(?:\s*,\s*\d+)?\))?(?:\[\])?$/i.test(
+ rest,
+ )
+ )
+ return null;
+ return value;
+}
diff --git a/src/features/database/index.ts b/src/features/database/index.ts
index 65bb28691..86ff35273 100644
--- a/src/features/database/index.ts
+++ b/src/features/database/index.ts
@@ -19,6 +19,7 @@ import {
setFileDecorations,
toolWindowService,
} from "@/workbench/contributions";
+import { installCellActions } from "./cellActions";
import { installValueEditorActions } from "./valueEditorActions";
import { SQL_LANGUAGE } from "./sqlLanguage";
import { TABLE_KIND, tableTitle } from "./tableInput";
@@ -125,6 +126,7 @@ export function activate(): () => void {
watchIdleConnections(),
installTableEditorFocus(),
installValueEditorActions(),
+ installCellActions(),
registerDatabaseTreeActions(),
registerActions([
{
diff --git a/src/features/database/results-view.test.tsx b/src/features/database/results-view.test.tsx
index 82a133fd7..31fbcef11 100644
--- a/src/features/database/results-view.test.tsx
+++ b/src/features/database/results-view.test.tsx
@@ -1,6 +1,8 @@
import { act, fireEvent, render, screen } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { DbDriver, DbQueryResult, DbTableDetails } from "@/platform/ipc";
+import { installKeyboardDispatcher, useKeymap } from "@/platform/keymap";
+import { installCellActions } from "./cellActions";
import { getContext } from "@/platform/context";
import { ResultsView } from "./ResultsView";
import { executeConsole, useDatabase, type ResultTab } from "./store";
@@ -361,3 +363,28 @@ describe("result grid keyboard Submit / Revert (#2332)", () => {
}
});
});
+
+it("omits a reset inserted cell from Submit instead of writing SQL NULL", async () => {
+ show("SELECT * FROM users", [{ name: "id" }, { name: "name" }], [["1", "Ann"]]);
+ useKeymap.setState({ preset: "intellij-macos", overrides: {} });
+ const disposeActions = installCellActions();
+ const disposeKeys = installKeyboardDispatcher();
+ try {
+ await act(async () => {
+ render(<ResultsView />);
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Add Row" }));
+ const cells = screen.getAllByRole("gridcell");
+ fireEvent.mouseDown(cells[2]!, { button: 0 });
+ fireEvent.paste(screen.getByRole("grid"), { clipboardData: { getData: () => "3\tCara" } });
+ fireEvent.mouseDown(cells[3]!, { button: 0 });
+ fireEvent.keyDown(screen.getByRole("grid"), { key: "Backspace", metaKey: true, shiftKey: true });
+ await act(async () => {
+ fireEvent.click(screen.getByRole("button", { name: "Submit" }));
+ });
+ expect(backend.applyEdits.mock.calls[0]?.[3]).toEqual([{ kind: "insert", values: [{ column: "id", value: "3" }] }]);
+ } finally {
+ disposeKeys();
+ disposeActions();
+ }
+});
diff --git a/src/features/database/table-editor.test.tsx b/src/features/database/table-editor.test.tsx
index ad923f695..f37cdbcb5 100644
--- a/src/features/database/table-editor.test.tsx
+++ b/src/features/database/table-editor.test.tsx
@@ -1,6 +1,8 @@
import { act, fireEvent, render, screen } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { DbDriver, DbTablePage } from "@/platform/ipc";
+import { installKeyboardDispatcher, useKeymap } from "@/platform/keymap";
+import { installCellActions } from "./cellActions";
import { getContext } from "@/platform/context";
import { TableEditor } from "./TableEditor";
import { activeTableEditor, installTableEditorFocus } from "./tableEditorFocus";
@@ -151,3 +153,29 @@ describe("table editor capabilities", () => {
}
});
});
+
+it("omits a reset inserted cell from Submit instead of writing SQL NULL", async () => {
+ backend.driver = "postgres";
+ backend.applyEdits.mockResolvedValue({ status: "ok", data: 1 });
+ useKeymap.setState({ preset: "intellij-macos", overrides: {} });
+ const disposeActions = installCellActions();
+ const disposeKeys = installKeyboardDispatcher();
+ try {
+ await act(async () => {
+ render(<TableEditor input={tableInput("source", "public", "users")} />);
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Add Row" }));
+ const cells = screen.getAllByRole("gridcell");
+ fireEvent.mouseDown(cells[2]!, { button: 0 });
+ fireEvent.paste(screen.getByRole("grid"), { clipboardData: { getData: () => "3\tCara" } });
+ fireEvent.mouseDown(cells[3]!, { button: 0 });
+ fireEvent.keyDown(screen.getByRole("grid"), { key: "Backspace", metaKey: true, shiftKey: true });
+ await act(async () => {
+ fireEvent.click(screen.getByRole("button", { name: "Submit" }));
+ });
+ expect(backend.applyEdits.mock.calls[0]?.[3]).toEqual([{ kind: "insert", values: [{ column: "id", value: "3" }] }]);
+ } finally {
+ disposeKeys();
+ disposeActions();
+ }
+});
diff --git a/src/platform/keymaps/intellij-macos.ts b/src/platform/keymaps/intellij-macos.ts
index 5b909aec9..108732311 100644
--- a/src/platform/keymaps/intellij-macos.ts
+++ b/src/platform/keymaps/intellij-macos.ts
@@ -354,6 +354,9 @@ export const intellijMacos: Record<string, string[]> = {
"http.runRequest": ["Meta+Enter"],
"graphql.runQuery": ["Meta+Enter"],
"http.runAll": [],
+ "db.toggleBooleanCell": ["Space"],
+ "db.setCellNull": ["Meta+Backspace"],
+ "db.setCellDefault": ["Meta+Shift+Backspace"],
"db.reformatValue": ["Meta+Alt+L"],
"db.openValueWindow": [],
"db.findInValue": ["Meta+F"],
diff --git a/src/platform/keymaps/intellij-windows.ts b/src/platform/keymaps/intellij-windows.ts
index ee01144a6..a96745b77 100644
--- a/src/platform/keymaps/intellij-windows.ts
+++ b/src/platform/keymaps/intellij-windows.ts
@@ -352,6 +352,9 @@ export const intellijWindows: Record<string, string[]> = {
"http.runRequest": ["Ctrl+Enter"],
"graphql.runQuery": ["Ctrl+Enter"],
"http.runAll": [],
+ "db.toggleBooleanCell": ["Space"],
+ "db.setCellNull": ["Ctrl+Backspace"],
+ "db.setCellDefault": ["Ctrl+Shift+Backspace"],
"db.reformatValue": ["Ctrl+Alt+L"],
"db.openValueWindow": [],
"db.findInValue": ["Ctrl+F"],
diff --git a/src/platform/keymaps/vscode-macos.ts b/src/platform/keymaps/vscode-macos.ts
index cfd6101f1..f349c8be0 100644
--- a/src/platform/keymaps/vscode-macos.ts
+++ b/src/platform/keymaps/vscode-macos.ts
@@ -350,6 +350,9 @@ export const vscodeMacos: Record<string, string[]> = {
"http.runRequest": ["Meta+Enter"],
"graphql.runQuery": ["Meta+Enter"],
"http.runAll": [],
+ "db.toggleBooleanCell": ["Space"],
+ "db.setCellNull": ["Meta+Backspace"],
+ "db.setCellDefault": ["Meta+Shift+Backspace"],
"db.reformatValue": ["Alt+Shift+F"],
"db.openValueWindow": [],
"db.findInValue": ["Meta+F"],
diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json
index 73d619f5d..393370dff 100644
--- a/src/platform/locales/text/en.json
+++ b/src/platform/locales/text/en.json
@@ -798,5 +798,10 @@
"Loading library sources…": "Loading library sources…",
"Sources not found": "Sources not found",
"Cannot load library sources": "Cannot load library sources",
- "Decompiled .class file: sources are not available.": "Decompiled .class file: sources are not available."
+ "Decompiled .class file: sources are not available.": "Decompiled .class file: sources are not available.",
+ "Set DEFAULT": "Set DEFAULT",
+ "Toggle Boolean Cell": "Toggle Boolean Cell",
+ "Toggle {name}": "Toggle {name}",
+ "true": "true",
+ "false": "false"
}
diff --git a/src/platform/locales/text/es.json b/src/platform/locales/text/es.json
index f1e4d62b4..5999bb7f1 100644
--- a/src/platform/locales/text/es.json
+++ b/src/platform/locales/text/es.json
@@ -1994,6 +1994,7 @@
"Services actions": "Acciones de servicios",
"Session finished": "Sesión finalizada",
"Set Active Changelist": "Establecer lista de cambios activa",
+ "Set DEFAULT": "Establecer como predeterminado",
"Set NULL": "Establecer como NULL",
"Set Value…": "Establecer valor…",
"Set active": "Establecer como activa",
diff --git a/src/platform/locales/text/fr.json b/src/platform/locales/text/fr.json
index 10fb3f224..ad97c2eec 100644
--- a/src/platform/locales/text/fr.json
+++ b/src/platform/locales/text/fr.json
@@ -1900,6 +1900,7 @@
"Services actions": "Actions des services",
"Session finished": "Session terminée",
"Set Active Changelist": "Définir comme liste de modifications active",
+ "Set DEFAULT": "Définir comme valeur par défaut",
"Set NULL": "Définir à NULL",
"Set Value…": "Définir la valeur…",
"Set active": "Définir comme active",
diff --git a/src/platform/locales/text/ko.json b/src/platform/locales/text/ko.json
index bd9cdc006..9fb6a2fcd 100644
--- a/src/platform/locales/text/ko.json
+++ b/src/platform/locales/text/ko.json
@@ -2050,6 +2050,7 @@
"Services actions": "서비스 액션",
"Session finished": "세션이 종료되었습니다",
"Set Active Changelist": "변경 목록 활성화",
+ "Set DEFAULT": "기본값 설정",
"Set NULL": "NULL 설정",
"Set Value…": "값 설정…",
"Set active": "활성화",
diff --git a/src/platform/locales/text/pl.json b/src/platform/locales/text/pl.json
index 4ab651803..4bbadc52a 100644
--- a/src/platform/locales/text/pl.json
+++ b/src/platform/locales/text/pl.json
@@ -1981,6 +1981,7 @@
"Services actions": "Akcje usług",
"Session finished": "Sesja została zakończona",
"Set Active Changelist": "Ustaw aktywną listę zmian",
+ "Set DEFAULT": "Ustaw jako domyślny",
"Set NULL": "Ustaw jako NULL",
"Set Value…": "Ustaw wartość…",
"Set active": "Ustaw jako aktywne",
diff --git a/src/platform/locales/text/pt.json b/src/platform/locales/text/pt.json
index 09a7f5815..288127792 100644
--- a/src/platform/locales/text/pt.json
+++ b/src/platform/locales/text/pt.json
@@ -1982,6 +1982,7 @@
"Services actions": "Ações de serviços",
"Session finished": "Sessão finalizada",
"Set Active Changelist": "Definir changelist ativa",
+ "Set DEFAULT": "Definir como padrão",
"Set NULL": "Definir como NULL",
"Set Value…": "Definir valor…",
"Set active": "Definir como ativo",
diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json
index b1eaa024f..3fdc87809 100644
--- a/src/platform/locales/text/zh.json
+++ b/src/platform/locales/text/zh.json
@@ -2308,6 +2308,7 @@
"Services actions": "服务操作",
"Session finished": "会话已结束",
"Set Active Changelist": "设置活动更改列表",
+ "Set DEFAULT": "设为默认值",
"Set NULL": "设为 NULL",
"Set Value…": "设置值…",
"Set active": "设为活动",
@@ -7132,5 +7133,9 @@
"Source archives": "源代码归档",
"Loading library sources…": "正在加载库源代码…",
"Sources not found": "未找到源代码",
- "Cannot load library sources": "无法加载库源代码"
+ "Cannot load library sources": "无法加载库源代码",
+ "Toggle Boolean Cell": "切换布尔单元格",
+ "Toggle {name}": "切换 {name}",
+ "true": "真",
+ "false": "假"
}
diff --git a/src/ui/Select.test.tsx b/src/ui/Select.test.tsx
index 1865b68af..001ef8843 100644
--- a/src/ui/Select.test.tsx
+++ b/src/ui/Select.test.tsx
@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from "vitest";
import { fireEvent, render, screen, within, waitFor } from "@testing-library/react";
import { StrictMode, useState } from "react";
import { Select, SelectListbox, type SelectOption } from "./Select";
+import { useI18n } from "@/platform/i18n";
import { Dialog } from "./Dialog";
const options: SelectOption[] = [
@@ -167,3 +168,17 @@ describe("Select preview lifecycle", () => {
expect(trigger).toHaveFocus();
});
});
+
+it("preserves user values when their labels match translated UI text", () => {
+ const previous = useI18n.getState().texts;
+ useI18n.setState({ texts: { Cancel: "取消" } });
+ try {
+ const changed = setup(false, [{ value: "Cancel", label: "Cancel", verbatim: true }]);
+ expect(within(list()).getByRole("option", { name: "Cancel" })).toBeInTheDocument();
+ key("c");
+ key("Enter");
+ expect(changed).toHaveBeenCalledWith("Cancel");
+ } finally {
+ useI18n.setState({ texts: previous });
+ }
+});
diff --git a/src/ui/Select.tsx b/src/ui/Select.tsx
index 9019f6faa..fc639ba94 100644
--- a/src/ui/Select.tsx
+++ b/src/ui/Select.tsx
@@ -10,6 +10,8 @@ import styles from "./Select.module.css";
export interface SelectOption<V extends string = string> {
value: V;
label: string;
+ /** User values are displayed as written. */
+ verbatim?: boolean;
icon?: IconName | (string & {});
detail?: string;
/** Extra text (not shown) that the search should also match. */
@@ -74,6 +76,7 @@ export function SelectListbox<V extends string = string>({
...aria
}: SelectListboxProps<V>) {
const given = useGivenTx();
+ const labelOf = (o: SelectOption<V>) => (o.verbatim ? o.label : given(o.label));
const [active, setActive] = useState(() =>
Math.max(
0,
@@ -91,7 +94,7 @@ export function SelectListbox<V extends string = string>({
const tokens = q.split(/\s+/).filter(Boolean);
const matches = (o: SelectOption<V>) => {
const haystack =
- `${given(o.label)} ${o.detail != null ? given(o.detail) : ""} ${o.keywords ?? ""}`.toLowerCase();
+ `${labelOf(o)} ${o.detail != null ? given(o.detail) : ""} ${o.keywords ?? ""}`.toLowerCase();
return tokens.every((tok) => containsOrFuzzy(haystack, tok));
};
// Keep section headers visible as long as at least one of their
@@ -181,7 +184,7 @@ export function SelectListbox<V extends string = string>({
const n = filtered.length;
for (let s = prefix.length > 1 ? 0 : 1; s <= n; s++) {
const i = (activeIndex + s) % n;
- if (!unavailable(filtered[i]!) && given(filtered[i]!.label).toLowerCase().startsWith(prefix)) {
+ if (!unavailable(filtered[i]!) && labelOf(filtered[i]!).toLowerCase().startsWith(prefix)) {
setActive(i);
break;
}
@@ -219,7 +222,7 @@ export function SelectListbox<V extends string = string>({
<div key={`${o.section ? "section" : "option"}:${o.value}`} className={styles.sizerRow}>
<span className={styles.check} />
{o.icon && <Icon name={o.icon} size={14} />}
- <span>{given(o.label)}</span>
+ <span>{labelOf(o)}</span>
{o.detail && <span className={styles.sizerDetail}>{given(o.detail)}</span>}
</div>
))}
@@ -228,7 +231,7 @@ export function SelectListbox<V extends string = string>({
items={filtered}
getKey={(o) => `${o.section ? "section" : "option"}:${o.value}`}
isSection={isSection}
- renderSection={(o) => <span className={styles.disabled}>{given(o.label)}</span>}
+ renderSection={(o) => <span className={styles.disabled}>{labelOf(o)}</span>}
activeIndex={activeIndex}
onActiveChange={(i) => {
if (!unavailable(filtered[i]!)) setActive(i);
@@ -243,8 +246,8 @@ export function SelectListbox<V extends string = string>({
<span className={clsx(styles.option, o.disabled && styles.disabled)} aria-disabled={o.disabled || undefined}>
<span className={styles.check}>{o.value === value && <Icon name="check" size={12} />}</span>
{o.icon && <Icon name={o.icon} size={14} />}
- <span className={clsx(styles.optionLabel, o.detail && styles.withDetail)} title={given(o.label)}>
- {given(o.label)}
+ <span className={clsx(styles.optionLabel, o.detail && styles.withDetail)} title={labelOf(o)}>
+ {labelOf(o)}
</span>
{o.detail && (
<span className={styles.detail} title={o.detail}>
@@ -309,7 +312,7 @@ export function Select<V extends string = string>({
<>
{current?.icon && <Icon name={current.icon} size={14} />}
<span className={clsx(styles.value, !current && styles.placeholder)}>
- {given(current?.label ?? placeholder)}
+ {current?.verbatim ? current.label : given(current?.label ?? placeholder)}
</span>
</>
)}