REFACTORED - migrate the data layer from Prisma to Drizzle (unify the stack)

- Add lib/db (Drizzle schema: 7 tables + 6 enums + relations, postgres.js client),
  drizzle.config.ts, lib/db/enums.ts (Prisma-compatible enum objects)
- Rewrite all 14 app consumers + 4 admin components to Drizzle
- Move the test DB layer to Drizzle + in-process PGlite; convert all 8 integration
  test files + factories (371 tests green)
- Remove Prisma: deps, prisma/ schema+migrations, lib/prisma.ts, Dockerfile prisma
  generate; wire db:generate/migrate/push/studio to drizzle-kit; update Makefile
- Preserve the old seed as scripts/legacy-prisma-seed.cjs (needs a Drizzle rewrite)
This commit is contained in:
MOH
2026-08-07 14:18:41 +02:00
parent e377877e7e
commit 0a5f77d8de
48 changed files with 3765 additions and 1358 deletions
+15 -13
View File
@@ -1,11 +1,14 @@
import { eq } from "drizzle-orm";
import { describe, expect, it } from "vitest";
import { prisma } from "@/lib/prisma";
import { db } from "@/lib/db";
import { appConfig, category } from "@/lib/db/schema";
describe("integration harness smoke test", () => {
it("connects to the migrated test database and performs CRUD", async () => {
const created = await prisma.category.create({
data: {
const [created] = await db
.insert(category)
.values({
slug: "smoke",
nameAr: "a",
nameEn: "b",
@@ -13,28 +16,27 @@ describe("integration harness smoke test", () => {
descriptionAr: "a",
descriptionEn: "b",
descriptionDe: "c",
},
});
})
.returning();
expect(created.id).toBeTruthy();
expect(created.isActive).toBe(true);
const found = await prisma.category.findUnique({ where: { slug: "smoke" } });
const found = await db.query.category.findFirst({ where: eq(category.slug, "smoke") });
expect(found?.nameEn).toBe("b");
});
it("resets the database between tests", async () => {
const count = await prisma.category.count();
const count = await db.$count(category);
expect(count).toBe(0);
});
it("supports enums and appconfig upsert", async () => {
await prisma.appConfig.upsert({
where: { key: "k" },
update: { value: "v2" },
create: { key: "k", value: "v1" },
});
const row = await prisma.appConfig.findUnique({ where: { key: "k" } });
await db
.insert(appConfig)
.values({ key: "k", value: "v1" })
.onConflictDoUpdate({ target: appConfig.key, set: { value: "v2" } });
const row = await db.query.appConfig.findFirst({ where: eq(appConfig.key, "k") });
expect(row?.value).toBe("v1");
});
});
+8 -5
View File
@@ -10,8 +10,11 @@ vi.mock("@/lib/admin-auth", async () => {
return { isAdminAuthenticated: m.isAdminAuthenticated, clearAdminSessionCookie: m.clearAdminSessionCookie };
});
import { eq } from "drizzle-orm";
import { createMediaAssetAction, deleteMediaAssetAction } from "@/app/_admin/media/actions";
import { prisma } from "@/lib/prisma";
import { db } from "@/lib/db";
import { mediaAsset } from "@/lib/db/schema";
import { removeManagedMediaFile } from "@/lib/media-storage";
import { createMediaAsset, createMediaUsage } from "@/tests/helpers/factories";
import { canManageUploads } from "@/tests/helpers/fs-capability";
@@ -25,7 +28,7 @@ describe("createMediaAssetAction", () => {
it("errors when no file is provided", async () => {
const url = await captureRedirect(() => createMediaAssetAction(formDataFrom({ kind: "IMAGE", label: "L" })));
expect(url).toContain("error=");
expect(await prisma.mediaAsset.count()).toBe(0);
expect(await db.$count(mediaAsset)).toBe(0);
});
it.skipIf(!canManageUploads)("creates an asset from an uploaded file", async () => {
@@ -34,7 +37,7 @@ describe("createMediaAssetAction", () => {
createMediaAssetAction(formDataFrom({ kind: "IMAGE", label: "Pic", file })),
);
expect(url).toContain("success=");
const assets = await prisma.mediaAsset.findMany();
const assets = await db.select().from(mediaAsset);
expect(assets.length).toBe(1);
expect(assets[0].source).toBe("UPLOAD");
await removeManagedMediaFile(assets[0].url);
@@ -58,14 +61,14 @@ describe("deleteMediaAssetAction", () => {
await createMediaUsage(asset.id);
const url = await captureRedirect(() => deleteMediaAssetAction(formDataFrom({ assetId: asset.id })));
expect(url).toContain("error=");
expect(await prisma.mediaAsset.findUnique({ where: { id: asset.id } })).not.toBeNull();
expect((await db.query.mediaAsset.findFirst({ where: eq(mediaAsset.id, asset.id) })) ?? null).not.toBeNull();
});
it("deletes an unused external asset", async () => {
const asset = await createMediaAsset({ url: "https://cdn/external.png" });
const url = await captureRedirect(() => deleteMediaAssetAction(formDataFrom({ assetId: asset.id })));
expect(url).toContain("success=");
expect(await prisma.mediaAsset.findUnique({ where: { id: asset.id } })).toBeNull();
expect((await db.query.mediaAsset.findFirst({ where: eq(mediaAsset.id, asset.id) })) ?? null).toBeNull();
});
it("redirects unauthenticated callers to the admin root", async () => {
+23 -17
View File
@@ -16,7 +16,15 @@ import {
saveProjectAction,
upsertCategoryAction,
} from "@/app/_admin/portfolio/actions";
import { prisma } from "@/lib/prisma";
import { and, eq } from "drizzle-orm";
import { db } from "@/lib/db";
import {
category as categoryTable,
mediaUsage as mediaUsageTable,
portfolioAsset as portfolioAssetTable,
portfolioProject as portfolioProjectTable,
} from "@/lib/db/schema";
import { createCategory, createProject } from "@/tests/helpers/factories";
import { adminAuth, captureRedirect, formDataFrom, resetNextMocks } from "@/tests/helpers/next-mocks";
@@ -81,7 +89,7 @@ describe("upsertCategoryAction", () => {
it("creates a category", async () => {
const url = await captureRedirect(() => upsertCategoryAction(categoryForm()));
expect(url).toContain("success=");
const category = await prisma.category.findUnique({ where: { slug: "branding" } });
const category = await db.query.category.findFirst({ where: eq(categoryTable.slug, "branding") });
expect(category?.nameEn).toBe("Branding");
expect(category?.isActive).toBe(true);
});
@@ -92,7 +100,7 @@ describe("upsertCategoryAction", () => {
upsertCategoryAction(categoryForm({ id: existing.id, slug: "old", nameEn: "Renamed" })),
);
expect(url).toContain("success=");
const category = await prisma.category.findUnique({ where: { id: existing.id } });
const category = await db.query.category.findFirst({ where: eq(categoryTable.id, existing.id) });
expect(category?.nameEn).toBe("Renamed");
});
@@ -121,14 +129,14 @@ describe("deleteCategoryAction", () => {
await createProject({ categoryId: category.id });
const url = await captureRedirect(() => deleteCategoryAction(formDataFrom({ id: category.id })));
expect(url).toContain("error=");
expect(await prisma.category.findUnique({ where: { id: category.id } })).not.toBeNull();
expect((await db.query.category.findFirst({ where: eq(categoryTable.id, category.id) })) ?? null).not.toBeNull();
});
it("deletes an empty category", async () => {
const category = await createCategory();
const url = await captureRedirect(() => deleteCategoryAction(formDataFrom({ id: category.id })));
expect(url).toContain("success=");
expect(await prisma.category.findUnique({ where: { id: category.id } })).toBeNull();
expect((await db.query.category.findFirst({ where: eq(categoryTable.id, category.id) })) ?? null).toBeNull();
});
});
@@ -138,16 +146,14 @@ describe("saveProjectAction", () => {
const url = await captureRedirect(() => saveProjectAction(projectForm(category.id)));
expect(url).toContain("success=");
const project = await prisma.portfolioProject.findUnique({ where: { slug: "case-study" } });
const project = await db.query.portfolioProject.findFirst({ where: eq(portfolioProjectTable.slug, "case-study") });
expect(project).not.toBeNull();
expect(project?.isPublished).toBe(true);
expect(project?.publishedAt).not.toBeNull();
expect(project?.coverImagePath).toBe("https://cdn/cover.png");
expect(await prisma.portfolioAsset.count({ where: { projectId: project!.id } })).toBe(1);
const usages = await prisma.mediaUsage.findMany({
where: { entityType: "portfolio-project", entityId: project!.id },
});
expect(await db.$count(portfolioAssetTable, eq(portfolioAssetTable.projectId, project!.id))).toBe(1);
const usages = await db.select().from(mediaUsageTable).where(and(eq(mediaUsageTable.entityType, "portfolio-project"), eq(mediaUsageTable.entityId, project!.id)));
const usageTypes = usages.map((u) => u.usageType).sort();
expect(usageTypes).toEqual(["PORTFOLIO_ASSET", "PORTFOLIO_COVER"]);
});
@@ -156,26 +162,26 @@ describe("saveProjectAction", () => {
const category = await createCategory();
const created = await captureRedirect(() => saveProjectAction(projectForm(category.id)));
void created;
const project = await prisma.portfolioProject.findUnique({ where: { slug: "case-study" } });
const project = await db.query.portfolioProject.findFirst({ where: eq(portfolioProjectTable.slug, "case-study") });
const url = await captureRedirect(() =>
saveProjectAction(projectForm(category.id, { id: project!.id, titleEn: "Updated Title" })),
);
expect(url).toContain("success=");
const updated = await prisma.portfolioProject.findUnique({ where: { id: project!.id } });
const updated = await db.query.portfolioProject.findFirst({ where: eq(portfolioProjectTable.id, project!.id) });
expect(updated?.titleEn).toBe("Updated Title");
// assets are replaced, not duplicated
expect(await prisma.portfolioAsset.count({ where: { projectId: project!.id } })).toBe(1);
expect(await db.$count(portfolioAssetTable, eq(portfolioAssetTable.projectId, project!.id))).toBe(1);
});
it("keeps the original publishedAt when re-saving an already published project", async () => {
const category = await createCategory();
await captureRedirect(() => saveProjectAction(projectForm(category.id)));
const first = await prisma.portfolioProject.findUnique({ where: { slug: "case-study" } });
const first = await db.query.portfolioProject.findFirst({ where: eq(portfolioProjectTable.slug, "case-study") });
const originalPublishedAt = first!.publishedAt;
await captureRedirect(() => saveProjectAction(projectForm(category.id, { id: first!.id })));
const second = await prisma.portfolioProject.findUnique({ where: { id: first!.id } });
const second = await db.query.portfolioProject.findFirst({ where: eq(portfolioProjectTable.id, first!.id) });
expect(second?.publishedAt?.toISOString()).toBe(originalPublishedAt?.toISOString());
});
@@ -183,7 +189,7 @@ describe("saveProjectAction", () => {
const category = await createCategory();
const url = await captureRedirect(() => saveProjectAction(projectForm(category.id, { titleEn: "" })));
expect(url).toContain("error=");
expect(await prisma.portfolioProject.count()).toBe(0);
expect(await db.$count(portfolioProjectTable)).toBe(0);
});
it("reports a unique-constraint violation on duplicate slugs", async () => {
@@ -206,7 +212,7 @@ describe("deleteProjectAction", () => {
const project = await createProject();
const url = await captureRedirect(() => deleteProjectAction(formDataFrom({ id: project.id })));
expect(url).toContain("success=");
expect(await prisma.portfolioProject.findUnique({ where: { id: project.id } })).toBeNull();
expect((await db.query.portfolioProject.findFirst({ where: eq(portfolioProjectTable.id, project.id) })) ?? null).toBeNull();
});
it("errors when the project does not exist", async () => {
+2 -2
View File
@@ -3,7 +3,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { GET as healthGet } from "@/app/api/health/route";
import { GET as defaultLocaleGet } from "@/app/api/site/default-locale/route";
import { setMaintenanceMode, updateSiteSettings, getSiteSettings } from "@/lib/app-config";
import { prisma } from "@/lib/prisma";
import { db } from "@/lib/db";
afterEach(() => {
vi.restoreAllMocks();
@@ -20,7 +20,7 @@ describe("GET /api/health", () => {
});
it("reports degraded (503) when the database query throws", async () => {
vi.spyOn(prisma, "$queryRaw").mockRejectedValueOnce(new Error("db down"));
vi.spyOn(db, "execute").mockRejectedValueOnce(new Error("db down"));
const response = await healthGet();
expect(response.status).toBe(503);
const body = await response.json();
+10 -11
View File
@@ -20,7 +20,10 @@ import {
updateMarqueeSettings,
updateSiteSettings,
} from "@/lib/app-config";
import { prisma } from "@/lib/prisma";
import { eq } from "drizzle-orm";
import { db } from "@/lib/db";
import { appConfig, mediaUsage } from "@/lib/db/schema";
import { createMediaAsset } from "@/tests/helpers/factories";
describe("maintenance mode", () => {
@@ -31,7 +34,7 @@ describe("maintenance mode", () => {
it("persists and reads back the enabled flag", async () => {
await setMaintenanceMode(true);
expect(await getMaintenanceMode()).toBe(true);
const row = await prisma.appConfig.findUnique({ where: { key: MAINTENANCE_MODE_KEY } });
const row = await db.query.appConfig.findFirst({ where: eq(appConfig.key, MAINTENANCE_MODE_KEY) });
expect(row?.value).toBe("true");
await setMaintenanceMode(false);
expect(await getMaintenanceMode()).toBe(false);
@@ -46,7 +49,7 @@ describe("site settings", () => {
});
it("uses the stored siteName key as the fallback name", async () => {
await prisma.appConfig.create({ data: { key: SITE_NAME_KEY, value: "My Studio" } });
await db.insert(appConfig).values({ key: SITE_NAME_KEY, value: "My Studio" });
const settings = await getSiteSettings();
expect(settings.locales.ar.siteName).toBe("My Studio");
});
@@ -113,24 +116,20 @@ describe("getSiteSettingsMediaBindings", () => {
it("maps media usages to their field bindings", async () => {
const logo = await createMediaAsset({ url: "https://cdn/logo.png" });
const favicon = await createMediaAsset({ url: "https://cdn/favicon.svg" });
await prisma.mediaUsage.create({
data: {
await db.insert(mediaUsage).values({
assetId: logo.id,
usageType: "GENERIC",
entityType: SITE_SETTINGS_ENTITY_TYPE,
entityId: SITE_SETTINGS_ENTITY_ID,
fieldKey: SITE_SETTINGS_LOGO_LIGHT_FIELD_KEY,
},
});
await prisma.mediaUsage.create({
data: {
});
await db.insert(mediaUsage).values({
assetId: favicon.id,
usageType: "GENERIC",
entityType: SITE_SETTINGS_ENTITY_TYPE,
entityId: SITE_SETTINGS_ENTITY_ID,
fieldKey: SITE_SETTINGS_FAVICON_FIELD_KEY,
},
});
});
const bindings = await getSiteSettingsMediaBindings();
expect(bindings.siteLogoLight?.assetId).toBe(logo.id);
+6 -3
View File
@@ -2,9 +2,12 @@ import { readFile } from "fs/promises";
import { describe, expect, it } from "vitest";
import { eq } from "drizzle-orm";
import { resolveMediaSelection } from "@/lib/media-service";
import { resolveMediaUploadPath } from "@/lib/media-storage";
import { prisma } from "@/lib/prisma";
import { db } from "@/lib/db";
import { mediaAsset } from "@/lib/db/schema";
import { createMediaAsset } from "@/tests/helpers/factories";
import { canManageUploads } from "@/tests/helpers/fs-capability";
@@ -47,7 +50,7 @@ describe("resolveMediaSelection — external mode", () => {
expect(result.createdAssetId).toBeTruthy();
expect(result.url).toBe("https://cdn/new/photo.png");
const stored = await prisma.mediaAsset.findUnique({ where: { id: result.assetId! } });
const stored = await db.query.mediaAsset.findFirst({ where: eq(mediaAsset.id, result.assetId!) });
expect(stored?.source).toBe("EXTERNAL");
expect(stored?.fileName).toBe("photo.png");
expect(stored?.label).toBe("Photo");
@@ -108,7 +111,7 @@ describe("resolveMediaSelection — upload mode (filesystem)", () => {
required: true,
});
expect(result.uploadedUrl).toBeTruthy();
const stored = await prisma.mediaAsset.findUnique({ where: { id: result.assetId! } });
const stored = await db.query.mediaAsset.findFirst({ where: eq(mediaAsset.id, result.assetId!) });
expect(stored?.source).toBe("UPLOAD");
// File actually written to disk
const bytes = await readFile(resolveMediaUploadPath(result.url));
+5 -8
View File
@@ -10,7 +10,8 @@ import {
getPortfolioMediaBindings,
replaceEntityMediaUsages,
} from "@/lib/media";
import { prisma } from "@/lib/prisma";
import { db } from "@/lib/db";
import { mediaUsage } from "@/lib/db/schema";
import { createMediaAsset as seedAsset } from "@/tests/helpers/factories";
describe("createMediaAsset / getMediaAssetById", () => {
@@ -110,13 +111,11 @@ describe("getPortfolioMediaBindings", () => {
const section = await seedAsset();
const asset = await seedAsset();
await prisma.mediaUsage.createMany({
data: [
await db.insert(mediaUsage).values([
{ assetId: cover.id, usageType: "PORTFOLIO_COVER", entityType: "portfolio-project", entityId: "proj", fieldKey: "cover" },
{ assetId: section.id, usageType: "PORTFOLIO_SECTION", entityType: "portfolio-project", entityId: "proj", fieldKey: "sec_1" },
{ assetId: asset.id, usageType: "PORTFOLIO_ASSET", entityType: "portfolio-project", entityId: "proj", fieldKey: "ast_1" },
],
});
]);
const bindings = await getPortfolioMediaBindings("proj");
expect(bindings.coverAssetId).toBe(cover.id);
@@ -131,7 +130,5 @@ describe("getPortfolioMediaBindings", () => {
});
async function createMediaUsageFor(assetId: string) {
await prisma.mediaUsage.create({
data: { assetId, usageType: "GENERIC", entityType: "e", entityId: "1", fieldKey: "f" },
});
await db.insert(mediaUsage).values({ assetId, usageType: "GENERIC", entityType: "e", entityId: "1", fieldKey: "f" });
}
+10 -9
View File
@@ -9,7 +9,10 @@ import {
getPublishedPortfolioProjectBySlug,
getPublishedPortfolioProjects,
} from "@/lib/portfolio";
import { prisma } from "@/lib/prisma";
import { eq } from "drizzle-orm";
import { db } from "@/lib/db";
import { category, mediaUsage, portfolioAsset, portfolioProject, portfolioSection } from "@/lib/db/schema";
import {
createAsset,
createCategory,
@@ -75,15 +78,13 @@ describe("admin projects", () => {
it("attaches media bindings to a project fetched by id", async () => {
const project = await createProject();
const cover = await createMediaAsset();
await prisma.mediaUsage.create({
data: {
await db.insert(mediaUsage).values({
assetId: cover.id,
usageType: "PORTFOLIO_COVER",
entityType: "portfolio-project",
entityId: project.id,
fieldKey: "cover",
},
});
});
const detail = await getAdminPortfolioProjectById(project.id);
expect(detail?.coverMediaAssetId).toBe(cover.id);
});
@@ -127,15 +128,15 @@ describe("referential integrity", () => {
it("restricts deleting a category that still has projects", async () => {
const cat = await createCategory();
await createProject({ categoryId: cat.id });
await expect(prisma.category.delete({ where: { id: cat.id } })).rejects.toThrow();
await expect(db.delete(category).where(eq(category.id, cat.id))).rejects.toThrow();
});
it("cascades section and asset deletion when a project is removed", async () => {
const project = await createProject();
await createSection(project.id);
await createAsset(project.id);
await prisma.portfolioProject.delete({ where: { id: project.id } });
expect(await prisma.portfolioSection.count()).toBe(0);
expect(await prisma.portfolioAsset.count()).toBe(0);
await db.delete(portfolioProject).where(eq(portfolioProject.id, project.id));
expect(await db.$count(portfolioSection)).toBe(0);
expect(await db.$count(portfolioAsset)).toBe(0);
});
});