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.8 KB
Raw Blame
import { readFileSync } from "node:fs";
import path from "node:path";
import { describe, expect, it } from "vitest";
import type { SchemaSnapshot } from "../types";

const fixturePath = path.resolve(__dirname, "../fixtures/keycloak.snapshot.json");

function loadFixture(): SchemaSnapshot {
  return JSON.parse(readFileSync(fixturePath, "utf8")) as SchemaSnapshot;
}

describe("fixture conformance", () => {
  // This fixture is generated by the REAL Rust serializer. Its job is to fail
  // when the Rust model changes shape, so the hand-maintained types.ts cannot
  // drift silently.

  it("has the shape types.ts declares", () => {
    const snapshot = loadFixture();
    expect(snapshot.formatVersion).toBe(1);
    expect(Array.isArray(snapshot.tables)).toBe(true);
    expect(snapshot.tables.length).toBeGreaterThan(0);
    expect(typeof snapshot.project.databaseType).toBe("string");
    expect(Array.isArray(snapshot.project.schemas)).toBe(true);
  });

  it("uses camelCase for snapshot-owned fields", () => {
    const raw = JSON.parse(readFileSync(fixturePath, "utf8")) as Record<string, unknown>;
    expect(raw).toHaveProperty("formatVersion");
    expect(raw).not.toHaveProperty("format_version");

    const table = (raw.tables as Record<string, unknown>[])[0];
    expect(table).toHaveProperty("noteSource");
    expect(table).toHaveProperty("columnNotes");
    expect(table).toHaveProperty("foreignKeys");
    expect(table).not.toHaveProperty("note_source");
  });

  it("keeps snake_case on columns, which come from crate::types", () => {
    const snapshot = loadFixture();
    const withColumns = snapshot.tables.find((table) => table.columns.length > 0);
    expect(withColumns, "fixture must contain at least one table with columns").toBeDefined();
    const column = withColumns!.columns[0] as unknown as Record<string, unknown>;
    expect(column).toHaveProperty("data_type");
    expect(column).toHaveProperty("is_nullable");
    expect(column).not.toHaveProperty("dataType");
  });

  it("carries an annotated note, a group and an orphan warning", () => {
    const snapshot = loadFixture();

    const annotated = snapshot.tables.find((table) => table.noteSource === "LOCAL");
    expect(annotated, "fixture must include a LOCAL-sourced note").toBeDefined();
    expect(annotated!.note).toBeTruthy();

    expect(snapshot.groups.length).toBeGreaterThan(0);
    expect(typeof snapshot.groups[0].hue).toBe("number");

    const orphan = snapshot.warnings.find((warning) => warning.kind === "orphanedNotes");
    expect(orphan, "fixture must include an orphanedNotes warning").toBeDefined();
  });

  it("every warning discriminant is one types.ts knows", () => {
    const known = new Set(["tableSkipped", "noForeignKeyMetadata", "commentsUnsupported", "orphanedNotes", "dbmlOmitted"]);
    for (const warning of loadFixture().warnings) {
      expect(known.has(warning.kind), `unknown warning kind: ${warning.kind}`).toBe(true);
    }
  });

  // Every struct below is pinned in BOTH directions — no missing key, no
  // unexpected key — because each direction catches a different drift. A
  // missing key is a removal or a rename's old name; an unexpected key is the
  // rename's new name. Pinning only "required keys present" lets a rename of
  // Relationship::to slip through the whole suite AND vue-tsc while
  // RelationshipList reads `field.table` on undefined and every table page
  // renders blank.
  //
  // `Object.hasOwn`, never truthiness: most of these keys are legitimately
  // null, and "present and null" must stay distinguishable from "absent",
  // which is what skip_serializing_if produces.
  function pinShape(label: string, instances: unknown[], required: string[], optional: string[] = []): void {
    // An empty instance list runs zero assertions and passes while proving
    // nothing, so every struct has to actually appear in the fixture.
    expect(instances.length, `fixture must contain at least one ${label}`).toBeGreaterThan(0);
    const allowed = new Set([...required, ...optional]);
    for (const [position, instance] of instances.entries()) {
      const record = instance as Record<string, unknown>;
      for (const key of required) {
        expect(Object.hasOwn(record, key), `${label}[${position}] must always carry ${key}`).toBe(true);
      }
      for (const key of Object.keys(record)) {
        expect(allowed.has(key), `${label}[${position}] carries unexpected key ${key}`).toBe(true);
      }
    }
  }

  it("the snapshot root has exactly the keys types.ts declares", () => {
    pinShape("SchemaSnapshot", [loadFixture()], ["formatVersion", "project", "tables", "relationships", "groups", "enums", "warnings"]);
  });

  it("ProjectMeta has exactly the keys types.ts declares", () => {
    pinShape("ProjectMeta", [loadFixture().project], ["name", "databaseType", "database", "schemas", "generatedAt", "note"]);
  });

  it("DocTable has exactly the keys types.ts declares", () => {
    pinShape("DocTable", loadFixture().tables, ["schema", "name", "kind", "columns", "indexes", "foreignKeys", "groupId", "note", "noteSource", "shadowedNote", "columnNotes", "estimatedRows", "viewDefinition"]);
  });

  it("ColumnInfo has exactly the keys types.ts declares", () => {
    // The required ten are required because Rust has no skip_serializing_if on
    // them. The optional three DO carry one, so the key is absent rather than
    // null when there is no value.
    const columns = loadFixture().tables.flatMap((table) => table.columns);
    pinShape("ColumnInfo", columns, ["name", "data_type", "is_nullable", "column_default", "is_primary_key", "extra", "comment", "numeric_precision", "numeric_scale", "character_maximum_length"], ["enum_values", "character_set", "collation"]);
  });

  it("IndexInfo has exactly the keys types.ts declares", () => {
    const indexes = loadFixture().tables.flatMap((table) => table.indexes);
    pinShape("IndexInfo", indexes, ["name", "columns", "is_unique", "is_primary", "filter", "index_type", "included_columns", "comment"]);
  });

  it("ForeignKeyInfo has exactly the keys types.ts declares", () => {
    const foreignKeys = loadFixture().tables.flatMap((table) => table.foreignKeys);
    pinShape("ForeignKeyInfo", foreignKeys, ["name", "column", "ref_table", "ref_column"], ["ref_schema", "on_update", "on_delete"]);
  });

  it("ColumnNote has exactly the keys types.ts declares", () => {
    const notes = loadFixture().tables.flatMap((table) => Object.values(table.columnNotes));
    pinShape("ColumnNote", notes, ["note", "source", "shadowed"]);
  });

  it("Relationship and FieldRef have exactly the keys types.ts declares", () => {
    const relationships = loadFixture().relationships;
    pinShape("Relationship", relationships, ["id", "name", "from", "to", "cardinality", "onUpdate", "onDelete"]);
    pinShape(
      "FieldRef",
      relationships.flatMap((relationship) => [relationship.from, relationship.to]),
      ["schema", "table", "column"],
    );
  });

  it("TableGroup has exactly the keys types.ts declares", () => {
    pinShape("TableGroup", loadFixture().groups, ["id", "name", "hue", "note"]);
  });

  it("records that the fixture source declares no enum types, leaving DocEnum unpinned", () => {
    // Keycloak's schema has no PostgreSQL enum types, so this fixture cannot
    // exercise DocEnum. That is a real gap: a Rust-side rename of a DocEnum
    // field would pass every test in this file and break the viewer's enum
    // rendering silently.
    //
    // Asserting the gap rather than deleting the test keeps it visible and
    // makes it self-correcting — the day the fixture source gains an enum this
    // fails, and the pin below should replace it:
    //
    //   pinShape("DocEnum", loadFixture().enums, ["schema", "name", "values", "note", "synthesized"]);
    expect(loadFixture().enums, "fixture gained enums — restore the DocEnum pinShape here").toEqual([]);
  });
});