Skip to content

How To Use Drizzle ORM with PlanetScale (connection string)

Posted on:May 30, 2023 at 07:22 PM

I was trying to use Drizzle ORM with PlanetScale, and I was having some issues when trying to push my database schema. For some reason it just woudln’t work, but I solved the issue by using a connection string.

Drizzle Configuration using a PlanetScale connection string

To get your connection string:

  1. Go to to your PlanetScale dashboard
  2. Click “Connect”
  3. Select the “Prisma” option
  4. Copy your connection string

If it doesn’t show you the connection string, you can generate a new password and repeat the steps above.

Here you can see what the dashboard looks like:

The connection string as displayed in the PlanetScale dashboard

You can then add your connection string to your .env file. Here’s an example:

DATABASE_URL='mysql://ab12s9c5u37ve345cd:pscale_pw_*******************@aws.connect.psdb.cloud/blogrecorder?sslaccept=strict'

You then use the DATABASE_URL in your Drizzle configuration.

// drizzle.config.ts
import type { Config } from "drizzle-kit";

export default {
  schema: "./drizzle/schema.ts",
  out: "./drizzle/generated",
  connectionString: process.env["DATABASE_URL"],
} satisfies Config;

To then push your schema, you can add this db:push command to your package.json:

"db:push": "drizzle-kit push:mysql --config ./drizzle.config.ts",

If you don’t have the dependencies installed yet, you can do so with these commands:

npm i drizzle-orm @planetscale/database
npm i -D drizzle-kit

If you have defined a schema and have configured everything as described here, you should now be able to push your Drizzle schema to PlanetScale:

npm run db:push

Error: foreign key constraints are not allowed when using PlanetScale

You might get this error when you push your schema to planetscale. I did, because my Drizzle schema had some relations in it that were generating foreign keys.

PlanetScale’s non-blocking schema change workflow can’t support foreign key constraints so PlanetScale databases reject them, but your schema will still work. (source).

You can either edit your schema to remove the relations or continue using it as is, it will work just fine on the PlanetScale side of things.

Conclusion

I hope this helps. I’m still playing around with both Drizzle and PlanetScale, so maybe you can expect some more articles about using them in the future.