Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(prisma): support pglite in developer environments #338

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion src/env.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ const sgidServerSchema = z.discriminatedUnion('NEXT_PUBLIC_ENABLE_SGID', [
*/
const server = z
.object({
DATABASE_URL: z.string().url(),
DATABASE_URL: z.string().url().optional(),
NODE_ENV: z.enum(['development', 'test', 'production']),
OTP_EXPIRY: z.coerce.number().positive().optional().default(600),
POSTMAN_API_KEY: z.string().optional(),
Expand Down Expand Up @@ -122,6 +122,17 @@ const server = z
message: 'SENDGRID_FROM_ADDRESS is required when SENDGRID_API_KEY is set',
path: ['SENDGRID_FROM_ADDRESS'],
})
.refine(
(val) =>
val.NODE_ENV === 'development' ||
LoneRifle marked this conversation as resolved.
Show resolved Hide resolved
val.NODE_ENV === 'test' ||
val.DATABASE_URL,
{
message:
'DATABASE_URL has to be set if NODE_ENV is not development or test',
path: ['DATABASE_URL'],
},
)

/**
* You can't destruct `process.env` as a regular object in the Next.js edge runtimes (e.g.
Expand Down
20 changes: 0 additions & 20 deletions src/server/prisma.ts

This file was deleted.

39 changes: 39 additions & 0 deletions src/server/prisma/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/**
* Instantiates a single instance PrismaClient and save it on the global object.
* @link https://www.prisma.io/docs/support/help-articles/nextjs-prisma-client-dev-practices
*/
import { PrismaClient } from '@prisma/client'
import pino from 'pino'
import { env } from '~/env.mjs'
import { makePgliteClient, applyMigrations } from './pglite'

const prismaGlobal = global as typeof global & {
prisma?: PrismaClient
}

const choosePrismaClient = () => {
if (
!env.DATABASE_URL &&
(env.NODE_ENV === 'development' || env.NODE_ENV === 'test')
) {
pino().warn({}, 'DATABASE_URL not set, using pglite')
LoneRifle marked this conversation as resolved.
Show resolved Hide resolved
const { client, prisma: pglitePrismaClient } = makePgliteClient()
// Inject an env var to appease Prisma
process.env.DATABASE_URL = 'postgres://using:pglite@localhost:5432/'
void applyMigrations(client)
return pglitePrismaClient
} else {
return (
prismaGlobal.prisma ||
new PrismaClient({
log: env.NODE_ENV === 'development' ? ['error', 'warn'] : ['error'],
LoneRifle marked this conversation as resolved.
Show resolved Hide resolved
})
)
}
}

export const prisma: PrismaClient = choosePrismaClient()

if (env.NODE_ENV !== 'production') {
prismaGlobal.prisma = prisma
}
25 changes: 25 additions & 0 deletions src/server/prisma/pglite.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { PGlite } from '@electric-sql/pglite'
import { PrismaPGlite } from 'pglite-prisma-adapter'
import { PrismaClient } from '@prisma/client'
import { readdirSync, readFileSync, statSync } from 'node:fs'

export const makePgliteClient = () => {
const client = new PGlite()
const adapter = new PrismaPGlite(client)
return {
client,
prisma: new PrismaClient({ adapter }),
}
}

export const applyMigrations = async (client: PGlite) => {
const prismaMigrationDir = './prisma/migrations'
const directory = readdirSync(prismaMigrationDir).sort()
for (const file of directory) {
const name = `${prismaMigrationDir}/${file}`
if (statSync(name).isDirectory()) {
const migration = readFileSync(`${name}/migration.sql`, 'utf8')
await client.exec(migration)
}
}
}
25 changes: 4 additions & 21 deletions vitest.setup.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,13 @@
import { vi } from 'vitest'
import { PGlite } from '@electric-sql/pglite'
import { PrismaPGlite } from 'pglite-prisma-adapter'
import { PrismaClient } from '@prisma/client'
import { readdirSync, readFileSync, statSync } from 'node:fs'
import { makePgliteClient, applyMigrations } from '~/server/prisma/pglite'

const client = new PGlite()
const adapter = new PrismaPGlite(client)
const prisma = new PrismaClient({ adapter })
const { client, prisma } = makePgliteClient()

vi.mock('./src/server/prisma', () => ({
prisma,
}))

export const resetDb = async () => {
const resetDb = async () => {
try {
await client.exec(`DROP SCHEMA public CASCADE`)
await client.exec(`CREATE SCHEMA public`)
Expand All @@ -21,21 +16,9 @@ export const resetDb = async () => {
}
}

const applyMigrations = async () => {
const prismaMigrationDir = './prisma/migrations'
const directory = readdirSync(prismaMigrationDir).sort()
for (const file of directory) {
const name = `${prismaMigrationDir}/${file}`
if (statSync(name).isDirectory()) {
const migration = readFileSync(`${name}/migration.sql`, 'utf8')
await client.exec(migration)
}
}
}

// Apply migrations before each test
beforeEach(async () => {
await applyMigrations()
await applyMigrations(client)
})

// Clean up the database after each test
Expand Down
Loading