Skip to content

Commit

Permalink
Guide to using Prisma with PlanetScale (#2708)
Browse files Browse the repository at this point in the history
Co-authored-by: Jan Piotrowski <piotrowski+github@gmail.com>
Co-authored-by: Tana Berry <tanaberry@Tanas-MacBook-Pro.local>
Co-authored-by: Lucy Keer <keer@prisma.io>
Co-authored-by: Lucy Keer <lucy.keer@gmail.com>
  • Loading branch information
5 people authored and matthewmueller committed Jul 22, 2022
1 parent 9978056 commit e753f25
Show file tree
Hide file tree
Showing 3 changed files with 251 additions and 0 deletions.
242 changes: 242 additions & 0 deletions content/300-guides/050-database/850-using-prisma-with-planetscale.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,242 @@
---
title: 'Using Prisma with PlanetScale'
metaTitle: 'Using Prisma with PlanetScale'
metaDescription: 'Guide to using Prisma with PlanetScale'
tocDepth: 2
toc: true
---

<TopBlock>

Prisma and [PlanetScale](https://planetscale.com/) together provide a development arena that optimizes rapid, type-safe development of data access applications, using Prisma's ORM and PlanetScale's highly scalable MySQL-based platform.

This document discusses the concepts behind using Prisma and PlanetScale, explains the commonalities and differences between PlanetScale and other database providers, and leads you through the process for configuring your application to integrate with PlanetScale.

</TopBlock>

## What is PlanetScale?

PlanetScale uses the [Vitess](https://vitess.io/) database clustering system to provide a MySQL-compatible database platform. Features include:

- **Enterprise scalability.** PlanetScale provides a highly available production database cluster that supports scaling across multiple database servers. This is particularly useful in a serverless context, as it avoids the problem of having to [manage connection limits](/guides/performance-and-optimization/connection-management#serverless-environments-faas).

- **Database branches.** PlanetScale allows you to create [branches of your database schema](https://docs.planetscale.com/concepts/branching), so that you can test changes on a development branch before applying them to your production database.

- **Support for [non-blocking schema changes](https://docs.planetscale.com/concepts/nonblocking-schema-changes).** PlanetScale provides a workflow that allows users to update database schemas without locking the database or causing downtime.

## Commonalities with other database providers

Many aspects of using Prisma with PlanetScale are just like using Prisma with any other relational database. You can still:

- model your database with the [Prisma Schema Language](/concepts/components/prisma-schema)
- use Prisma's existing [`mysql` database connector](/concepts/database-connectors/mysql) in your schema, along with the [connection string PlanetScale provides you](https://docs.planetscale.com/concepts/connection-strings)
- use [Introspection](/concepts/components/introspection) for existing projects if you already have a database schema in PlanetScale
- use [`db push`](/concepts/components/prisma-migrate/db-push) to push changes in your schema to the database
- use [Prisma Client](/concepts/components/prisma-client) in your application to talk to the database server at PlanetScale

## Differences to consider

PlanetScale's branching model and design for scalability means that there are also a number of differences to consider. You should be aware of the following points when deciding to use PlanetScale with Prisma:

- **Branching and deploy requests.** PlanetScale provides two types of database branches: _development branches_, which allow you to test out schema changes, and _production branches_, which are protected from direct schema changes. Instead, changes must be first created on a development branch and then deployed to production using a deploy request. Production branches are highly available and include automated daily backups. To learn more, see [How to use branches and deploy requests](#how-to-use-branches-and-deploy-requests).

- **Referential actions and integrity.** To support scaling across multiple database servers, PlanetScale [does not allow the use of foreign key constraints](https://docs.planetscale.com/learn/operating-without-foreign-key-constraints), which are normally used in relational databases to enforce relationships between data in different tables. To maintain these relationships in your data while using PlanetScale with Prisma and allow the use of [referential actions](/concepts/components/prisma-schema/relations/referential-actions), you will need to use Prisma's ability to [emulate referential integrity in the Prisma client](/concepts/components/prisma-schema/relations/referential-integrity#handling-the-referential-integrity-in-prisma). For more information, see [How to enable emulation of referential integrity](#how-to-enable-emulation-of-referential-integrity).

- **Creating indexes on foreign keys.** In a standard MySQL database, if a table has a column with a foreign key constraint, an index is automatically created on that column. As PlanetScale does not support foreign keys, these indexes are [currently](https://github.com/prisma/prisma/issues/10611) not created when emulating referential integrity in Prisma, which can lead to issues with queries not being well optimised. To avoid this, you can create indexes in Prisma. For more information, see [How to create indexes on foreign keys](#how-to-create-indexes-on-foreign-keys).

- **Making schema changes with `db push`.** When you merge a development branch into your production branch, PlanetScale will automatically compare the two schemas and generate its own schema diff. This means that Prisma's [`prisma migrate`](/concepts/components/prisma-migrate) workflow, which generates its own history of migration files, is not a natural fit when working with PlanetScale. These migration files may not reflect the actual schema changes run by PlanetScale when the branch is merged.

<Admonition type="warning">

Prisma recommends not using `prisma migrate` when making schema changes with PlanetScale. Instead, we recommend that you use the `prisma db push` command.

</Admonition>

For an example of how this works, see [How to make schema changes with `db push`](#how-to-make-schema-changes-with-db-push)

- **Introspection**. When you introspect on an existing database, you will get a schema with no relations, as they are usually defined based on foreign keys that connect tables. Because PlanetScale does not support foreign keys, and you use Prisma to emulate referential integrity, you will need to add the missing relations in manually. For more information, see [How to add in missing relations after Introspection](#how-to-add-in-missing-relations-after-Introspection).

## How to use branches and deploy requests

When connecting to PlanetScale with Prisma, you will need to use the correct connection string for your branch. The connection URL for a given database branch can be found from your PlanetScale account by going to the overview page for the branch and selecting the 'Connect' dropdown. In the 'Passwords' section, generate a new password and select 'Prisma' from the dropdown to get the Prisma format for the connection URL. See Prisma's [Getting Started guide](/getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-typescript-planetscale) for more details of how to connect to a PlanetScale database.

Every PlanetScale database is created with a branch called `main`, which is initially a development branch that you can use to test schema changes on. Once you are happy with the changes you make there, you can [promote it](https://docs.planetscale.com/concepts/branching#branch-promotion) to become a production branch. Note that you can only push new changes to a development branch, so further changes will need to be created on a separate development branch and then later deployed to production using a [deploy request](https://docs.planetscale.com/concepts/branching#create-a-deploy-request).

If you try to push to a production branch, you will get the [error message](/reference/api-reference/error-reference#p3022) `Direct execution of DDL (Data Definition Language) SQL statements is disabled on this database.`

## How to enable emulation of referential integrity

Referential integrity is currently a [Preview feature](/concepts/components/preview-features). To enable this, add it to the `previewFeatures` list in the `generator` block of `schema.prisma`, and then set the `referentialIntegrity` type to `"prisma"` in the `datasource` block:

```prisma file=schema.prisma
datasource db {
provider = "mysql"
url = env("DATABASE_URL")
referentialIntegrity = "prisma"
}
generator js {
provider = "prisma-client-js"
previewFeatures = ["referentialIntegrity"]
}
```

## How to create indexes on foreign keys

When [emulating referential integrity in Prisma](#how-to-enable-emulation-of-referential-integrity), you will need to create your own indexes. As an example of a situation where you would want to an add an index, take this schema for a blog with posts and comments:

```prisma file=schema.prisma
model Post {
id Int @id @default(autoincrement())
title String
content String
likes Int @default(0)
comments Comment[]
}
model Comment {
id Int @id @default(autoincrement())
comment String
postId Int
post Post @relation(fields: [postId], references: [id], onDelete: Cascade)
}
```

The `postId` field in the `User` model refers to the corresponding `id` field in the `Post` model. However this is not implemented as a foreign key in PlanetScale, so the column doesn't have an automatic index. This means that some queries may not be well optimised. For example, if you query for all comments with a certain post `id`, PlanetScale may have to do a full table lookup. This could be slow, and also expensive because PlanetScale's billing model charges for the number of rows read.

To avoid this, you can define an index on the `postId` field using [Prisma's `@@index` argument](https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference#index):

```prisma file=schema.prisma highlight=15;add
model Post {
id Int @id @default(autoincrement())
title String
content String
likes Int @default(0)
comments Comment[]
}
model Comment {
id Int @id @default(autoincrement())
comment String
postId Int
post Post @relation(fields: [postId], references: [id], onDelete: Cascade)
@@index([postId])
}
```

You can then add this change to your schema [using `db push`](#how-to-make-schema-changes-with-db-push).

<Admonition type="warning">

One issue to be aware of is that [implicit many-to-many relations](/concepts/components/prisma-schema/relations/many-to-many-relations#implicit-many-to-many-relations) cannot have an index added in this way. If query speed or cost is an issue, you may instead want to use an [explicit many-to-many relation](/concepts/components/prisma-schema/relations/many-to-many-relations#explicit-many-to-many-relations) in this case.

</Admonition>

## How to make schema changes with `db push`

To use `db push` with PlanetScale, you will first need to [enable emulation of referential integrity in Prisma](#how-to-enable-emulation-of-referential-integrity). Pushing to your branch without referential emulation enabled will give the [error message](http://localhost:8000/reference/api-reference/error-reference#p3021) `Foreign keys cannot be created on this database.`

As an example, let's say you decide to decide to add a new `excerpt` field to the blog post schema above. You will first need to [create a new development branch and connect to it](#how-to-use-branches-and-deploy-requests).

Next, add the following to your `schema.prisma` file:

```prisma file=schema.prisma highlight=5;edit
model Post {
id Int @id @default(autoincrement())
title String
content String
excerpt String?
likes Int @default(0)
comments Comment[]
}
model Comment {
id Int @id @default(autoincrement())
comment String
postId Int
post Post @relation(fields: [postId], references: [id], onDelete: Cascade)
@@index([postId])
}
```

To push these changes, navigate to your project directory in your terminal and run

```terminal
npx prisma db push
```

Once you are happy with your changes on your development branch, you can open a deploy request to deploy these to your production branch.

For more examples, see PlanetScale's tutorial on [automatic migrations with Prisma](https://docs.planetscale.com/tutorials/automatic-prisma-migrations) using `db push`.

## How to add in missing relations after Introspection

After introspecting with `npx prisma db pull`, the schema you get may be missing some relations. For example, the following schema is missing a relation between the `User` and `Post` models:

```prisma file=schema.prisma
model Post {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
title String @db.VarChar(255)
content String?
authorId Int
@@index([authorId])
}
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
}
```

In this case you need to add the relation in manually:

```prisma file=schema.prisma highlight=6,16;add
model Post {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
title String @db.VarChar(255)
content String?
author User @relation(fields: [authorId], references: [id])
authorId Int
@@index([authorId])
}
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
posts Post[]
}
```

For a more detailed example, see the [Getting Started guide for PlanetScale](/getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection-typescript-planetscale).

## More on using PlanetScale with Prisma

The fastest way to start using PlanetScale with Prisma is to refer to our Getting Started documentation:

- [Start from scratch](https://www.prisma.io/docs/getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-planetscale)
- [Add to existing project](https://www.prisma.io/docs/getting-started/setup-prisma/add-to-existing-project/relational-databases-typescript-planetscale)

These tutorials will take you through the process of connecting to PlanetScale, pushing schema changes, and using the Prisma Client.

For further tips on best practices when using Prisma and PlanetScale together, watch our video:

<div class="videoWrapper">

<iframe
width="560"
height="315"
src="https://www.youtube.com/embed/iaHt5_hg44c"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen
></iframe>

</div>
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,14 @@ Possible errors:

"The automatic creation of shadow databases is disabled on Azure SQL. Please set up a shadow database using the `shadowDatabaseUrl` datasource attribute.<br />Read the docs page for more details: https://pris.ly/d/migrate-shadow"

#### <inlinecode>P3021</inlinecode>

"Foreign keys cannot be created on this database. Learn more how to handle this: https://pris.ly/d/migrate-no-foreign-keys"

#### <inlinecode>P3022</inlinecode>

"Direct execution of DDL (Data Definition Language) SQL statements is disabled on this database. Please read more here how to handle this: https://pris.ly/d/migrate-no-direct-ddl"

### <inlinecode>prisma db pull</inlinecode> (Introspection Engine)

#### <inlinecode>P4000</inlinecode>
Expand Down
1 change: 1 addition & 0 deletions gatsby-config.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ const gatsbyRemarkPlugins = [
'/getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-planetscale',
'/getting-started/setup-prisma/add-to-existing-project/relational-databases-typescript-planetscale',
'/getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-typescript-planetscale',
'/getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection-typescript-planetscale',
],
},
},
Expand Down

0 comments on commit e753f25

Please sign in to comment.