239 lines
8.6 KiB
TypeScript
239 lines
8.6 KiB
TypeScript
import { describe, expect, it } from "vitest";
|
|
import {
|
|
assertClientCoversTenantScopedModels,
|
|
createPrismaRestoreRunner,
|
|
createPrismaSnapshotRunner,
|
|
prismaModelAccessor,
|
|
type PrismaLikeClient,
|
|
} from "./prisma-runner.js";
|
|
import { TENANT_SCOPED_MODELS } from "./models.js";
|
|
import type { ModelScalarTypeMap } from "./json-codec.js";
|
|
|
|
describe("prismaModelAccessor", () => {
|
|
it("lowercases the first character", () => {
|
|
expect(prismaModelAccessor("TenantUser")).toBe("tenantUser");
|
|
expect(prismaModelAccessor("Row")).toBe("row");
|
|
expect(prismaModelAccessor("TenantSettingsRow")).toBe("tenantSettingsRow");
|
|
});
|
|
});
|
|
|
|
describe("createPrismaSnapshotRunner", () => {
|
|
it("paginates by id cursor and yields every row exactly once", async () => {
|
|
const rows = Array.from({ length: 5 }, (_, i) => ({ id: `r${i + 1}`, tenantId: "t1", v: i }));
|
|
const calls: Array<Record<string, unknown>> = [];
|
|
const client: PrismaLikeClient = {
|
|
tenantUser: {
|
|
findMany: async (args: Record<string, unknown>) => {
|
|
calls.push(args);
|
|
const take = args.take as number;
|
|
const skip = (args.skip as number | undefined) ?? 0;
|
|
const cursor = args.cursor as { id?: string } | undefined;
|
|
let startIdx = 0;
|
|
if (cursor?.id) {
|
|
startIdx = rows.findIndex((r) => r.id === cursor.id) + skip;
|
|
}
|
|
return rows.slice(startIdx, startIdx + take);
|
|
},
|
|
},
|
|
};
|
|
const runner = createPrismaSnapshotRunner(client);
|
|
const out: Array<Record<string, unknown>> = [];
|
|
for await (const r of runner.findManyByTenant("TenantUser", "tenantId", "t1", 2)) {
|
|
out.push(r);
|
|
}
|
|
expect(out.map((r) => r.id)).toEqual(["r1", "r2", "r3", "r4", "r5"]);
|
|
// First page: no cursor; subsequent pages must include cursor + skip=1.
|
|
expect(calls[0]?.cursor).toBeUndefined();
|
|
expect(calls[1]?.cursor).toEqual({ id: "r2" });
|
|
expect(calls[1]?.skip).toBe(1);
|
|
});
|
|
|
|
it("uses tenantId as the cursor for TenantSettingsRow", async () => {
|
|
const calls: Array<Record<string, unknown>> = [];
|
|
const client: PrismaLikeClient = {
|
|
tenantSettingsRow: {
|
|
findMany: async (args: Record<string, unknown>) => {
|
|
calls.push(args);
|
|
if ((args.cursor as { tenantId?: string } | undefined)?.tenantId === "t1") return [];
|
|
return [{ tenantId: "t1", foo: "bar" }];
|
|
},
|
|
},
|
|
};
|
|
const runner = createPrismaSnapshotRunner(client);
|
|
const out: Array<Record<string, unknown>> = [];
|
|
for await (const r of runner.findManyByTenant("TenantSettingsRow", "tenantId", "t1", 100)) {
|
|
out.push(r);
|
|
}
|
|
expect(out).toEqual([{ tenantId: "t1", foo: "bar" }]);
|
|
expect(calls[0]?.orderBy).toEqual({ tenantId: "asc" });
|
|
});
|
|
|
|
it("throws when the client has no delegate for the model", async () => {
|
|
const client: PrismaLikeClient = {};
|
|
const runner = createPrismaSnapshotRunner(client);
|
|
const iter = runner.findManyByTenant("TenantUser", "tenantId", "t1", 100);
|
|
await expect((async () => {
|
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
for await (const _ of iter) {
|
|
/* unreachable */
|
|
}
|
|
})()).rejects.toThrow(/no delegate for model "TenantUser"/u);
|
|
});
|
|
});
|
|
|
|
describe("createPrismaRestoreRunner", () => {
|
|
it("calls createMany with skipDuplicates and returns the written count", async () => {
|
|
let received: Record<string, unknown> | undefined;
|
|
const client: PrismaLikeClient = {
|
|
tenantUser: {
|
|
createMany: async (args: Record<string, unknown>) => {
|
|
received = args;
|
|
return { count: (args.data as unknown[]).length };
|
|
},
|
|
},
|
|
};
|
|
const types = new Map<string, ModelScalarTypeMap>();
|
|
const runner = createPrismaRestoreRunner(client, types);
|
|
const result = await runner.createMany("TenantUser", [
|
|
{ id: "tu1", tenantId: "t2", userId: "u1" },
|
|
{ id: "tu2", tenantId: "t2", userId: "u2" },
|
|
]);
|
|
expect(result.written).toBe(2);
|
|
expect(received?.skipDuplicates).toBe(true);
|
|
expect((received?.data as unknown[]).length).toBe(2);
|
|
});
|
|
|
|
it("decodes coded scalar fields before passing rows to Prisma", async () => {
|
|
let received: Array<Record<string, unknown>> | undefined;
|
|
const client: PrismaLikeClient = {
|
|
collabDoc: {
|
|
createMany: async (args: Record<string, unknown>) => {
|
|
received = args.data as Array<Record<string, unknown>>;
|
|
return { count: received.length };
|
|
},
|
|
},
|
|
};
|
|
const types = new Map<string, ModelScalarTypeMap>([
|
|
[
|
|
"CollabDoc",
|
|
{
|
|
modelName: "CollabDoc",
|
|
fields: new Map([
|
|
["createdAt", "DateTime"],
|
|
["ydocState", "Bytes"],
|
|
]),
|
|
},
|
|
],
|
|
]);
|
|
const runner = createPrismaRestoreRunner(client, types);
|
|
const base64 = Buffer.from("hi").toString("base64");
|
|
await runner.createMany("CollabDoc", [
|
|
{ id: "c1", tenantId: "t1", createdAt: "2026-05-24T12:00:00.000Z", ydocState: base64 },
|
|
]);
|
|
const row = received![0]!;
|
|
expect(row.createdAt).toBeInstanceOf(Date);
|
|
expect(Buffer.isBuffer(row.ydocState)).toBe(true);
|
|
expect((row.ydocState as Buffer).toString()).toBe("hi");
|
|
});
|
|
|
|
it("findManyByIds delegates to findMany with where.id.in", async () => {
|
|
let received: Record<string, unknown> | undefined;
|
|
const client: PrismaLikeClient = {
|
|
user: {
|
|
findMany: async (args: Record<string, unknown>) => {
|
|
received = args;
|
|
return [{ id: "u1" }, { id: "u2" }];
|
|
},
|
|
},
|
|
};
|
|
const runner = createPrismaSnapshotRunner(client);
|
|
const rows = await runner.findManyByIds!("User", ["u1", "u2"]);
|
|
expect(rows).toHaveLength(2);
|
|
expect(received).toEqual({ where: { id: { in: ["u1", "u2"] } } });
|
|
});
|
|
|
|
it("findManyByIds returns [] without calling Prisma for an empty id list", async () => {
|
|
let invoked = false;
|
|
const client: PrismaLikeClient = {
|
|
user: {
|
|
findMany: async () => {
|
|
invoked = true;
|
|
return [];
|
|
},
|
|
},
|
|
};
|
|
const runner = createPrismaSnapshotRunner(client);
|
|
const rows = await runner.findManyByIds!("User", []);
|
|
expect(rows).toEqual([]);
|
|
expect(invoked).toBe(false);
|
|
});
|
|
|
|
it("upsertManyById creates fresh rows and reports updated=N for pre-existing ids", async () => {
|
|
const existing = new Set(["u_exists"]);
|
|
const createdRows: Array<Record<string, unknown>> = [];
|
|
const client: PrismaLikeClient = {
|
|
user: {
|
|
findUnique: async (args: { where: { id: string } }) => {
|
|
return existing.has(args.where.id) ? { id: args.where.id } : null;
|
|
},
|
|
create: async (args: { data: Record<string, unknown> }) => {
|
|
createdRows.push(args.data);
|
|
return args.data;
|
|
},
|
|
},
|
|
};
|
|
const runner = createPrismaRestoreRunner(client, new Map());
|
|
const result = await runner.upsertManyById!("User", [
|
|
{ id: "u_exists", email: "old@x" },
|
|
{ id: "u_new", email: "new@x" },
|
|
]);
|
|
expect(result).toEqual({ created: 1, updated: 1 });
|
|
expect(createdRows).toHaveLength(1);
|
|
expect(createdRows[0]?.id).toBe("u_new");
|
|
});
|
|
|
|
it("upsertManyById throws when a row has no string id", async () => {
|
|
const client: PrismaLikeClient = {
|
|
user: {
|
|
findUnique: async () => null,
|
|
create: async (args: { data: Record<string, unknown> }) => args.data,
|
|
},
|
|
};
|
|
const runner = createPrismaRestoreRunner(client, new Map());
|
|
await expect(runner.upsertManyById!("User", [{ email: "x@y" }])).rejects.toThrow(
|
|
/has no string id/u,
|
|
);
|
|
});
|
|
|
|
it("returns { written: 0 } for an empty row list without calling Prisma", async () => {
|
|
let invoked = false;
|
|
const client: PrismaLikeClient = {
|
|
tenantUser: {
|
|
createMany: async () => {
|
|
invoked = true;
|
|
return { count: 99 };
|
|
},
|
|
},
|
|
};
|
|
const runner = createPrismaRestoreRunner(client, new Map());
|
|
const result = await runner.createMany("TenantUser", []);
|
|
expect(result.written).toBe(0);
|
|
expect(invoked).toBe(false);
|
|
});
|
|
});
|
|
|
|
describe("assertClientCoversTenantScopedModels", () => {
|
|
it("passes for a client exposing every accessor", () => {
|
|
const client: PrismaLikeClient = {};
|
|
for (const { model } of TENANT_SCOPED_MODELS) {
|
|
client[prismaModelAccessor(model)] = { findMany: () => Promise.resolve([]) };
|
|
}
|
|
expect(() => assertClientCoversTenantScopedModels(client)).not.toThrow();
|
|
});
|
|
|
|
it("throws listing the missing models when accessors are absent", () => {
|
|
const client: PrismaLikeClient = {};
|
|
expect(() => assertClientCoversTenantScopedModels(client)).toThrow(/missing accessors/u);
|
|
});
|
|
});
|