LoginSignup
0
0

【エラー対応】`prisma db seed` で .env.localを読み込む方法

Last updated at Posted at 2023-09-17

背景

  • Next.jsを導入しているプロジェクトにPrismaのseed.tsファイルを作成し、prisma db seedを実行した時に起きたエラー
seed.ts
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()

console.log('Prisma seed');

async function main() {
  const events = await prisma.event.findMany({})
  console.log({events})
  // ...
}

main()
  .then(async () => {
    await prisma.$disconnect()
  })
  .catch(async (e) => {
    console.error(e)
    await prisma.$disconnect()
    process.exit(1)
  })
package.json
{
  // ...
  "prisma": {
    "seed": "ts-node --compiler-options {\"module\":\"CommonJS\"} prisma/seed.ts"
  }
}
.env
# ダミーデータ
DATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public"

エラー文

$ npx prisma db seed

Environment variables loaded from .env
Running seed command `ts-node --compiler-options {"module":"CommonJS"} prisma/seed.ts` ...
Prisma seed
PrismaClientInitializationError: 
Invalid `prisma.event.findMany()` invocation in
/Users/xxx/git/maiamea/remake-hayaoki-girls-calendar/prisma/seed.ts:12:37

   9 console.log('Prisma seed');
  10 
  11 async function main() {
→ 12   const events = await prisma.event.findMany(
User `johndoe` was denied access on the database `mydb.public`
    at vn.handleRequestError (/Users/xxx/git/maiamea/remake-hayaoki-girls-calendar/node_modules/@prisma/client/runtime/library.js:123:7003)
    at vn.handleAndLogRequestError (/Users/xxx/git/maiamea/remake-hayaoki-girls-calendar/node_modules/@prisma/client/runtime/library.js:123:6119)
    at vn.request (/Users/xxx/git/maiamea/remake-hayaoki-girls-calendar/node_modules/@prisma/client/runtime/library.js:123:5839)
    at async l (/Users/xxx/git/maiamea/remake-hayaoki-girls-calendar/node_modules/@prisma/client/runtime/library.js:128:9763) {
  clientVersion: '5.2.0',
  errorCode: undefined
}

An error occurred while running the seed command:
Error: Command failed with exit code 1: ts-node --compiler-options {"module":"CommonJS"} prisma/seed.ts

prisma db seed 実行時に起こること(想像)

  1. Prismaが.envを読み込む
  2. package.jsonprisma.seedに書いているコマンドを実行する
  3. .envに書いてあるDATABASE_URLをもとに、DBに接続しに行く
    • Next.jsにおいては機密情報は.env.localに記述するのを推奨している。しかしPrismaはデフォルトだと.envしか読み込まない
  4. .envに書いてあるDATABASE_URLはダミーデータなのでDBに接続できずエラーとなる

対処

  • .env.localを読み込ませるためには以下のコマンドを実行する
# dotenv-cli をインストール
$ npm install --save-dev dotenv-cli

# .env.local を読み込んで prisma db seed を実行
$ ./node_modules/.bin/dotenv -e .env.local -- npx prisma db seed

Prisma seed
{ events: [] }

🌱  The seed command has been executed.

無事エラーが解消された。

参考サイト

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0