Файли
openidea/src/features/database/dumpTools.ts
T
Ernstjan FreriksтаEjaYF 318f4a2d82 feat(database): export with mysqldump and restore with mysql (#4001)
MySQL and MariaDB data sources, schemas and tables get Import/Export >
Export with 'mysqldump' and Restore with 'mysql'. ide-db builds the arguments
from typed options and runs the tool connected like the data source (TCP,
the driver's SSL flags, the SSH tunnel); the password goes in a user-only
temporary option file passed as --defaults-extra-file and removed after the
run. Restore pipes the dump into mysql's standard input.

Restore dialogs (MySQL and PostgreSQL) now check the target first: the
Database field lists the source's databases and disables Run for a missing
one, and db_dump_info (formerly db_dump_kind) reports whether an SQL dump
creates its database itself. pg_restore gains --create.

Part of #3188

Co-authored-by: EjaYF <[email protected]>
2026-11-17 23:39:50 +08:00

263 рядки
9.8 KiB
TypeScript

/** The dump / restore dialogs' model: their forms, file names, tool choice and version hints. */
import type {
DataSource,
DbDumpFormat,
DbDumpKind,
DbMysqldumpOptions,
DbPgDumpOptions,
DbPgRestoreOptions,
DbPsqlOptions,
DbTool,
DbToolInstall,
} from "@/platform/ipc";
import { splitTarget } from "./model";
import { nodeTarget, type DbNode } from "./nodes";
export const DUMP_FORMATS: readonly { id: DbDumpFormat; label: string; extension: string }[] = [
{ id: "plain", label: "Plain SQL", extension: ".sql" },
{ id: "custom", label: "Custom archive", extension: ".dump" },
{ id: "directory", label: "Directory", extension: "" },
{ id: "tar", label: "Tar archive", extension: ".tar" },
];
/** A name list as typed in a field (`public, audit`). */
type Typed<T, K extends keyof T> = Omit<T, K> & { [P in K]: string };
export type DumpForm = Typed<DbPgDumpOptions, "schemas" | "tables" | "excludeTables">;
export type RestoreForm = Typed<DbPgRestoreOptions, "schemas">;
/** `maskingPolicies` is the checkbox; whether the client knows the option is decided at run time. */
export type MysqldumpForm = Typed<Omit<DbMysqldumpOptions, "maskingPolicies">, "databases" | "tables"> & {
maskingPolicies: boolean;
};
export const DEFAULT_DUMP: DumpForm = {
format: "plain",
statements: "copy",
content: "all",
schemas: "",
tables: "",
excludeTables: "",
clean: false,
ifExists: false,
create: false,
noOwner: false,
noPrivileges: false,
jobs: 1,
};
export const DEFAULT_RESTORE: RestoreForm = {
content: "all",
schemas: "",
create: false,
clean: false,
ifExists: false,
noOwner: false,
noPrivileges: false,
singleTransaction: false,
exitOnError: true,
jobs: 1,
};
export const DEFAULT_PSQL: DbPsqlOptions = { singleTransaction: true, stopOnError: true };
/**
* `mysqldump`'s own defaults, except `--single-transaction` instead of DataGrip's
* `--lock-all-tables`, which needs the RELOAD privilege.
*/
export const DEFAULT_MYSQLDUMP: MysqldumpForm = {
databases: "",
tables: "",
addDropTable: true,
disableKeys: true,
addLocks: true,
addDropTrigger: false,
noData: false,
completeInsert: false,
createOptions: true,
routines: false,
events: false,
singleTransaction: true,
lockAllTables: false,
maskingPolicies: false,
};
/** `a, b c` → `["a", "b", "c"]`; a double-quoted part keeps its spaces and commas: `public."Order Items"`. */
export function nameList(text: string): string[] {
return text.match(/(?:"(?:[^"]|"")*"|[^\s,"]|")+/g) ?? [];
}
export function dumpOptions(f: DumpForm): DbPgDumpOptions {
return { ...f, schemas: nameList(f.schemas), tables: nameList(f.tables), excludeTables: nameList(f.excludeTables) };
}
export function restoreOptions(f: RestoreForm): DbPgRestoreOptions {
return { ...f, schemas: nameList(f.schemas) };
}
/** The typed list with `name` added, or taken out when it is there: `a, b` + `c` → `a, b, c`. */
export function toggleName(text: string, name: string): string {
const names = nameList(text);
return (names.includes(name) ? names.filter((n) => n !== name) : [...names, name]).join(", ");
}
/** `knowsMasking`: the chosen `mysqldump` lists `--masking-policies` in its `--help`. */
export function mysqldumpOptions(f: MysqldumpForm, knowsMasking: boolean): DbMysqldumpOptions {
const databases = nameList(f.databases);
return {
...f,
databases,
tables: databases.length === 1 ? nameList(f.tables) : [],
maskingPolicies: knowsMasking ? f.maskingPolicies : null,
};
}
/**
* The PostgreSQL tool for a dump: from its header when known, else `psql` for a `.sql` file and
* `pg_restore` for anything else (archives, directories).
*/
export function restoreToolFor(path: string, kind: DbDumpKind | null = null): Extract<DbTool, "pgRestore" | "psql"> {
if (kind === "postgresArchive") return "pgRestore";
if (kind === "postgresSql") return "psql";
return /\.sql$/i.test(path.trim()) ? "psql" : "pgRestore";
}
export type DumpMismatch = "postgresIntoMysql" | "mysqlIntoPostgres" | "archiveIntoPsql" | "sqlIntoPgRestore";
/** Why `tool` cannot restore a dump of `kind`; `null` when it can, or the kind is unknown. */
export function dumpMismatch(tool: DbTool, kind: DbDumpKind | null): DumpMismatch | null {
if (!kind || kind === "unknown") return null;
if (tool === "mysql") return kind === "mysqlSql" ? null : "postgresIntoMysql";
if (kind === "mysqlSql") return "mysqlIntoPostgres";
if (tool === "psql" && kind === "postgresArchive") return "archiveIntoPsql";
if (tool === "pgRestore" && kind === "postgresSql") return "sqlIntoPgRestore";
return null;
}
export type TargetProblem = "missing" | "noDatabase";
/**
* Why a restore cannot run in or connect to `database`; `null` when it can, or while the
* databases are unknown. An empty name is the data source's own for PostgreSQL; MySQL then runs
* without a database, which only works for a dump that creates its databases.
*/
export function restoreTargetProblem(
database: string,
existing: readonly string[] | null,
mysql: boolean,
createsDatabase: boolean,
): TargetProblem | null {
const name = database.trim();
if (!name) return mysql && !createsDatabase ? "noDatabase" : null;
if (!existing) return null;
return existing.includes(name) ? null : "missing";
}
/** `2026-03-07_09-05-02` (local time). */
export function timestamp(d: Date): string {
const p = (n: number) => String(n).padStart(2, "0");
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}_${p(d.getHours())}-${p(d.getMinutes())}-${p(d.getSeconds())}`;
}
const unsafe = /[\\/:*?"<>|\s]+/g;
/** Fills `{data_source}`, `{database}` and `{timestamp}` of an output path pattern. */
export function outputPath(pattern: string, values: { dataSource: string; database: string; now: Date }): string {
return pattern
.replaceAll("{data_source}", values.dataSource.replace(unsafe, "_"))
.replaceAll("{database}", values.database.replace(unsafe, "_"))
.replaceAll("{timestamp}", timestamp(values.now));
}
/** The pattern with the format's extension in place of the previous one. */
export function withExtension(pattern: string, format: DbDumpFormat): string {
const ext = DUMP_FORMATS.find((f) => f.id === format)!.extension;
return pattern.replace(/\.(sql|dump|backup|tar)$/i, "") + ext;
}
/** A name as a `pg_dump` pattern: quoted unless it is a lower-case identifier. */
export function patternName(name: string): string {
return /^[a-z_][a-z0-9_$]*$/.test(name) ? name : `"${name.replaceAll('"', '""')}"`;
}
/** A typed `pg_dump` name back to the name itself: `"My Schema"` → `My Schema`, `Public` → `public`. */
export function unquoteName(pattern: string): string {
return /^".*"$/.test(pattern) ? pattern.slice(1, -1).replaceAll('""', '"') : pattern.toLowerCase();
}
export interface DumpScope {
target: string;
database: string;
schemas?: string;
tables?: string;
}
/** What the dump / restore actions act on for tree node `n`; `null` when they don't apply. */
export function dumpScope(n: DbNode, source: DataSource | undefined): DumpScope | null {
const target = nodeTarget(n);
if (!target || source?.driver !== "postgres") return null;
const database = n.kind === "database" ? n.name : (splitTarget(target).database ?? source.database ?? "");
if (n.kind === "source" || n.kind === "database") return { target, database };
if (n.kind === "schema") return { target, database, schemas: patternName(n.schema) };
if (n.kind === "table" && n.table.kind === "table")
return { target, database, tables: `${patternName(n.schema)}.${patternName(n.table.name)}` };
return null;
}
/**
* What Export with 'mysqldump' / Restore with 'mysql' act on for tree node `n`: a MySQL schema
* is a database. `null` when they don't apply.
*/
export function mysqlDumpScope(n: DbNode, source: DataSource | undefined): DumpScope | null {
const target = nodeTarget(n);
if (!target || source?.driver !== "mysql") return null;
if (n.kind === "source") return { target, database: source.database ?? "" };
if (n.kind === "schema") return { target, database: n.schema };
if (n.kind === "table" && n.table.kind === "table") return { target, database: n.schema, tables: n.table.name };
return null;
}
/** The major version in a `--version` line (`pg_dump (PostgreSQL) 17.2` → 17). */
export function majorOf(version: string): number | null {
const m = /(\d+)(?:\.\d+)?/.exec(version);
return m ? Number(m[1]) : null;
}
/**
* How a tool's major version fits the server's: `pg_dump` refuses an older-than-server
* copy, and what newer `pg_dump` / `pg_restore` write may not load into an older server
* (17 and later set `transaction_timeout`, unknown before 17).
*/
export function versionFit(tool: DbTool, toolMajor: number | null, serverMajor: number | null) {
if (tool === "psql" || toolMajor === null || serverMajor === null || toolMajor === serverMajor) return "ok";
if (toolMajor < serverMajor) return tool === "pgDump" ? "tooOld" : "ok";
return "newer";
}
/** The copy to preselect: the server's major version, else the one used last, else the newest. */
export function pickInstall(installs: DbToolInstall[], serverMajor: number | null, last: string | null): string {
const matching = installs.find((i) => majorOf(i.version) === serverMajor);
return matching?.path ?? last ?? installs[0]?.path ?? "";
}
/** `< 1 s`, `4 s`, `12 min 4 s`, `2 h 5 min`. */
export function formatElapsed(ms: number): string {
if (ms < 1000) return "< 1 s";
const total = Math.floor(ms / 1000);
const h = Math.floor(total / 3600);
const m = Math.floor((total % 3600) / 60);
const sec = total % 60;
if (h) return `${h} h ${m} min`;
if (m) return `${m} min ${sec} s`;
return `${sec} s`;
}
/** The last part of a path, for one-line summaries. */
export function baseName(path: string): string {
return (
path
.replace(/[\\/]+$/, "")
.split(/[\\/]/)
.pop() || path
);
}