Remix Blues Stackを使ってアプリを作成する場合、Prismaを活用すると思います。
その場合、必ず既存のschema.prismaに修正を加えたいと考えると思います。
しかし、schema.prismaに存在する既存のUserモデルなどにカラムを追加した後にnpm run setup
を実行すると、The column *** does not exist in the current database.
エラーが発生する場合があります。
node ➜ /workspaces/example (main) $ npm run setup
> setup
> prisma generate && prisma migrate deploy && prisma db seed
Environment variables loaded from .env
Prisma schema loaded from prisma/schema.prisma
✔ Generated Prisma Client (4.6.1 | library) to ./node_modules/@prisma/client in 155ms
You can now start using Prisma Client in your code. Reference: https://pris.ly/d/client
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
Environment variables loaded from .env
Prisma schema loaded from prisma/schema.prisma
Datasource "db": PostgreSQL database "postgres", schema "public" at "localhost:5432"
3 migrations found in prisma/migrations
No pending migrations to apply.
Environment variables loaded from .env
Running seed command `ts-node --require tsconfig-paths/register prisma/seed.ts` ...
PrismaClientKnownRequestError:
Invalid `prisma.user.create()` invocation in
/workspaces/example/prisma/seed.ts:17:34
14 const hashedPassword = await bcrypt.hash("racheliscool", 10);
15
16 // create an admin user
→ 17 const user = await prisma.user.create(
The column `name` does not exist in the current database.
at RequestHandler.handleRequestError (/workspaces/example/node_modules/@prisma/client/runtime/index.js:34310:13)
at RequestHandler.request (/workspaces/example/node_modules/@prisma/client/runtime/index.js:34293:12)
at async PrismaClient._request (/workspaces/example/node_modules/@prisma/client/runtime/index.js:35273:16)
at async seed (/workspaces/example/prisma/seed.ts:17:16) {
code: 'P2022',
clientVersion: '4.6.1',
meta: { column: 'name' }
}
An error occurred while running the seed command:
Error: Command failed with exit code 1: ts-node --require tsconfig-paths/register prisma/seed.ts
具体的にどの箇所が問題なのかを確認するために、まずはsetup
スクリプトの詳細を確認しましょう。
prisma generate && prisma migrate deploy && prisma db seed
そして、エラーを確認してみると次の一文が確認できます。
Error: Command failed with exit code 1: ts-node --require tsconfig-paths/register prisma/seed.ts
つまり、prisma db seed
の実行時にエラーが発生していることがわかります。
もう少し遡ってみましょう。
今度は、prisma migrate deploy
の部分です。
3 migrations found in prisma/migrations
No pending migrations to apply.
はい、これが原因です。
つまり、スキーマを変更した後に新しいマイグレーションファイルを作成しないといけないにも関わらず、マイグレーションファイルが作成されていないため、データベースに新しいカラムの情報が反映されていないことが確認できます。
それでは、新しいマイグレーションファイルを作成しましょう。
npx prisma migrate dev --name add_column_name
prisma/migrations/xxxx_add_column_name/migration.sqlが作成されていることを確認してみてください。
確認ができたら、再度npm run setup
を実行してみましょう。
node ➜ /workspaces/example (main) $ npm run setup
...
Environment variables loaded from .env
Running seed command `ts-node --require tsconfig-paths/register prisma/seed.ts` ...
Database has been seeded. 🌱
🌱 The seed command has been executed.
The seed command has been executed.
と表示されたら成功です。