/** DataGrip's Export with 'mysqldump' and Restore with 'mysql' dialogs. */ import { useEffect, useState } from "react"; import clsx from "clsx"; import { call, commands, type DbToolJob } from "@/platform/ipc"; import { tx } from "@/platform/i18n"; import { Checkbox, Dialog, IconButton, Input, T, type DialogButton } from "@/ui"; import { DEFAULT_MYSQLDUMP, dumpMismatch, restoreTargetProblem, mysqldumpOptions, nameList, outputPath, type MysqldumpForm, } from "./dumpTools"; import { DatabaseField, ExecutableField, NamesField, Preview, RunOutput, joinPath, mismatchText, pathKey, runButtons, TargetHint, useDatabaseNames, useDumpInfo, useHome, useTableNames, useToolPreview, } from "./DumpDialogs"; import { splitTarget } from "./model"; import { closeDialog, refresh, sourceById } from "./store"; import { startToolRun, useToolRuns } from "./toolRuns"; import styles from "./Database.module.css"; /** Whether the executable at `path` lists `option` in its `--help` (`false` while unknown). */ function useKnowsOption(path: string, option: string): boolean { const [known, setKnown] = useState<{ path: string; options: string[]; } | null>(null); useEffect(() => { const p = path.trim(); if (!p) return; let live = true; const timer = setTimeout(() => { call(commands.dbToolOptions(p)) .then((options) => live && setKnown({ path: p, options })) .catch(() => live && setKnown({ path: p, options: [] })); }, 250); return () => { live = false; clearTimeout(timer); }; }, [path]); return known?.path === path.trim() && known.options.includes(option); } type Switch = { [K in keyof MysqldumpForm]: MysqldumpForm[K] extends boolean ? K : never; }[keyof MysqldumpForm]; const CHECKS: readonly [Switch, string][] = [ ["addDropTable", "Add DROP TABLE before CREATE TABLE"], ["completeInsert", "Include column names in each INSERT"], ["disableKeys", "Add DISABLE KEYS before each INSERT block"], ["createOptions", "Include all table options in CREATE TABLE"], ["addLocks", "Add LOCK TABLES around each table"], ["routines", "Include stored routines"], ["addDropTrigger", "Add DROP TRIGGER before CREATE TRIGGER"], ["events", "Include scheduled events"], ["noData", "Export schema without data"], ]; export function MysqlDumpDialog({ target, database, tables }: { target: string; database: string; tables?: string }) { const source = sourceById(target); const home = useHome(); const [executable, setExecutable] = useState(""); const [form, setForm] = useState({ ...DEFAULT_MYSQLDUMP, databases: database, tables: tables ?? "", }); const [edited, setOutput] = useState(null); const output = edited ?? (home ? joinPath(home, "{data_source}-{database}-{timestamp}.sql") : ""); const [runKey, setRunKey] = useState(null); const running = useToolRuns((s) => (runKey !== null ? s.runs[runKey]?.status === "running" : false)); const knowsMasking = useKnowsOption(executable, "masking-policies"); const chosenDatabases = nameList(form.databases); const oneDatabase = chosenDatabases.length === 1; const databases = useDatabaseNames(target); const tableNames = useTableNames(splitTarget(target).id, oneDatabase ? chosenDatabases : null)?.map((t) => t.name) ?? null; const set = (k: K) => (v: MysqldumpForm[K]) => setForm((f) => ({ ...f, [k]: v })); const jobFor = (file: string): DbToolJob => ({ tool: "mysqldump", file, options: mysqldumpOptions(form, knowsMasking), }); const preview = useToolPreview(target, executable || "mysqldump", jobFor(output)); const browse = async () => { try { const { save } = await import("@/platform/dialog"); const path = await save({ defaultPath: output }); if (path) setOutput(path); } catch { // No dialog (tests): keep typing the path. } }; const run = async () => { const databases = nameList(form.databases); const file = outputPath(output, { dataSource: source?.name ?? "", database: databases.join("_"), now: new Date(), }); const job = jobFor(file); localStorage.setItem(pathKey("mysqldump"), executable); const commandLine = await call(commands.dbToolPreview(target, executable, job)).catch(() => ""); setRunKey( startToolRun({ target, executable, job, commandLine, output: file, from: databases.join(", ") || tx("all databases"), to: file, }), ); }; const buttons: DialogButton[] = runKey !== null ? runButtons(runKey, running, () => setRunKey(null)) : [ { label: "Cancel", role: "cancel" }, { label: "Run", role: "default", disabled: !executable.trim() || !output.trim(), onClick: () => void run(), }, ]; return ( {runKey !== null ? ( ) : (
Output result to:
setOutput(e.target.value)} /> void browse()} />
Allowed substitution patterns: {"{timestamp}, {data_source}, {database}"} Databases to dump: Tables to dump:
{CHECKS.map(([k, label]) => ( ))} {knowsMasking && ( )}
)}
); } export function MysqlRestoreDialog({ target, database: initialDatabase }: { target: string; database: string }) { const source = sourceById(target); const [executable, setExecutable] = useState(""); const [database, setDatabase] = useState(initialDatabase); const [file, setFile] = useState(""); const [force, setForce] = useState(false); const [runKey, setRunKey] = useState(null); const running = useToolRuns((s) => (runKey !== null ? s.runs[runKey]?.status === "running" : false)); const readOnly = !!source?.readOnly; const info = useDumpInfo(file); const mismatch = dumpMismatch("mysql", info?.kind ?? null); const databases = useDatabaseNames(target); const creates = !!info?.createsDatabase; // Until the dump is read, an empty choice is not yet wrong. const problem = restoreTargetProblem(database, databases?.names ?? null, true, creates || !info); const job: DbToolJob = { tool: "mysql", file, options: { database, force } }; const preview = useToolPreview(target, executable || "mysql", job); const browse = async () => { try { const { open } = await import("@/platform/dialog"); const path = await open({ multiple: false, directory: false, title: tx("Path to dump"), }); if (typeof path === "string") setFile(path); } catch { // No dialog (tests): keep typing the path. } }; const run = async () => { localStorage.setItem(pathKey("mysql"), executable); const commandLine = await call(commands.dbToolPreview(target, executable, job)).catch(() => preview); setRunKey( startToolRun({ target, executable, job, commandLine, from: file, to: database || (source?.name ?? target), onSuccess: () => void refresh(target), }), ); }; const buttons: DialogButton[] = runKey !== null ? runButtons(runKey, running, () => setRunKey(null)) : [ { label: "Cancel", role: "cancel" }, { label: "Run", role: "default", disabled: readOnly || !!mismatch || !!problem || !info || !executable.trim() || !file.trim(), title: readOnly ? tx`The data source is read-only` : undefined, onClick: () => void run(), }, ]; return ( {runKey !== null ? ( ) : (
Database: Path to dump:
setFile(e.target.value)} /> void browse()} />
{mismatch ? mismatchText(mismatch) : mysql runs the SQL dump that mysqldump wrote.} {readOnly && ( <> The data source is read-only. )}
)}
); }