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:
+58
-37
@@ -1,6 +1,13 @@
|
||||
import { MediaKind, MediaSource, MediaUsageType, PortfolioSectionType } from "@prisma/client";
|
||||
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { db } from "@/lib/db";
|
||||
import {
|
||||
category,
|
||||
mediaAsset,
|
||||
mediaUsage,
|
||||
portfolioAsset,
|
||||
portfolioProject,
|
||||
portfolioSection,
|
||||
} from "@/lib/db/schema";
|
||||
import { MediaKind, MediaSource, MediaUsageType, PortfolioSectionType } from "@/lib/db/enums";
|
||||
|
||||
let counter = 0;
|
||||
function uniq(prefix: string) {
|
||||
@@ -8,11 +15,11 @@ function uniq(prefix: string) {
|
||||
return `${prefix}-${counter}`;
|
||||
}
|
||||
|
||||
export function createCategory(overrides: Record<string, unknown> = {}) {
|
||||
const slug = (overrides.slug as string) ?? uniq("cat");
|
||||
return prisma.category.create({
|
||||
data: {
|
||||
slug,
|
||||
export async function createCategory(overrides: Record<string, unknown> = {}) {
|
||||
const [row] = await db
|
||||
.insert(category)
|
||||
.values({
|
||||
slug: (overrides.slug as string) ?? uniq("cat"),
|
||||
nameAr: "الاسم",
|
||||
nameEn: "Name",
|
||||
nameDe: "Name",
|
||||
@@ -22,16 +29,19 @@ export function createCategory(overrides: Record<string, unknown> = {}) {
|
||||
sortOrder: 0,
|
||||
isActive: true,
|
||||
...overrides,
|
||||
},
|
||||
});
|
||||
} as typeof category.$inferInsert)
|
||||
.returning();
|
||||
|
||||
return row;
|
||||
}
|
||||
|
||||
export async function createProject(overrides: Record<string, unknown> = {}) {
|
||||
const categoryId = (overrides.categoryId as string) ?? (await createCategory()).id;
|
||||
const isPublished = (overrides.isPublished as boolean) ?? true;
|
||||
const slug = (overrides.slug as string) ?? uniq("proj");
|
||||
return prisma.portfolioProject.create({
|
||||
data: {
|
||||
const [row] = await db
|
||||
.insert(portfolioProject)
|
||||
.values({
|
||||
categoryId,
|
||||
slug,
|
||||
viewMode: "GRID",
|
||||
@@ -51,13 +61,16 @@ export async function createProject(overrides: Record<string, unknown> = {}) {
|
||||
...overrides,
|
||||
isPublished,
|
||||
publishedAt: isPublished ? new Date() : null,
|
||||
},
|
||||
});
|
||||
} as typeof portfolioProject.$inferInsert)
|
||||
.returning();
|
||||
|
||||
return row;
|
||||
}
|
||||
|
||||
export function createSection(projectId: string, overrides: Record<string, unknown> = {}) {
|
||||
return prisma.portfolioSection.create({
|
||||
data: {
|
||||
export async function createSection(projectId: string, overrides: Record<string, unknown> = {}) {
|
||||
const [row] = await db
|
||||
.insert(portfolioSection)
|
||||
.values({
|
||||
projectId,
|
||||
type: PortfolioSectionType.RICH_TEXT,
|
||||
titleAr: "ع",
|
||||
@@ -68,13 +81,16 @@ export function createSection(projectId: string, overrides: Record<string, unkno
|
||||
bodyDe: "b",
|
||||
sortOrder: 0,
|
||||
...overrides,
|
||||
},
|
||||
});
|
||||
} as typeof portfolioSection.$inferInsert)
|
||||
.returning();
|
||||
|
||||
return row;
|
||||
}
|
||||
|
||||
export function createAsset(projectId: string, overrides: Record<string, unknown> = {}) {
|
||||
return prisma.portfolioAsset.create({
|
||||
data: {
|
||||
export async function createAsset(projectId: string, overrides: Record<string, unknown> = {}) {
|
||||
const [row] = await db
|
||||
.insert(portfolioAsset)
|
||||
.values({
|
||||
projectId,
|
||||
kind: "IMAGE",
|
||||
filePath: "/uploads/media/assets/x.svg",
|
||||
@@ -83,35 +99,40 @@ export function createAsset(projectId: string, overrides: Record<string, unknown
|
||||
altDe: "a",
|
||||
sortOrder: 0,
|
||||
...overrides,
|
||||
},
|
||||
});
|
||||
} as typeof portfolioAsset.$inferInsert)
|
||||
.returning();
|
||||
|
||||
return row;
|
||||
}
|
||||
|
||||
export function createMediaAsset(overrides: Record<string, unknown> = {}) {
|
||||
return prisma.mediaAsset.create({
|
||||
data: {
|
||||
export async function createMediaAsset(overrides: Record<string, unknown> = {}) {
|
||||
const [row] = await db
|
||||
.insert(mediaAsset)
|
||||
.values({
|
||||
source: MediaSource.EXTERNAL,
|
||||
kind: MediaKind.IMAGE,
|
||||
url: (overrides.url as string) ?? `https://cdn.example.com/${uniq("img")}.png`,
|
||||
fileName: "img.png",
|
||||
label: "Image",
|
||||
...overrides,
|
||||
},
|
||||
});
|
||||
} as typeof mediaAsset.$inferInsert)
|
||||
.returning();
|
||||
|
||||
return row;
|
||||
}
|
||||
|
||||
export function createMediaUsage(
|
||||
assetId: string,
|
||||
overrides: Record<string, unknown> = {},
|
||||
) {
|
||||
return prisma.mediaUsage.create({
|
||||
data: {
|
||||
export async function createMediaUsage(assetId: string, overrides: Record<string, unknown> = {}) {
|
||||
const [row] = await db
|
||||
.insert(mediaUsage)
|
||||
.values({
|
||||
assetId,
|
||||
usageType: MediaUsageType.GENERIC,
|
||||
entityType: "test-entity",
|
||||
entityId: "e1",
|
||||
fieldKey: uniq("field"),
|
||||
...overrides,
|
||||
},
|
||||
});
|
||||
} as typeof mediaUsage.$inferInsert)
|
||||
.returning();
|
||||
|
||||
return row;
|
||||
}
|
||||
|
||||
@@ -5,12 +5,12 @@ import path from "path";
|
||||
* Global integration setup.
|
||||
*
|
||||
* Only needed when running against a real Postgres via TEST_DATABASE_URL: reset the
|
||||
* schema and apply every migration once before the workers start. When
|
||||
* TEST_DATABASE_URL is not set, each worker spins up its own in-process PGlite database
|
||||
* (see tests/helpers/integration-setup.ts) and this is a no-op.
|
||||
* schema and apply every Drizzle migration once before the workers start. When
|
||||
* TEST_DATABASE_URL is not set, each worker spins up its own in-process PGlite
|
||||
* database (see tests/helpers/integration-setup.ts) and this is a no-op.
|
||||
*/
|
||||
|
||||
const MIGRATIONS_DIR = path.resolve(process.cwd(), "prisma", "migrations");
|
||||
const MIGRATIONS_DIR = path.resolve(process.cwd(), "lib", "db", "migrations");
|
||||
|
||||
export default async function setup() {
|
||||
const connectionString = process.env.TEST_DATABASE_URL?.trim();
|
||||
@@ -23,11 +23,11 @@ export default async function setup() {
|
||||
await client.connect();
|
||||
try {
|
||||
await client.query("DROP SCHEMA IF EXISTS public CASCADE; CREATE SCHEMA public;");
|
||||
const dirs = readdirSync(MIGRATIONS_DIR)
|
||||
.filter((entry) => /^\d/.test(entry))
|
||||
const files = readdirSync(MIGRATIONS_DIR)
|
||||
.filter((entry) => entry.endsWith(".sql"))
|
||||
.sort();
|
||||
for (const dir of dirs) {
|
||||
await client.query(readFileSync(path.join(MIGRATIONS_DIR, dir, "migration.sql"), "utf8"));
|
||||
for (const file of files) {
|
||||
await client.query(readFileSync(path.join(MIGRATIONS_DIR, file), "utf8"));
|
||||
}
|
||||
} finally {
|
||||
await client.end();
|
||||
|
||||
@@ -1,16 +1,19 @@
|
||||
import { readFileSync, readdirSync } from "fs";
|
||||
import path from "path";
|
||||
|
||||
import { sql } from "drizzle-orm";
|
||||
import { afterAll, beforeEach, vi } from "vitest";
|
||||
|
||||
import * as schema from "@/lib/db/schema";
|
||||
|
||||
/**
|
||||
* Integration database wiring.
|
||||
* Integration database wiring (Drizzle).
|
||||
*
|
||||
* - If TEST_DATABASE_URL is set, the real `lib/prisma` singleton is used unchanged,
|
||||
* pointed at that Postgres (e.g. the Docker instance). Migrations are applied once
|
||||
* by the global setup; files run serially and truncate between tests.
|
||||
* - If TEST_DATABASE_URL is set, the real `@/lib/db` singleton is used unchanged,
|
||||
* pointed at that Postgres. Migrations are applied once by the global setup;
|
||||
* files run serially and truncate between tests.
|
||||
*
|
||||
* - Otherwise, `lib/prisma` is mocked with a Prisma client backed by an in-process
|
||||
* - Otherwise, `@/lib/db` is mocked with a Drizzle client backed by an in-process
|
||||
* PGlite database (Postgres compiled to WASM) — real Postgres semantics, fully
|
||||
* isolated per worker, no external server. Production code is never modified.
|
||||
*/
|
||||
@@ -20,44 +23,45 @@ if (realDbUrl) {
|
||||
process.env.DATABASE_URL = realDbUrl;
|
||||
}
|
||||
|
||||
vi.mock("@/lib/prisma", async () => {
|
||||
vi.mock("@/lib/db", async () => {
|
||||
if (process.env.TEST_DATABASE_URL?.trim()) {
|
||||
return await vi.importActual<typeof import("@/lib/prisma")>("@/lib/prisma");
|
||||
return await vi.importActual<typeof import("@/lib/db")>("@/lib/db");
|
||||
}
|
||||
|
||||
const { PGlite } = await import("@electric-sql/pglite");
|
||||
const { PrismaPGlite } = await import("pglite-prisma-adapter");
|
||||
const { PrismaClient } = await import("@prisma/client");
|
||||
const { drizzle } = await import("drizzle-orm/pglite");
|
||||
|
||||
const db = await PGlite.create();
|
||||
const migrationsDir = path.resolve(process.cwd(), "prisma", "migrations");
|
||||
const dirs = readdirSync(migrationsDir)
|
||||
.filter((entry) => /^\d/.test(entry))
|
||||
const client = new PGlite();
|
||||
const migrationsDir = path.resolve(process.cwd(), "lib", "db", "migrations");
|
||||
const files = readdirSync(migrationsDir)
|
||||
.filter((entry) => entry.endsWith(".sql"))
|
||||
.sort();
|
||||
for (const dir of dirs) {
|
||||
await db.exec(readFileSync(path.join(migrationsDir, dir, "migration.sql"), "utf8"));
|
||||
for (const file of files) {
|
||||
await client.exec(readFileSync(path.join(migrationsDir, file), "utf8"));
|
||||
}
|
||||
|
||||
const prisma = new PrismaClient({ adapter: new PrismaPGlite(db) });
|
||||
return { prisma };
|
||||
const db = drizzle(client, { schema });
|
||||
return { db, schema };
|
||||
});
|
||||
|
||||
const { prisma } = await import("@/lib/prisma");
|
||||
const { db } = await import("@/lib/db");
|
||||
|
||||
export { db };
|
||||
|
||||
// Truncated in dependency order (children first) between every test for isolation.
|
||||
const TABLES = [
|
||||
"MediaUsage",
|
||||
"MediaAsset",
|
||||
"PortfolioAsset",
|
||||
"PortfolioSection",
|
||||
"PortfolioProject",
|
||||
"Category",
|
||||
"AppConfig",
|
||||
"media_usage",
|
||||
"media_asset",
|
||||
"portfolio_asset",
|
||||
"portfolio_section",
|
||||
"portfolio_project",
|
||||
"category",
|
||||
"app_config",
|
||||
];
|
||||
|
||||
export async function resetDb() {
|
||||
const list = TABLES.map((table) => `"${table}"`).join(", ");
|
||||
await prisma.$executeRawUnsafe(`TRUNCATE TABLE ${list} RESTART IDENTITY CASCADE;`);
|
||||
await db.execute(sql.raw(`TRUNCATE TABLE ${list} RESTART IDENTITY CASCADE;`));
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
@@ -65,5 +69,6 @@ beforeEach(async () => {
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await prisma.$disconnect();
|
||||
// PGlite is in-process and torn down with the worker; the real postgres.js
|
||||
// client is a shared singleton and is left open on purpose.
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user