63 lines
1.7 KiB
JavaScript
63 lines
1.7 KiB
JavaScript
import path from "node:path"
|
|
|
|
// NOTE: This helper imports the generated Prisma client from TypeScript files.
|
|
// Run scripts that rely on it via a transpiling runner (e.g. `tsx` or Bun).
|
|
import { PrismaClient } from "../../src/generated/prisma/client.ts"
|
|
import { PrismaBetterSqlite3 } from "@prisma/adapter-better-sqlite3"
|
|
|
|
const PROJECT_ROOT = process.cwd()
|
|
const PRISMA_DIR = path.join(PROJECT_ROOT, "prisma")
|
|
|
|
function resolveFileUrl(url) {
|
|
if (!url.startsWith("file:")) {
|
|
return url
|
|
}
|
|
|
|
const filePath = url.slice("file:".length)
|
|
|
|
if (filePath.startsWith("//")) {
|
|
return url
|
|
}
|
|
|
|
if (path.isAbsolute(filePath)) {
|
|
return `file:${path.normalize(filePath)}`
|
|
}
|
|
|
|
const normalized = path.normalize(filePath)
|
|
const prismaPrefix = `prisma${path.sep}`
|
|
const relativeToPrisma = normalized.startsWith(prismaPrefix)
|
|
? normalized.slice(prismaPrefix.length)
|
|
: normalized
|
|
|
|
const absolutePath = path.resolve(PRISMA_DIR, relativeToPrisma)
|
|
|
|
if (!absolutePath.startsWith(PROJECT_ROOT)) {
|
|
throw new Error(`DATABASE_URL path escapes project directory: ${filePath}`)
|
|
}
|
|
|
|
return `file:${absolutePath}`
|
|
}
|
|
|
|
function normalizeDatasourceUrl(envUrl) {
|
|
const trimmed = envUrl?.trim()
|
|
if (trimmed) {
|
|
return resolveFileUrl(trimmed)
|
|
}
|
|
|
|
if (process.env.NODE_ENV === "production") {
|
|
return "file:/app/data/db.sqlite"
|
|
}
|
|
|
|
return resolveFileUrl("file:./db.dev.sqlite")
|
|
}
|
|
|
|
export function createPrismaClient() {
|
|
const resolvedDatabaseUrl = normalizeDatasourceUrl(process.env.DATABASE_URL)
|
|
process.env.DATABASE_URL = resolvedDatabaseUrl
|
|
|
|
const adapter = new PrismaBetterSqlite3({
|
|
url: resolvedDatabaseUrl,
|
|
})
|
|
|
|
return new PrismaClient({ adapter })
|
|
}
|