Planetscale gives users a mysql database with features such as branches that have the main purpose of proposing new database schema changes which can then be merged or moved into the production environment or branch. Of course branches can also host data in it’s tables separate from the production branch so it makes a very good practice in testing schema changes before deploying to production.
When working with prisma and planetscale, there are a few changes I discuss here:
You can refer to this youtube video
Prisma Schema Changes
You can use the same prisma schema for your databases as usual, there are only a few changes:
- Setting the relation mode. Prisma by default supports database relations with foreign keys but planetscale does not support foreign keys so in other to use prisma with planetscale, you must set your database relation to
prisma
which allows your client to still emulate relations.
datasource db {
provider = "mysql"
url = env("DATABASE_URL")
relationMode = "prisma"
}
- Adding Indexes to foreign keys. Because there’s no support for foreign keys, you need to manually add indexes to your foreign keys to avoid full table scans.
Example:
model User {
id String @id @default(cuid())
name String @unique
email String @unique
profile Profile?
}
model Profile {
id String @id @default(cuid())
image String?
bio String?
user_id String @unique
user User @relation(fields: [user_id], references: [id])
@@index([user_id]) // this is the index for my user_id
}
Performing migrations
Planetscale with prisma does not support migrate commands so generating sql schemas with prisma migrate dev
will have no effect on your planetscale database. Instead, you make changes by running prisma db push
command. This will ensure that any prisma schema changes are pushed to the branch you provided as your connection string.
In this way, you can provision a dev branch for instance, push your schema changes there, and then when you are satisfied with the changes, use a planetscale deploy request to merge it into your production branch. So instead of using migrate commands to run your migrations and do schema changes, your push your schema changes and use planetscale to do the changes merge into your production environment. And of course planetscale will let you know during deploy requests if there are any change conflicts so you resolve them.
If you want to use planetsale with prisma on the edge, checkout my other article on using prisma client on the edge