Error when saving migration

Hi all,

I’m getting this error after updating schema.prisma and running yarn rw db save. I updated User to include posts Post[] and Post to include user User and @relation(fields: [userId], references: [id]) userId Int

model User {
  id Int @id @default(autoincrement())
  email String @unique
  name String?
  posts Post[]
}

model Post {
  id Int @id @default(autoincrement())
  rating Int
  body String
  createdAt DateTime @default(now())
  user User @relation(fields: [userId], references: [id])
  userId Int      
}

Error: 

⚠️ We found migration(s) that cannot be executed:

  • Added the required column `userId` to the `Post` table without a default value. There are 2 rows in this table, it is not possible to execute this migration.

error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Any advice on where I should be looking :smile:

Thanks,
Connor

Hi @CRR.

Any advice on where I should be looking :smile:

I think you said that you were a new developer just starting out, so want to share that one of the great lessons is that (most) people building software are out there trying to help you use it – so they try – for the most part – to guide you along the way with error messages. And one of the great skills starting out as a dev is learning how to read and recognize them.

Added the required column userId to the Post table without a default value. There are 2 rows in this table, it is not possible to execute this migration.

It’s saying that you tried to run a migration and it failed. The migration tried to add a userId to Post and that it is a required field (ie it needs a value and cannot be null) but you tried to add it with out a default value.

The issue is that in the Post table you have two existing records with data in it. When it tried to add the userId it couldn’t because it needed a value – but there was no default.

Basically, you have two Posts with data in it – tried to connect a User, but it can’t connect it because it doesn’t know the userId to … well use.

The easiest way to fix this is:

Since this is a dev environment, just truncate the Post table or delete all the records. If there are 0 Posts, then it can add the column and won’t run into issues because no Posts need a userId.

Now, if you were in Production, you’d have to:

  1. Add the userId and let it be nullable.
  2. Then dataMigrate to assign posts to the users you need.
  3. Add a migration to make the userId required.

But, don’t do that. Just delete the dev Posts.

Now this assumes you do want every Post to have an author/user, which I imagine you do.

Note on default fields.

Sometimes you will add a column that is required, but you can give it a default value (like current datetime or 0 or FALSE).

Prisma does this via @default() as described here: Models

1 Like