Порівняти коміти

...
Автор SHA1 Повідомлення Дата
l0ng-aiтаClaude Opus 5.5 0379d597be fix(database): rename databases and schemas from the tree
Rename… (db.rename, Shift+F6) did nothing on a database or schema node:
canRename accepted only tables, columns, views and PostgreSQL indexes, and
database nodes have no schema object.

Databases of a server that creates them (PostgreSQL, SQL Server) rename with
ALTER DATABASE after closing the IDE's sessions on them; the connected
database and read-only sources keep Rename disabled, as Drop does. Schemas
rename with ALTER SCHEMA on PostgreSQL and Snowflake. Both use the rename
dialog with its SQL preview and refresh the tree.

Fixes #5205

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-22 21:22:40 +08:00
9 змінених файлів з 120 додано та 9 видалено

No files matched your search

+32 -7
Переглянути файл
@@ -17,6 +17,7 @@ import {
createTableSql,
draftOf,
dropDatabaseSql,
renameDatabaseSql,
dropSql,
ident,
reference,
@@ -33,6 +34,7 @@ import {
connectedTargets,
createDatabase,
dropDatabase,
renameDatabase,
loadDetails,
openSourceDialog,
readableDdl,
@@ -103,20 +105,34 @@ function useRunner() {
// ---- Rename ------------------------------------------------------------------
function RenameDialog({ id, object }: { id: string; object: DbObjectRef | null }) {
/** Renames a data source, a schema object, or (with `database`) a database of the server. */
function RenameDialog({ id, object, database }: { id: string; object: DbObjectRef | null; database?: string }) {
const source = sourceById(id);
const initial = object ? objectName(object) : (source?.name ?? "");
const initial = database ?? (object ? objectName(object) : (source?.name ?? ""));
const [name, setName] = useState(initial);
const { busy, runAndClose } = useRunner();
const [renaming, setRenaming] = useState(false);
const driver = driverOf(id);
const changed = !!name.trim() && name.trim() !== initial;
const sql = object && changed ? renameSql(driver, object, name.trim()) : "";
const submit = () => {
const sql = !changed
? ""
: database !== undefined
? renameDatabaseSql(driver, database, name.trim())
: object
? renameSql(driver, object, name.trim())
: "";
const submit = async () => {
if (!changed) return closeDialog();
if (database !== undefined) {
setRenaming(true);
if (await renameDatabase(id, database, sql)) closeDialog();
else setRenaming(false);
return;
}
if (!object) return void renameSource(id, name).then(closeDialog);
void runAndClose(id, [sql]);
};
const what = object ? KIND_LABEL[object.kind] : "data source";
const what = database !== undefined ? "database" : object ? KIND_LABEL[object.kind] : "data source";
return (
<Dialog
open
@@ -125,7 +141,12 @@ function RenameDialog({ id, object }: { id: string; object: DbObjectRef | null }
width={480}
buttons={[
{ label: "Cancel", role: "cancel" },
{ label: "Refactor", role: "default", disabled: busy || !name.trim(), onClick: () => void submit() },
{
label: "Refactor",
role: "default",
disabled: busy || renaming || !name.trim(),
onClick: () => void submit(),
},
]}
>
<div className={styles.dialogBody}>
@@ -139,7 +160,7 @@ function RenameDialog({ id, object }: { id: string; object: DbObjectRef | null }
onFocus={(e) => e.currentTarget.select()}
onChange={(e) => setName(e.target.value)}
/>
{object && <SqlPreview sql={sql || `-- ${what} keeps its name`} />}
{(object || database !== undefined) && <SqlPreview sql={sql || `-- ${what} keeps its name`} />}
</div>
</Dialog>
);
@@ -895,6 +916,10 @@ export function ObjectDialogs() {
switch (dialog.kind) {
case "rename":
return <RenameDialog key={`${dialog.id}`} id={dialog.id} object={dialog.object} />;
case "renameDatabase":
return (
<RenameDialog key={`${dialog.id}:${dialog.database}`} id={dialog.id} object={null} database={dialog.database} />
);
case "drop":
return <DropDialog id={dialog.id} object={dialog.object} />;
case "truncate":
+13
Переглянути файл
@@ -13,7 +13,9 @@ import {
dropSql,
ident,
reference,
canRename,
renameSql,
renameDatabaseSql,
scriptSql,
truncateSql,
quoteIdent,
@@ -114,6 +116,17 @@ describe("database object SQL", () => {
);
});
it("renames schemas and databases where the server can", () => {
const schema = { kind: "schema" as const, schema: "sales", name: "sales" };
expect(canRename("postgres", schema)).toBe(true);
expect(canRename("snowflake", schema)).toBe(true);
expect(canRename("mysql", schema)).toBe(false);
expect(canRename("sqlServer", schema)).toBe(false);
expect(renameSql("postgres", schema, "Old Sales")).toBe('alter schema sales rename to "Old Sales";');
expect(renameDatabaseSql("postgres", "shop", "store")).toBe("alter database shop rename to store;");
expect(renameDatabaseSql("sqlServer", "shop", "store")).toBe("alter database shop modify name = store;");
});
it("drops with IF EXISTS / CASCADE", () => {
const t = { kind: "table" as const, schema: "public", name: "users" };
expect(dropSql("postgres", t, { ifExists: true, cascade: true })).toBe(
+10 -1
Переглянути файл
@@ -86,12 +86,15 @@ export const canRename = (driver: DbDriver, o: DbObjectRef) =>
(o.kind === "table" ||
o.kind === "column" ||
(o.kind === "view" && driver !== "sqlite") ||
(o.kind === "index" && driver === "postgres"));
(o.kind === "index" && driver === "postgres") ||
(o.kind === "schema" && (driver === "postgres" || driver === "snowflake")));
/** The statement renaming `o` to `to`. */
export function renameSql(driver: DbDriver, o: DbObjectRef, to: string): string {
const q = qualifiedName(driver, o.schema, o.name);
switch (o.kind) {
case "schema":
return `alter schema ${ident(driver, o.name)} rename to ${ident(driver, to)};`;
case "column":
return `alter table ${q} rename column ${ident(driver, o.column ?? "")} to ${ident(driver, to)};`;
case "index":
@@ -239,6 +242,12 @@ export function dropDatabaseSql(driver: DbDriver, name: string, force: boolean):
return `drop database ${db}${force && driver === "postgres" ? " with (force)" : ""};`;
}
/** The statement renaming database `name` of a server to `to` (PostgreSQL, SQL Server). */
export function renameDatabaseSql(driver: DbDriver, name: string, to: string): string {
if (driver === "sqlServer") return `alter database ${ident(driver, name)} modify name = ${ident(driver, to)};`;
return `alter database ${ident(driver, name)} rename to ${ident(driver, to)};`;
}
export type ScriptKind = "selectAll" | "selectFirst" | "insert" | "update" | "delete";
export const SCRIPT_LABELS: Record<ScriptKind, string> = {
+49
Переглянути файл
@@ -0,0 +1,49 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { getAction } from "@/platform/actions";
import type { DbNode } from "./nodes";
import { useDatabase } from "./store";
import { registerDatabaseTreeActions } from "./treeActions";
import { nodeMenu } from "./treeMenu";
const database = (current: boolean): DbNode => ({ kind: "database", key: "db", id: "pg:shop", name: "shop", current });
const schema: DbNode = { kind: "schema", id: "pg:shop", key: "schema", schema: "sales" };
const renameItem = (n: DbNode) =>
nodeMenu(n).find((item) => "action" in item && item.action === "db.rename") as { disabled?: boolean } | undefined;
let dispose: () => void;
beforeEach(() => {
dispose = registerDatabaseTreeActions();
useDatabase.setState({ sources: [{ id: "pg", driver: "postgres" }], dialog: null, loaded: true });
});
afterEach(() => dispose());
describe("Rename on databases and schemas", () => {
it("is offered on a database other than the connected one", () => {
expect(renameItem(database(false))?.disabled).toBe(false);
expect(renameItem(database(true))?.disabled).toBe(true);
});
it("is offered on a schema", () => {
expect(renameItem(schema)?.disabled).toBe(false);
});
it("is not offered on a read-only data source", () => {
useDatabase.setState({ sources: [{ id: "pg", driver: "postgres", readOnly: true }] });
expect(renameItem(database(false))?.disabled).toBe(true);
});
it("opens the rename dialog through db.rename", async () => {
await getAction("db.rename")!.run({ arg: database(false) } as never);
expect(useDatabase.getState().dialog).toEqual({ kind: "renameDatabase", id: "pg", database: "shop" });
useDatabase.setState({ dialog: null });
await getAction("db.rename")!.run({ arg: database(true) } as never);
expect(useDatabase.getState().dialog).toBeNull();
await getAction("db.rename")!.run({ arg: schema } as never);
expect(useDatabase.getState().dialog).toMatchObject({
kind: "rename",
id: "pg:shop",
object: { kind: "schema", name: "sales" },
});
});
});
+9
Переглянути файл
@@ -135,6 +135,7 @@ export type DialogState =
| { kind: "sourceUrl" }
/** Rename a data source (`object` null) or a schema object of target `id`. */
| { kind: "rename"; id: string; object: DbObjectRef | null }
| { kind: "renameDatabase"; id: string; database: string }
/** Confirm Drop / Truncate, with a preview of the statement. */
| { kind: "drop"; id: string; object: DbObjectRef }
| { kind: "truncate"; id: string; schema: string; table: string }
@@ -1349,6 +1350,14 @@ export async function dropDatabase(id: string, database: string, sql: string): P
return true;
}
/** Renames `database` of data source `id` with `sql` after closing the sessions on it. */
export async function renameDatabase(id: string, database: string, sql: string): Promise<boolean> {
await disconnect(`${id}:${database}`);
if (!(await runSql(id, [sql]))) return false;
void refresh(id);
return true;
}
/** Opens the query console of `id` with `text` appended and selected (SQL Scripts › …). */
export async function openConsoleWith(id: string, text: string): Promise<void> {
let path: string;
+3
Переглянути файл
@@ -346,6 +346,9 @@ export function registerDatabaseTreeActions(): () => void {
if (!n) return;
const id = nodeTarget(n);
if (n.kind === "source" && id) return openDialog({ kind: "rename", id, object: null });
const source = sourceById(id);
if (n.kind === "database" && !n.current && !source?.readOnly && createsDatabases(source))
return openDialog({ kind: "renameDatabase", id: splitTarget(n.id).id, database: n.name });
const o = objectOf(n);
if (id && o && canRename(driverOf(id), o)) openDialog({ kind: "rename", id, object: o });
},
+2 -1
Переглянути файл
@@ -178,6 +178,7 @@ export function nodeMenu(n: DbNode | null): MenuItem[] {
{ label: "Copy/Paste", submenu: [copyRef] },
refresh,
act("db.disconnect", n, { disabled: !useDatabase.getState().connected.has(id) || n.current }),
...(createsDatabases(sourceById(id)) ? [sep, act("db.rename", n, { disabled: n.current || readOnly })] : []),
sep,
navigation(),
sqlScripts(n, false),
@@ -191,7 +192,7 @@ export function nodeMenu(n: DbNode | null): MenuItem[] {
...(n.kind === "schema" ? [{ label: "Copy/Paste", submenu: [copyRef] }] : []),
refresh,
sep,
...(n.kind === "schema" ? [quickDoc] : []),
...(n.kind === "schema" ? [rename, sep, quickDoc] : []),
navigation(),
sep,
sqlScripts(n, false),
+1
Переглянути файл
@@ -1485,6 +1485,7 @@
"Installed: {0} · No newer npm release.": "Installed: {0} · No newer npm release.",
"Installed: {0}. Use your installer to manage this release channel.": "Installed: {0}. Use your installer to manage this release channel.",
"npm scripts": "npm scripts",
"database": "database",
"npm could not complete the operation ({0}).": "npm could not complete the operation ({0}).",
"An update for this agent is already running.": "An update for this agent is already running.",
"This is not a global npm install OpenIDEA can update. Use its original installer.": "This is not a global npm install OpenIDEA can update. Use its original installer.",
+1
Переглянути файл
@@ -5561,6 +5561,7 @@
"trigger": "触发器",
"sequence": "序列",
"data source": "数据源",
"database": "数据库",
"{count} library frames hidden": "已隐藏 {count} 个库帧",
"unverified": "未验证",
"temp": "临时",