Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

7.5 KB
Raw Blame
import { describe, expect, it } from "vitest";
import {
  databaseBackupFileNamePatternIsValid,
  databaseBackupFilePath,
  databaseBackupRunDirectory,
  databaseBackupTimestamp,
  sanitizeDatabaseBackupFileSegment,
  databaseBackupRunsToPrune,
  databaseBackupTableMatchesPattern,
  normalizeDatabaseBackupRun,
  resolveScheduledDatabaseBackupTableScope,
  type DatabaseBackupRun,
  normalizeDatabaseBackupTableTargets,
  databaseBackupTableTargetKey,
  normalizeDatabaseBackupSchedule,
  toDatabaseBackupExecutionConfig,
} from "../../backup/scheduledDatabaseBackup";

const startedAt = "2026-08-12T00:00:00.000Z";

function run(overrides: Record<string, unknown> = {}) {
  return {
    id: "run-1",
    scheduleName: "One-time backup",
    connectionId: "mysql-1",
    connectionName: "Local MySQL",
    trigger: "manual",
    source: "one-shot",
    status: "success",
    startedAt,
    files: [],
    ...overrides,
  };
}

describe("database backup run persistence", () => {
  it("renders preview names in the saved zone rather than the browser zone", () => {
    const instant = "2026-09-12T18:00:00Z";
    expect(databaseBackupTimestamp(instant, "Asia/Shanghai")).toBe("20260913-020000");
    expect(databaseBackupTimestamp(instant, "America/New_York")).toBe("20260912-140000");
    expect(databaseBackupRunDirectory("/backups", "{date}/{timestamp}", "Daily", instant, "12345678", "Asia/Shanghai")).toBe("/backups/20260913/20260913020000");
    expect(databaseBackupFilePath("/backups", "Daily", "app", instant, "12345678", "gzip", "{timestamp}", "Asia/Shanghai")).toBe("/backups/20260913-020000__app.sql.gz");
  });
  it("uses a gzip extension when the backup output is compressed", () => {
    expect(databaseBackupFilePath("/backups", "Nightly", "app", startedAt, "run-12345678", "gzip")).toMatch(/\.sql\.gz$/);
  });

  it("uses a custom file-name template without implicit run ID suffixes", () => {
    const path = databaseBackupFilePath("/backups", "Nightly", "app", startedAt, "run-12345678", "none", "before-migration");

    expect(path).toBe("/backups/before-migration__app.sql");
  });

  it("renders all file-name template variables without duplicating suffixes", () => {
    const path = databaseBackupFilePath("/backups", "Nightly", "app", startedAt, "run-12345678", "none", "{schedule}__{date}__{database}__{runId}");

    expect(path).toBe("/backups/Nightly__20260812__app__run-1234.sql");
  });

  it("rejects file-name templates that could form a path", () => {
    expect(databaseBackupFileNamePatternIsValid("before-migration")).toBe(true);
    expect(databaseBackupFileNamePatternIsValid("../before-migration")).toBe(false);
    expect(databaseBackupFileNamePatternIsValid("before-migration ")).toBe(false);
  });

  it("accepts a one-shot run without a schedule id", () => {
    const normalized = normalizeDatabaseBackupRun(run());

    expect(normalized).toEqual(
      expect.objectContaining({
        id: "run-1",
        scheduleId: undefined,
        source: "one-shot",
        trigger: "manual",
      }),
    );
  });

  it("keeps the backup destination root in persisted run records", () => {
    const normalized = normalizeDatabaseBackupRun(run({ destinationDirectory: "/backups" }));

    expect(normalized?.destinationDirectory).toBe("/backups");
  });

  it("keeps legacy runs compatible and treats them as scheduled history", () => {
    const normalized = normalizeDatabaseBackupRun(run({ scheduleId: "schedule-1", source: undefined, scheduleName: "Nightly backup" }));

    expect(normalized).toEqual(expect.objectContaining({ scheduleId: "schedule-1", source: "scheduled", scheduleName: "Nightly backup" }));
  });

  it("does not include one-shot runs in schedule retention pruning", () => {
    const scheduledRuns = [run({ id: "scheduled-old", scheduleId: "schedule-1", source: "scheduled", startedAt: "2026-08-10T00:00:00.000Z" }), run({ id: "scheduled-new", scheduleId: "schedule-1", source: "scheduled", startedAt: "2026-08-11T00:00:00.000Z" })];
    const oneShotRun = run({ id: "one-shot", scheduleId: undefined, source: "one-shot", startedAt: "2026-08-12T00:00:00.000Z" });

    const normalizedRuns = [...scheduledRuns, oneShotRun].map((value) => normalizeDatabaseBackupRun(value)!).filter((value): value is DatabaseBackupRun => !!value);
    expect(databaseBackupRunsToPrune(normalizedRuns, "schedule-1", 1).map((value) => value.id)).toEqual(["scheduled-old"]);
  });
});

describe("database backup table pattern matching", () => {
  it("matches a fully-qualified db.schema.table pattern when the database and schema share the same name", () => {
    // Regression for #7314: PostgreSQL commonly has a schema with the same
    // name as its database, and the fully-qualified candidate was previously
    // suppressed whenever database === schema, silently breaking exclude
    // rules written as "db.schema.table".
    expect(databaseBackupTableMatchesPattern("vector_data", ["issue7314.issue7314.vector_data"], "issue7314", "issue7314")).toBe(true);
  });

  it("still matches a fully-qualified db.schema.table pattern when the database and schema differ", () => {
    expect(databaseBackupTableMatchesPattern("vector_data", ["mydb.myschema.vector_data"], "mydb", "myschema")).toBe(true);
  });

  it("excludes the matched table from the backup scope when database and schema share the same name", () => {
    const scope = resolveScheduledDatabaseBackupTableScope("exclude", ["issue7314.issue7314.vector_data"], ["vector_data", "keep_rows"], "issue7314", "issue7314");
    expect(scope.includedTables).toEqual(["keep_rows"]);
    expect(scope.excludedTables).toEqual(["vector_data"]);
  });
});

describe("database backup file name segment sanitization", () => {
  it("appends an underscore to Windows reserved device names", () => {
    for (const reserved of ["con", "PRN", "Aux", "nul", "com3", "LPT9"]) {
      expect(sanitizeDatabaseBackupFileSegment(reserved)).toBe(`${reserved}_`);
    }
  });

  it("keeps ordinary segment names unchanged", () => {
    expect(sanitizeDatabaseBackupFileSegment("nightly-full")).toBe("nightly-full");
    expect(sanitizeDatabaseBackupFileSegment("con_backup")).toBe("con_backup");
  });
});

describe("exact backup target persistence", () => {
  it("keeps literal identifiers and distinguishes dotted schema and table names", () => {
    const first = { database: "app", schema: "a.b", table: " odd*,name' " };
    const second = { database: "app", schema: "a", table: "b. odd*,name' " };
    expect(databaseBackupTableTargetKey(first)).not.toBe(databaseBackupTableTargetKey(second));
    expect(normalizeDatabaseBackupTableTargets([first, first, second])).toEqual([first, second]);
    const plan = normalizeDatabaseBackupSchedule({ id: "exact", connectionId: "source", destinationDirectory: "/backups", tableFilterMode: "selected", databases: ["app"], selectedTables: [first, second] })!;
    expect(plan.tableFilterMode).toBe("selected");
    expect(toDatabaseBackupExecutionConfig(plan).selectedTables).toEqual([first, second]);
  });

  it("rejects a malformed selection instead of silently dropping part of backup coverage", () => {
    const valid = { database: "app", schema: "public", table: "chosen" };
    expect(() => normalizeDatabaseBackupTableTargets([valid, { database: "app", table: "broken" }])).toThrow();
    expect(normalizeDatabaseBackupSchedule({ id: "exact", connectionId: "source", destinationDirectory: "/backups", tableFilterMode: "selected", selectedTables: [valid, { table: "broken" }] })).toBeNull();
    expect(() => resolveScheduledDatabaseBackupTableScope("selected", [], ["chosen"])).toThrow();
  });
});