import mariadbCliEnv, { mariadbCliConnectionArgs } from "./mariadb-cli-env"; /** * Prefer mariadb-dump, fall back to mysqldump. */ export function resolveDumpBinary() { const candidates = ["mariadb-dump", "mysqldump"]; for (const bin of candidates) { try { const result = Bun.spawnSync(["which", bin], { stdout: "pipe", stderr: "pipe", }); if (result.exitCode === 0) { return new TextDecoder().decode(result.stdout).trim() || bin; } } catch { // try next } } return "mariadb-dump"; } /** * Prefer mariadb client, fall back to mysql. */ export function resolveClientBinary() { const candidates = ["mariadb", "mysql"]; for (const bin of candidates) { try { const result = Bun.spawnSync(["which", bin], { stdout: "pipe", stderr: "pipe", }); if (result.exitCode === 0) { return new TextDecoder().decode(result.stdout).trim() || bin; } } catch { // try next } } return "mariadb"; } /** * Dump the configured database to an SQL string. */ export async function dumpDatabase(config) { const dumpBin = resolveDumpBinary(); const args = [ dumpBin, ...mariadbCliConnectionArgs(), "--single-transaction", "--routines", "--triggers", "--events", config.db_name, ]; const proc = Bun.spawn(args, { stdout: "pipe", stderr: "pipe", env: mariadbCliEnv(), }); const [stdout, stderr, exitCode] = await Promise.all([ new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited, ]); if (exitCode !== 0) { throw new Error(`Dump failed (exit ${exitCode}): ${stderr || "unknown error"}. Ensure \`mariadb-dump\` or \`mysqldump\` is installed.`); } return stdout; } /** * Restore an SQL dump into the configured database. */ export async function restoreDatabase(config, sql) { const clientBin = resolveClientBinary(); const args = [clientBin, ...mariadbCliConnectionArgs(), config.db_name]; const proc = Bun.spawn(args, { stdin: new Blob([sql]), stdout: "pipe", stderr: "pipe", env: mariadbCliEnv(), }); const [stderr, exitCode] = await Promise.all([ new Response(proc.stderr).text(), proc.exited, ]); if (exitCode !== 0) { throw new Error(`Restore failed (exit ${exitCode}): ${stderr || "unknown error"}. Ensure \`mariadb\` or \`mysql\` is installed.`); } }