Created
January 17, 2025 19:28
-
-
Save gtindo/008c341a638db79b842732425b263b03 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import fs from "node:fs/promises"; | |
import path from "node:path"; | |
import crypto from "node:crypto"; | |
import { PGlite } from "@electric-sql/pglite"; | |
import { PrismaPGlite } from "pglite-prisma-adapter"; | |
import { PrismaClient } from "@prisma/client"; | |
/** | |
* Create a PgLite instance, then create tables in the db from prisma migrations | |
*/ | |
export async function createInMemoryDb() { | |
console.time("setup-db==="); | |
try { | |
await fs.mkdir("/tmp/pglite"); | |
} catch (e) {} | |
const dbPath = `/tmp/pglite/${crypto.randomUUID()}`; | |
const client = new PGlite(dbPath); | |
const adapter = new PrismaPGlite(client); | |
const prisma = new PrismaClient({ adapter }); | |
// TODO: Add path of migrations folder | |
const migrationsDirPath = | |
// Apply Migrations | |
const migrations = await fs.readdir(migrationsDirPath); | |
for (let migration of migrations) { | |
// Skip lock file | |
if (migration === "migration_lock.toml") continue; | |
const migrationSqlPath = path.join(migrationsDirPath, migration, "migration.sql"); | |
const migrationSql = (await fs.readFile(migrationSqlPath)).toString("utf-8"); | |
await client.exec(migrationSql); | |
} | |
console.timeEnd("setup-db==="); | |
return { | |
dbPath, | |
prisma: prisma, | |
pglite: client, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment