/** * Dialogs of the Database tree's object actions, after IDEA's: Rename, Confirm * Drop, Truncate, Modify Table / New Table, New Database / New Schema (with a * Preview of the SQL they run), Remove Data Source, Data Source from URL, and the Quick Documentation popup. */ import { useEffect, useMemo, useRef, useState } from "react"; import { call, commands, type DbColumnInfo, type DbDriver, type DbPersistence, type DbSourceFolder, type DbTableDetails, type DbTableGrant, } from "@/platform/ipc"; import { highlightInto } from "@/editor/lsp/markdown"; import { Button, Checkbox, Dialog, IconButton, Input, Popup, Icon, SearchField, Select, T, Tabs, tooltipAttrs, type SelectOption, } from "@/ui"; import { parseSourceUrl, sourceLabel, splitTarget } from "./model"; import { nodeTarget, schemaObjectOf, tableOf, type DbNode } from "./nodes"; import { alterTableSql, canAlterColumn, canAlterIndex, canChangePrimaryKey, createDatabaseSql, createSchemaSql, commentsSupported, createTableCommentSql, createTableKeySql, createTableSql, draftOf, dropDatabaseSql, grantMatrix, grantsSupported, hasTableProperties, indexDraftOf, keyName, keySupport, propertySupport, renameDatabaseSql, dropSql, ident, reference, renameSql, tablePropertiesOf, truncateSql, type ColumnDraft, type IndexDraft, type TableProperties, templateOf, type CreateOptions, type DbObjectRef, } from "./objects"; import { closeDialog, createSourceFolder, detailsKey, connectedTargets, createDatabase, dropDatabase, renameDatabase, loadDetails, loadGrants, loadTables, openSourceDialog, readableDdl, refresh, renameSourceFolder, renameSource, runSql, sourceById, useDatabase, withConnection, type DialogState, } from "./store"; import { openTableData } from "./treeActions"; import styles from "./Database.module.css"; import { tx, txPart } from "@/platform/i18n"; /** Read-only SQL with the editor's syntax colours (IDEA's dialog Preview pane). */ function SqlPreview({ sql, label = "Preview" }: { sql: string; label?: string }) { const ref = useRef(null); useEffect(() => { const el = ref.current; if (!el) return; el.textContent = sql; void highlightInto(el, sql, "SQL"); }, [sql]); return (
{label}
    
); } const driverOf = (id: string): DbDriver => sourceById(id)?.driver ?? "sqlite"; const KIND_LABEL: Record = { table: "table", view: "view", materializedView: "materialized view", column: "column", index: "index", schema: "schema", function: "function", procedure: "procedure", package: "package", trigger: "trigger", sequence: "sequence", }; function objectName(o: DbObjectRef): string { return o.kind === "column" ? (o.column ?? "") : o.name; } function useRunner() { const [busy, setBusy] = useState(false); const running = useRef(false); const runAndClose = async (id: string, statements: string[]): Promise => { if (running.current) return false; running.current = true; setBusy(true); const ok = await runSql(id, statements); running.current = false; setBusy(false); if (ok) closeDialog(); return ok; }; return { busy, runAndClose }; } // ---- Rename ------------------------------------------------------------------ /** 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 = 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 = !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 = database !== undefined ? "database" : object ? KIND_LABEL[object.kind] : "data source"; return ( void submit(), }, ]} >
e.currentTarget.select()} onChange={(e) => setName(e.target.value)} /> {(object || database !== undefined) && }
); } // ---- Drop / Truncate ----------------------------------------------------------- function DropDialog({ id, object }: { id: string; object: DbObjectRef }) { const driver = driverOf(id); const [ifExists, setIfExists] = useState(false); const [cascade, setCascade] = useState(false); const { busy, runAndClose } = useRunner(); const sql = dropSql(driver, object, { ifExists, cascade }); return ( void runAndClose(id, [sql]) }, ]} >
{tx`Drop ${txPart(KIND_LABEL[object.kind])}`} {reference(driver, object)} {tx`? This cannot be undone.`}
); } function TruncateDialog({ id, schema, table }: { id: string; schema: string; table: string }) { const driver = driverOf(id); const [restartIdentity, setRestart] = useState(false); const [cascade, setCascade] = useState(false); const { busy, runAndClose } = useRunner(); const sql = truncateSql(driver, schema, table, { restartIdentity, cascade }); return ( void runAndClose(id, [sql]) }, ]} >
Delete all rows of {table}?
{driver === "postgres" && ( <> )}
); } // ---- New Database / New Schema / Drop database --------------------------------- const TEMPLATES: SelectOption[] = [ { value: "", label: "Server default" }, ...["template0", "template1"].map((name) => ({ value: name, label: name, verbatim: true })), ]; /** An optional text field of the create dialogs: empty leaves it to the server. */ function OptionField({ id, label, value, onChange, }: { id: string; label: string; value: string; onChange: (value: string) => void; }) { return ( <> onChange(e.target.value)} /> ); } /** New › Database (`database`) or New › Schema (`schema`) in target `id`. */ function CreateDialog({ id, what }: { id: string; what: "database" | "schema" }) { const driver = driverOf(id); const [name, setName] = useState(""); const [opts, setOpts] = useState({}); const { busy: running, runAndClose } = useRunner(); const [creating, setCreating] = useState(false); const busy = running || creating; const sql = (what === "database" ? createDatabaseSql : createSchemaSql)(driver, name.trim() || "", opts); const submit = async () => { if (what === "schema") { if (await runAndClose(id, [sql])) void refresh(id); return; } setCreating(true); if (await createDatabase(id, templateOf(driver, opts), sql)) closeDialog(); else setCreating(false); }; const field = (key: keyof CreateOptions, label: string) => ( setOpts((o) => ({ ...o, [key]: value }))} /> ); return (
setName(e.target.value)} /> {what === "database" && driver === "postgres" && ( <> {field("owner", "Owner:")} setName(e.target.value)} autoFocus={!table} /> {schema}
{comments && (
setComment(e.target.value)} />
)} {(showGrants || showProperties) && ( setTab(t as typeof tab)} items={[ { id: "columns", label: tx("Columns") }, ...(showProperties ? [{ id: "properties", label: tx("Properties") }] : []), ...(showGrants ? [{ id: "grants", label: tx("Grants") }] : []), ]} /> )} {showGrants && tab === "grants" ? ( ) : showProperties && tab === "properties" ? ( setProperties((v) => ({ ...v, ...p }))} /> ) : (
{support.uniqueKey && ( addIndex("unique")} /> )} {support.index && ( addIndex("index")} /> )}
{groupHeader("columns", "Columns", shownColumns.length)} {!collapsed.has("columns") && shownColumns.map((c) => (
setSelected({ group: "column", key: c.key })} > {c.name || ""} {c.dataType}
))}
{groups.map((g) => (
{groupHeader(g.id, g.label, g.rows.length)} {!collapsed.has(g.id) && g.rows.map((r) => (
{ const d = r.draft; if (d) setSelected({ group: "index", key: d.key }); }} > {r.name} {r.detail}
))}
))}
{current ? ( <> patch({ name: e.target.value })} /> patch({ dataType: e.target.value })} /> {driver !== "clickhouse" && ( <> patch({ notNull })} label="Not null" /> )} {(table ? support.primaryKey : driver !== "clickhouse") && ( <> patch(primaryKey ? { primaryKey, notNull: true } : { primaryKey })} label="Primary key" /> )} patch({ default: e.target.value })} /> {comments && ( <> patch({ comment: e.target.value })} /> )} {locked && ( <> SQLite can rename or drop an existing column, not change its type, NOT NULL or default. )} ) : currentIndex ? ( <> patchIndex({ name: e.target.value })} /> Columns
{currentIndex.original ? currentIndex.original.columns.map((n) => ( {}} label={{n}} /> )) : liveColumns.map((c) => ( patchIndex({ columnKeys: on ? [...currentIndex.columnKeys, c.key] : currentIndex.columnKeys.filter((k) => k !== c.key), }) } label={{c.name}} /> ))}
{currentIndex.kind === "index" && ( <> patchIndex({ unique })} label="Unique" /> )} {indexLocked && ( <> SQLite cannot drop the index of a primary key or unique constraint. )} ) : ( Select a column )}
)} {TYPES[driver].map((t) => (
); } const PERSISTENCE: Record = { permanent: "Logged", unlogged: "Unlogged", temporary: "Temporary", }; /** * The Modify Table dialog's Properties tab: the owner, tablespace, storage options and * persistence the engine reports (editable per `propertySupport`), its access method and partition key read-only. */ function PropertiesPanel({ driver, details, value, onChange, }: { driver: DbDriver; details: DbTableDetails | undefined; value: TableProperties; onChange: (p: Partial) => void; }) { const support = propertySupport(driver); const reported = (v: unknown) => v !== undefined && v !== null; const original = details?.persistence; // A temporary table can't be made permanent, nor a permanent one temporary. const persistence: DbPersistence[] = original === "temporary" ? ["temporary"] : ["permanent", "unlogged"]; return (
{reported(details?.owner) && ( <> onChange({ owner: e.target.value })} /> )} {reported(details?.tablespace) && ( <> onChange({ tablespace: e.target.value })} /> )} {reported(details?.persistence) && ( <> onChange({ storageOptions: e.target.value })} /> )} {reported(details?.accessMethod) && ( <> )} {reported(details?.partitioning) && ( <> )}
); } type GrantsState = | { status: "loading" } | { status: "ok"; grants: DbTableGrant[] } | { status: "error"; message: string }; /** The Modify Table dialog's Grants tab: who holds which privilege on `table`, read-only. */ function GrantsPanel({ id, schema, table }: { id: string; schema: string; table: string }) { const [state, setState] = useState({ status: "loading" }); useEffect(() => { let live = true; loadGrants(id, schema, table).then( (grants) => live && setState({ status: "ok", grants }), (e: unknown) => live && setState({ status: "error", message: e instanceof Error ? e.message : String(e) }), ); return () => { live = false; }; }, [id, schema, table]); if (state.status !== "ok") return (
{state.status === "error" ? state.message : tx("Loading…")}
); const { privileges, rows } = grantMatrix(state.grants); if (!rows.length) return (
No privileges are granted on this table.
); return (
{privileges.map((p) => ( ))} {rows.map((r) => ( {privileges.map((p) => { const grantable = r.privileges.get(p); return ( ); })} ))}
Grantee Grantor {p}
{r.grantee} {r.grantor ?? "—"} {grantable !== undefined && ( {grantable && *} )}
* With grant option: the grantee may grant the privilege to others.
); } // ---- Data sources ------------------------------------------------------------- function SourceUrlDialog() { const [url, setUrl] = useState(""); const parsed = url.trim() ? parseSourceUrl(url) : null; const next = () => { if (!parsed) return; closeDialog(); const s = parsed.source; const name = s.name ?? (s.driver === "jdbc" ? undefined : `${s.database || s.user || "db"}@${s.host}`); openSourceDialog(null, { ...s, name }, parsed.password); }; return (
setUrl(e.target.value)} /> {url.trim() && !parsed ? tx("Not a URL of PostgreSQL, MySQL, SQLite or a compatible database") : "postgresql://, mysql://, mariadb://, redshift://, tidb://…, jdbc:…, sqlite:path, jdbc:duckdb:path"}
); } // ---- Quick Documentation ------------------------------------------------------ function QuickDoc({ node, anchor }: { node: DbNode; anchor: { x: number; y: number } }) { const id = nodeTarget(node) ?? ""; const source = sourceById(id); const t = tableOf(node); const [ddl, setDdl] = useState(null); const object = schemaObjectOf(node); const showDdl = node.kind === "table" || !!object; useEffect(() => { if (!showDdl || (!t && !object)) return; let live = true; const read = object ? withConnection(object.id, () => call(commands.dbObjectDdl(object.id, object.schema, object.kind, object.name))) : withConnection(t!.id, () => call(commands.dbDdl(t!.id, t!.schema, t!.table))).then((d) => readableDdl(d, driverOf(t!.id)), ); read .then((d) => live && setDdl(d)) .catch((e: unknown) => live && setDdl(`-- ${e instanceof Error ? e.message : String(e)}`)); return () => { live = false; }; // eslint-disable-next-line react-hooks/exhaustive-deps }, [node.key]); const rows: Array<[string, string]> = []; if (source) rows.push(["Data Source", source.name ?? ""]); const db = splitTarget(id).database; if (db) rows.push(["Database", db]); switch (node.kind) { case "source": rows.push(["Driver", sourceLabel(node.source).replace(/^.*\((.*)\)$/, "$1")]); if (node.source.comment?.trim()) rows.push(["Comment", node.source.comment.trim()]); rows.push( node.source.driver === "sqlite" ? ["File", node.source.file ?? ""] : [ "Host", `${node.source.host ?? ""}${node.source.port ? `:${node.source.port}` : ""}${node.source.database ? `/${node.source.database}` : ""}`, ], ); rows.push(["Status", connectedTargets(node.source.id ?? "").length ? "Connected" : "Not connected"]); break; case "database": rows.push(["Database", node.name]); break; case "schema": case "folder": rows.push(["Schema", node.schema]); break; case "routine": rows.push( ["Schema", node.schema], [node.routine.kind === "procedure" ? "Procedure" : "Function", node.routine.name], ); if (node.routine.arguments) rows.push(["Arguments", node.routine.arguments]); if (node.routine.returns) rows.push(["Returns", node.routine.returns]); break; case "package": rows.push(["Schema", node.schema], ["Package", node.package.name]); break; case "sequence": rows.push(["Schema", node.schema], ["Sequence", node.sequence.name], ["Type", node.sequence.dataType]); break; case "trigger": rows.push( ["Table", node.table], ["Trigger", node.trigger.name], ["Fires", `${node.trigger.timing} ${node.trigger.events}`], ); break; default: if (t) rows.push(["Schema", t.schema], [t.view ? "View" : "Table", t.table]); } let definition: string | null = null; if (node.kind === "column") { const c = node.column; const d = driverOf(id); definition = `${ident(d, c.name)} ${c.dataType}${c.nullable ? "" : " not null"}${c.default ? ` default ${c.default}` : ""}${c.primaryKey ? " primary key" : ""}`; } else if (node.kind === "index") { definition = `${node.index.unique ? "unique " : ""}index ${node.index.name} (${node.index.columns.join(", ")})`; } else if (node.kind === "foreignKey") { definition = `foreign key (${node.fk.columns.join(", ")}) references ${node.fk.refTable} (${node.fk.refColumns.join(", ")})`; } else if (node.kind === "key") { definition = `primary key (${node.columns.join(", ")})`; } return (
{rows.map(([k, v]) => (
{k}:
{v}
))}
{definition && } {showDdl && } {t && (
)}
); } const NO_SOURCES: readonly string[] = []; function SourceFolderDialog({ folder, sources = NO_SOURCES, }: { folder: DbSourceFolder | null; sources?: readonly string[]; }) { const [name, setName] = useState(folder?.name ?? ""); const [busy, setBusy] = useState(false); const submit = async () => { if (!name.trim() || busy) return; setBusy(true); const saved = folder ? await renameSourceFolder(folder.id, name) : await createSourceFolder(name, sources); if (saved) closeDialog(); else setBusy(false); }; return ( void submit(), }, ]} >
e.currentTarget.select()} onChange={(e) => setName(e.target.value)} /> {!folder && sources.length > 0 && ( {tx`The ${sources.length} selected data sources will be moved into this folder.`} )}
); } export function ObjectDialogs() { const dialog = useDatabase((s) => s.dialog) as DialogState | null; if (!dialog) return null; switch (dialog.kind) { case "rename": return ; case "renameDatabase": return ( ); case "sourceFolder": return ; case "drop": return ; case "truncate": return ; case "createDatabase": return ; case "createSchema": return ; case "dropDatabase": return ; case "modifyTable": return ( ); case "sourceUrl": return ; case "quickDoc": return ; default: return null; } }