P
Prisma3mo ago
hill

Prisma ORM with Cloudflare D1/Next-on-pages

I'm transitioning my app from planetscale/prisma -> D1/Drizzle -> Cloudflare D1/prisma. Trying to set up a 'db.ts' folder which can be callable into different portions of the app to query the db. Anybody have experience setting this up? Doesn't help that there are only two examples in existence, both of which query D1 through a worker (rather than directly from the app). This is my current code: const adapter = new PrismaD1( process.env.NODE_ENV === "development" ? getRequestContext().env.DB : (process.env as any).DB ); const db = new PrismaClient({ adapter }) and this is the old code, when using MySQL: import { PrismaClient } from "@prisma/client" declare global { // eslint-disable-next-line no-var var cachedPrisma: PrismaClient } let prisma: PrismaClient if (process.env.NODE_ENV === "production") { prisma = new PrismaClient() } else { if (!global.cachedPrisma) { global.cachedPrisma = new PrismaClient() } prisma = global.cachedPrisma } export const db = prisma Any assistance would be greatly appreciated.
2 Replies
zilla
zilla3mo ago
Not sure if this helps, but this is what I used when migrating from Planetscale to Turso. I am assuming you will only need slight changes to make it work on D1 as both Turso and D1 are based on LibSQL.
import { createClient } from '@libsql/client';
import { PrismaLibSQL } from '@prisma/adapter-libsql';
import { PrismaClient } from '@prisma/client';

const libsql = createClient({
url: `${process.env.TURSO_DATABASE_URL}`,
authToken: `${process.env.TURSO_AUTH_TOKEN}`,
});

const adapter = new PrismaLibSQL(libsql);
const prisma = new PrismaClient({
adapter,
log: ['query', 'info', 'warn', 'error'],
});

export default prisma;
import { createClient } from '@libsql/client';
import { PrismaLibSQL } from '@prisma/adapter-libsql';
import { PrismaClient } from '@prisma/client';

const libsql = createClient({
url: `${process.env.TURSO_DATABASE_URL}`,
authToken: `${process.env.TURSO_AUTH_TOKEN}`,
});

const adapter = new PrismaLibSQL(libsql);
const prisma = new PrismaClient({
adapter,
log: ['query', 'info', 'warn', 'error'],
});

export default prisma;
hill
hill3mo ago
Thanks Zilla, might try to mess around with it a bit tomorrow. The kicker is that with D1 on Pages, since it is a page function (possibly?) it doesnt use a url for the connection - I get why its needed for local development, but I've just adapted the existing code and tweaked it a bit: import { PrismaClient } from "@prisma/client"; import { PrismaD1 } from "@prisma/adapter-d1"; import { getRequestContext } from "@cloudflare/next-on-pages"; const adapter = new PrismaD1(getRequestContext().env.DB); export const db = new PrismaClient({ adapter });