Skip to content

[6.6.0] D1 & Turso migrations #6775

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Apr 8, 2025
18 changes: 0 additions & 18 deletions content/200-orm/050-overview/500-databases/890-neon.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -6,32 +6,14 @@ tocDepth: 2
toc: true
---

<TopBlock>

This guide explains how to:

- [Connect Prisma ORM using Neon's connection pooling feature](#how-to-use-neons-connection-pooling)
- [Resolve connection timeout issues](#resolving-connection-timeouts)
- [Use Neon's serverless driver with Prisma ORM](#how-to-use-neons-serverless-driver-with-prisma-orm-preview)

</TopBlock>

## What is Neon?

<img
src="https://avatars.githubusercontent.com/u/77690634?s=200&v=4"
style={{
margin: 'auto',
width: '25%',
'padding-left': '20px',
float: 'right',
'@media (max-width: 641px)': {
display: 'none',
},
}}
alt="Neon's logo"
/>

[Neon](https://neon.tech/) is a fully managed serverless PostgreSQL with a generous free tier. Neon separates storage and compute, and offers modern developer features such as serverless, branching, bottomless storage, and more. Neon is open source and written in Rust.

Learn more about Neon [here](https://neon.tech/docs/introduction).
Expand Down
92 changes: 72 additions & 20 deletions content/200-orm/050-overview/500-databases/900-turso.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,9 @@ Prisma ORM support for Turso is currently in [Early Access](/orm/more/releases#e

[Turso](https://turso.tech/) is an edge-hosted, distributed database that's based on [libSQL](https://turso.tech/libsql), an open-source and open-contribution fork of [SQLite](https://sqlite.org/), enabling you to bring data closer to your application and minimize query latency. Turso can also be hosted on a remote server.

<Admonition type="warning">

:::warning
Support for Turso is available in [Early Access](/orm/more/releases#early-access) from Prisma ORM versions 5.4.2 and later.

</Admonition>
:::

## Commonalities with other database providers

Expand Down Expand Up @@ -78,7 +76,7 @@ turso db tokens create turso-prisma-db

Update your `.env` file with the authentication token and connection string:

```text file=.env
```bash file=.env
TURSO_AUTH_TOKEN="eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9..."
TURSO_DATABASE_URL="libsql://turso-prisma-db-user.turso.io"
```
Expand Down Expand Up @@ -130,31 +128,85 @@ const prisma = new PrismaClient({ adapter })

You can use Prisma Client as you normally would with full type-safety in your project.

## How to manage schema changes
## Using Prisma Migrate via a driver adapter in `prisma.config.ts` (Early Access)

As of [v6.6.0](https://pris.ly/release/6.6.0) and with a `prisma.config.ts` file, you can use `prisma db push` to make changes to your database schema.

Prisma Migrate and Introspection workflows are currently not supported when working with Turso. This is because Turso uses HTTP to connect to your database, which Prisma Migrate doesn't support.
:::warning

To update your database schema:
This functionality has been introduced in [Early Access](/orm/more/releases#early-access) in [v6.6.0](https://pris.ly/release/6.6.0) and supports the following commands:

1. Generate a migration file using `prisma migrate dev` against a local SQLite database:
- `prisma db push`
- `prisma db pull`
- `prisma migrate diff`

```terminal
npx prisma migrate dev --name init
```
Other commands like `prisma migrate dev` and `prisma migrate deploy` will be added soon.

2. Apply the migration using Turso's CLI:
:::

### 1. Install the LibSQL driver adapter

```terminal
turso db shell turso-prisma-db < ./prisma/migrations/20230922132717_init/migration.sql
```
Run this command in your terminal:

```termina
npm install @prisma/adapter-libsql
```

:::info
### 2. Set environment variables

Replace `20230922132717_init` with the name of your migration.
In order to set up the LibSQL adapter, you'll need to add a few secrets to a `.env` file:

:::
- `LIBSQL_DATABASE_URL`: The connection URL of your Turso database instance.
- `LIBSQL_DATABASE_TOKEN`: The token of your Turso database instance.

You can then add these to your `.env` file or use them directly if they are stored in a different secret store:

```bash file=.env
LIBSQL_DATABASE_URL="..."
LIBSQL_DATABASE_TOKEN="..."
```

### 3. Set up Prisma Config file

Make sure that you have a [`prisma.config.ts`](/orm/reference/prisma-config-reference) file for your project. Then, set up the [migration driver adapter](/orm/reference/prisma-config-reference#migrationadapter) to use `PrismaLibSQL`:

```ts file=prisma.config.ts
import path from 'node:path'
import { defineConfig } from 'prisma/config'
import { PrismaLibSQL } from '@prisma/adapter-libsql'

For subsequent migrations, repeat the above steps to apply changes to your database. This workflow does not support track the history of applied migrations to your remote database.
// import your .env file
import 'dotenv/config'

type Env = {
LIBSQL_DATABASE_URL: string
LIBSQL_DATABASE_TOKEN: string
}

export default defineConfig<Env>({
earlyAccess: true,
schema: path.join('prisma', 'schema.prisma'),

migrate: {
async adapter(env) {
return new PrismaLibSQL({
url: env.LIBSQL_DATABASE_URL,
authToken: env.LIBSQL_DATABASE_TOKEN,
})
}
}
})
```

### 4. Migrate your database

Prisma Migrate now will run migrations against your remote Turso database based on the configuration provided in `prisma.config.ts`.

To create your first migration with this workflow, run the following command:

```terminal
npx prisma db push
```

## Embedded Turso database replicas

Expand Down
143 changes: 124 additions & 19 deletions content/200-orm/050-overview/500-databases/950-cloudflare-d1.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,15 @@ tocDepth: 3
preview: true
---

<TopBlock>

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

Prisma ORM support for Cloudflare D1 is currently in [Preview](/orm/more/releases#preview). We would appreciate your feedback [on GitHub](https://github.com/prisma/prisma/discussions/23646).

If you want to deploy a Cloudflare Worker with D1 and Prisma ORM, follow this [tutorial](/guides/cloudflare-d1).

</TopBlock>

## What is Cloudflare D1?

D1 is Cloudflare's native serverless database and was initially [launched in 2022](https://blog.cloudflare.com/introducing-d1/). It's based on SQLite and can be used when deploying applications with Cloudflare.
D1 is Cloudflare's native serverless database and was initially [launched in 2022](https://blog.cloudflare.com/introducing-d1/). It's based on SQLite and can be used when deploying applications with Cloudflare Workers.

Following Cloudflare's principles of geographic distribution and bringing compute and data closer to application users, D1 supports automatic read-replication. It dynamically manages the number of database instances and locations of read-only replicas based on how many queries a database is getting, and from where.

Expand All @@ -38,28 +34,133 @@ Many aspects of using Prisma ORM with D1 are just like using Prisma ORM with any

There are a number of differences between D1 and SQLite to consider. You should be aware of the following when deciding to use D1 and Prisma ORM:

- **Making schema changes**. As of [v6.6.0](https://pris.ly/release/6.6.0) and with a `prisma.config.ts` file, you can use `prisma db push`. However, if you prefer a Cloudflare first approach, you can use D1's [migration system](https://developers.cloudflare.com/d1/reference/migrations/) and the [`prisma migrate diff`](/orm/reference/prisma-cli-reference#migrate-diff) command for your migration workflows. See the [Schema migrations with Prisma ORM on D1](#schema-migrations-with-prisma-orm-on-d1) section below for more information.
- **Local and remote D1 (SQLite) databases**. Cloudflare provides local and remote versions of D1. The [local](https://developers.cloudflare.com/d1/build-with-d1/local-development/) version is managed using the `--local` option of the `wrangler d1` CLI and is located in `.wrangler/state`. The [remote](https://developers.cloudflare.com/d1/build-with-d1/remote-development/) version is managed by Cloudflare and is accessed via HTTP.
- **Making schema changes**. Since D1 uses HTTP to connect to the remote database, this makes it incompatible with some commands of Prisma Migrate, like `prisma migrate dev`. However, you can use D1's [migration system](https://developers.cloudflare.com/d1/reference/migrations/) and the [`prisma migrate diff`](/orm/reference/prisma-cli-reference#migrate-diff) command for your migration workflows. See the [Migration workflows](#migration-workflows) below for more information.

## How to connect to D1 in Cloudflare Workers or Cloudflare Pages

When using Prisma ORM with D1, you need to use the `sqlite` database provider and the `@prisma/adapter-d1` [driver adapter](/orm/overview/databases/database-drivers#driver-adapters).

If you want to deploy a Cloudflare Worker with D1 and Prisma ORM, follow these [step-by-step instructions](/guides/cloudflare-d1).

## Migration workflows
## Schema migrations with Prisma ORM on D1

You can use two approaches for migrating your database schema with Prisma ORM and D1:
- Using `prisma db push` via a driver adapter in `prisma.config.ts`
- Using the Wrangler CLI

### Using Prisma Migrate via a driver adapter in `prisma.config.ts` (Early Access)

:::warning

This functionality has been introduced in [Early Access](/orm/more/releases#early-access) in [v6.6.0](https://pris.ly/release/6.6.0) and supports the following commands:

- `prisma db push`
- `prisma db pull`
- `prisma migrate diff`

Other commands like `prisma migrate dev` and `prisma migrate deploy` will be added soon.

:::

#### 1. Install the Prisma D1 driver adapter

Run this command in your terminal:

```terminal
npm install @prisma/adapter-d1
```

#### 2. Set environment variables

In order to set up the D1 adapter, you'll need to add a few secrets to a `.env` file:

- `CLOUDFLARE_ACCOUNT_ID`: Your Cloudflare account ID, fetched via `npx wrangler whoami`.
- `CLOUDFLARE_DATABASE_ID`: Retrieved during D1 database creation. If you have an existing D1 database, you can use `npx wrangler d1 list` and `npx wrangler d1 info <database_name>` to get the ID.
- `CLOUDFLARE_D1_TOKEN`: This API token is used by Prisma ORM to communicate with your D1 instance directly. To create it, follow these steps:
1. Visit https://dash.cloudflare.com/profile/api-tokens
2. Click **Create Token**
3. Click **Custom token** template
4. Fill out the template: Make sure you use a recognizable name and add the **Account / D1 / Edit** permission.
5. Click **Continue to summary** and then **Create Token**.

You can then add these to your `.env` file or use them directly if they are stored in a different secret store:

```bash file=.env
CLOUDFLARE_ACCOUNT_ID="0773..."
CLOUDFLARE_DATABASE_ID="01f30366-..."
CLOUDFLARE_D1_TOKEN="F8Cg..."
```

#### 3. Set up Prisma Config file

Cloudflare D1 comes with its own [migration system](https://developers.cloudflare.com/d1/reference/migrations/). We recommend that you use this migration system via the `wrangler d1 migrations` command to create and manage migration files on your file system.
Make sure that you have a [`prisma.config.ts`](/orm/reference/prisma-config-reference) file for your project. Then, set up the [migration driver adapter](/orm/reference/prisma-config-reference#migrationadapter) to reference D1:

```ts file=prisma.config.ts
import path from 'node:path'
import type { PrismaConfig } from 'prisma'
import { PrismaD1HTTP } from '@prisma/adapter-d1'

// import your .env file
import 'dotenv/config'

type Env = {
CLOUDFLARE_D1_TOKEN: string
CLOUDFLARE_ACCOUNT_ID: string
CLOUDFLARE_DATABASE_ID: string
}

export default {
earlyAccess: true,
schema: path.join('prisma', 'schema.prisma'),

// add-start
migrate: {
async adapter(env) {
return new PrismaD1HTTP({
CLOUDFLARE_D1_TOKEN: env.CLOUDFLARE_D1_TOKEN,
CLOUDFLARE_ACCOUNT_ID: env.CLOUDFLARE_ACCOUNT_ID,
CLOUDFLARE_DATABASE_ID: env.CLOUDFLARE_DATABASE_ID,
})
},
},
// add-end
} satisfies PrismaConfig<Env>
```

#### 4. Migrate your database

Prisma Migrate now will run migrations against your remote D1 database based on the configuration provided in `prisma.config.ts`.

To update the remote schema with this workflow, run the following command:

```terminal
npx prisma db push
```

:::note

Note that for querying the database, you keep using the `PrismaD1` driver adapter from the `@prisma/adapter-d1` package:

```ts
import { PrismaD1HTTP } from '@prisma/adapter-d1'
```

:::

### Using the Wrangler CLI

Cloudflare D1 comes with its own [migration system](https://developers.cloudflare.com/d1/reference/migrations/). While we recommend that you use the [native Prisma Migrate workflow](#using-prisma-migrate-via-a-driver-adapter-in-prismaconfigts-early-access), this migration system via the `wrangler d1 migrations` command is available.

This command doesn't help you in figuring out the SQL statements for creating your database schema that need to be put _inside_ of these migration files though. If you want to query your database using Prisma Client, it's important that your database schema maps to your Prisma schema, this is why it's recommended to generate the SQL statements from your Prisma schema.

When using D1, you can use the [`prisma migrate diff`](/orm/reference/prisma-cli-reference#migrate-diff) command for that purpose.

### Creating an initial migration
#### Creating an initial migration

The workflow for creating an initial migration looks as follows. Assume you have a fresh D1 instance without any tables.

#### 1. Update your Prisma data model
##### 1. Update your Prisma data model

This is your initial version of the Prisma schema that you want to map to your D1 instance:

Expand All @@ -71,7 +172,7 @@ model User {
}
```

#### 2. Create migration file using `wrangler` CLI
##### 2. Create migration file using `wrangler` CLI

Next, you need to create the migration file using the [`wrangler d1 migrations create`](https://developers.cloudflare.com/workers/wrangler/commands/#migrations-create) command:

Expand All @@ -90,7 +191,7 @@ migrations/

However, before you can apply the migration to your D1 instance, you actually need to put a SQL statement into the currently empty `0001_create_user_table.sql` file.

#### 3. Generate SQL statements using `prisma migrate diff`
##### 3. Generate SQL statements using `prisma migrate diff`

To generate the initial SQL statement, you can use the `prisma migrate diff` command which compares to _schemas_ (via its `--to-X` and `--from-X` options) and generates the steps that are needed to "evolve" from one to the other. These schemas can be either Prisma or SQL schemas.

Expand Down Expand Up @@ -125,7 +226,7 @@ CREATE TABLE "User" (
CREATE UNIQUE INDEX "User_email_key" ON "User"("email");
```

#### 4. Execute the migration using `wrangler d1 migrations apply`
##### 4. Execute the migration using `wrangler d1 migrations apply`

Finally, you can apply the migration against your D1 instances.

Expand All @@ -141,11 +242,11 @@ For the **remote** instance, run:
npx wrangler d1 migrations apply __YOUR_DATABASE_NAME__ --remote
```

### Evolve your schema with further migrations
#### Evolve your schema with further migrations

For any further migrations, you can use the same workflow but instead of using `--from-empty`, you'll need to use `--from-local-d1` because your source schema for the `prisma migrate diff` command now is the current schema of that local D1 instance, while the target remains your (then updated) Prisma schema.

#### 1. Update your Prisma data model
##### 1. Update your Prisma data model

Assume you have updated your Prisma schema with another model:

Expand All @@ -165,7 +266,7 @@ model Post {
}
```

#### 2. Create migration file using `wrangler` CLI
##### 2. Create migration file using `wrangler` CLI

Like before, you first need to create the migration file:

Expand All @@ -183,7 +284,7 @@ migrations/

As before, you now need to put a SQL statement into the currently empty `0002_create_post_table.sql` file.

#### 3. Generate SQL statements using `prisma migrate diff`
##### 3. Generate SQL statements using `prisma migrate diff`

As explained above, you now need to use `--from-local-d1` instead of `--from-empty` to specify a source schema:

Expand Down Expand Up @@ -214,7 +315,7 @@ CREATE TABLE "Post" (
);
```

#### 4. Execute the migration using `wrangler d1 migrations apply`
##### 4. Execute the migration using `wrangler d1 migrations apply`

Finally, you can apply the migration against your D1 instances.

Expand All @@ -235,3 +336,7 @@ npx wrangler d1 migrations apply __YOUR_DATABASE_NAME__ --remote
### Transactions not supported

Cloudflare D1 currently does not support transactions (see the [open feature request](https://github.com/cloudflare/workers-sdk/issues/2733)). As a result, Prisma ORM does not support transactions for Cloudflare D1. When using Prisma's D1 adapter, implicit & explicit transactions will be ignored and run as individual queries, which breaks the guarantees of the ACID properties of transactions.

### Prisma Migrate only supports remote D1 databases

The Wrangler CLI can distinguish between local and remote D1 (i.e. SQLite) database instances via the `--local` and `--remote` options. This distinction is currently not available with the [native Prisma Migrate workflow](#using-prisma-migrate-via-a-driver-adapter-in-prismaconfigts-early-access).
Loading
Loading