# Drizzle (/docs/guides/switch-to-prisma-orm/from-drizzle)

Location: Guides > Switch to Prisma ORM > Drizzle

Introduction [#introduction]

This guide shows you how to migrate your application from Drizzle to Prisma ORM. We'll use a sample project based off of the [Drizzle Next.js example](https://orm.drizzle.team/docs/tutorials/drizzle-nextjs-neon) to demonstrate the migration steps. You can find the example used for this guide on [GitHub](https://github.com/prisma/migrate-from-drizzle-to-prisma).

You can learn how Prisma ORM compares to Drizzle on the [Prisma ORM vs Drizzle](/orm/more/comparisons/prisma-and-drizzle) page.

Prerequisites [#prerequisites]

Before starting this guide, make sure you have:

* A Drizzle project you want to migrate
* Node.js installed (version 16 or higher)
* PostgreSQL or another supported database
* Basic familiarity with Drizzle and Next.js

> [!NOTE]
> this migration guide uses Neon PostgreSQL as the example database, but it equally applies to any other relational database that are [supported by Prisma ORM](/orm/reference/supported-databases).

You can learn how Prisma ORM compares to Drizzle on the [Prisma ORM vs Drizzle](/orm/more/comparisons/prisma-and-drizzle) page.

Overview of the migration process [#overview-of-the-migration-process]

Note that the steps for migrating from Drizzle to Prisma ORM are always the same, no matter what kind of application or API layer you're building:

1. Install the Prisma CLI
2. Introspect your database
3. Create a baseline migration
4. Install Prisma Client
5. Gradually replace your Drizzle queries with Prisma Client

These steps apply, no matter if you're building a REST API (e.g. with Express, koa or NestJS), a GraphQL API (e.g. with Apollo Server, TypeGraphQL or Nexus) or any other kind of application that uses Drizzle for database access.

Prisma ORM lends itself really well for **incremental adoption**. This means, you don't have to migrate your entire project from Drizzle to Prisma ORM at once, but rather you can *step-by-step* move your database queries from Drizzle to Prisma ORM.

Step 1. Install the Prisma CLI [#step-1-install-the-prisma-cli]

The first step to adopt Prisma ORM is to [install the Prisma CLI](/orm/reference/prisma-cli-reference) in your project:

  

#### npm

```bash
npm install prisma @types/pg --save-dev
npm install @prisma/client @prisma/adapter-pg pg
```

#### pnpm

```bash
pnpm add prisma @types/pg --save-dev
pnpm add @prisma/client @prisma/adapter-pg pg
```

#### yarn

```bash
yarn add prisma @types/pg --dev
yarn add @prisma/client @prisma/adapter-pg pg
```

#### bun

```bash
bun add prisma @types/pg --dev
bun add @prisma/client @prisma/adapter-pg pg
```

> [!NOTE]
> If you are using a different database provider (MySQL, SQL Server, SQLite), install the corresponding driver adapter package instead of `@prisma/adapter-pg`. For more information, see [Database drivers](/orm/core-concepts/supported-databases/database-drivers).

Step 2. Introspect your database [#step-2-introspect-your-database]

2.1. Set up Prisma ORM [#21-set-up-prisma-orm]

Before you can introspect your database, you need to set up your [Prisma schema](/orm/prisma-schema/overview) and connect Prisma to your database. Run the following command in the root of your project to create a basic Prisma schema file:

  

#### npm

```bash
npx prisma init --output ../generated/prisma
```

#### pnpm

```bash
pnpm dlx prisma init --output ../generated/prisma
```

#### yarn

```bash
yarn dlx prisma init --output ../generated/prisma
```

#### bun

```bash
bunx --bun prisma init --output ../generated/prisma
```

This command created a new directory called `prisma` with the following files for you:

* `schema.prisma`: Your Prisma schema that specifies your database connection and models
* `.env`: A [`dotenv`](https://github.com/motdotla/dotenv) to configure your database connection URL as an environment variable

> [!NOTE]
> You may already have a `.env` file. If so, the `prisma init` command will append lines to it rather than creating a new file.

The Prisma schema currently looks as follows:

```prisma title="prisma/schema.prisma" showLineNumbers
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

datasource db {
  provider = "postgresql"
}

generator client {
  provider = "prisma-client"
  output   = "./generated/prisma"
}
```

> [!NOTE]
> If you're using VS Code, be sure to install the [Prisma VS Code extension](https://marketplace.visualstudio.com/items?itemName=Prisma.prisma) for syntax highlighting, formatting, auto-completion and a lot more cool features.

2.2. Connect your database [#22-connect-your-database]

If you're not using PostgreSQL, you need to adjust the `provider` field on the `datasource` block to the database you currently use:

  

#### PostgreSQL

```prisma title="schema.prisma" showLineNumbers 
datasource db {
  provider = "postgresql"
}
```

#### MySQL

```prisma title="schema.prisma" showLineNumbers 
datasource db {
  provider = "mysql"
}
```

#### Microsoft SQL Server

```prisma title="schema.prisma" showLineNumbers 
datasource db {
  provider = "sqlserver"
}
```

#### SQLite

```prisma title="schema.prisma" showLineNumbers 
datasource db {
  provider = "sqlite"
}
```

Once that's done, you can configure your [database connection URL](/orm/reference/connection-urls) in the `.env` file. Drizzle and Prisma ORM use the same format for connection URLs, so your existing connection URL should work fine.

2.3. Configure Prisma [#23-configure-prisma]

Create a `prisma.config.ts` file in the root of your project with the following content:

```typescript title="prisma.config.ts"
import "dotenv/config";
import { defineConfig, env } from "prisma/config";

export default defineConfig({
  schema: "prisma/schema.prisma",
  migrations: {
    path: "prisma/migrations",
  },
  datasource: {
    url: env("DATABASE_URL"),
  },
});
```

> [!NOTE]
> You'll need to install the `dotenv` package to load environment variables. If you haven't already, install it using your package manager:
> 
> 
>   
> 
>   #### npm

>     ```bash
>     npm install dotenv
>     ```
>
> 
>   #### pnpm

>     ```bash
>     pnpm add dotenv
>     ```
>
> 
>   #### yarn

>     ```bash
>     yarn add dotenv
>     ```
>
> 
>   #### bun

>     ```bash
>     bun add dotenv
>     ```
>
> 

2.4. Introspect your database using Prisma ORM [#24-introspect-your-database-using-prisma-orm]

With your connection URL in place, you can [introspect](/orm/prisma-schema/introspection) your database to generate your Prisma models:

  

#### npm

```bash
npx prisma db pull
```

#### pnpm

```bash
pnpm dlx prisma db pull
```

#### yarn

```bash
yarn dlx prisma db pull
```

#### bun

```bash
bunx --bun prisma db pull
```

If you're using the [sample project](https://github.com/prisma/migrate-from-drizzle-to-prisma) the following model would be created:

```prisma title="prisma/schema.prisma" showLineNumbers
model todo {
  id   Int     @id
  text String
  done Boolean @default(false)
}
```

The generated Prisma model represents a database table. Prisma models are the foundation for your programmatic Prisma Client API which allows you to send queries to your database.

2.5. Create a baseline migration [#25-create-a-baseline-migration]

To continue using Prisma Migrate to evolve your database schema, you will need to [baseline your database](/orm/prisma-migrate/getting-started).

First, create a `migrations` directory and add a directory inside with your preferred name for the migration. In this example, we will use `0_init` as the migration name:

```bash
mkdir -p prisma/migrations/0_init
```

Next, generate the migration file with `prisma migrate diff`. Use the following arguments:

* `--from-empty`: assumes the data model you're migrating from is empty
* `--to-schema`: the current database state using the URL in the `datasource` block
* `--script`: output a SQL script

  

#### npm

```bash
npx prisma migrate diff --from-empty --to-schema prisma/schema.prisma --script > prisma/migrations/0_init/migration.sql
```

#### pnpm

```bash
pnpm dlx prisma migrate diff --from-empty --to-schema prisma/schema.prisma --script > prisma/migrations/0_init/migration.sql
```

#### yarn

```bash
yarn dlx prisma migrate diff --from-empty --to-schema prisma/schema.prisma --script > prisma/migrations/0_init/migration.sql
```

#### bun

```bash
bunx --bun prisma migrate diff --from-empty --to-schema prisma/schema.prisma --script > prisma/migrations/0_init/migration.sql
```

Review the generated migration to ensure everything is correct.

Next, mark the migration as applied using `prisma migrate resolve` with the `--applied` argument.

  

#### npm

```bash
npx prisma migrate resolve --applied 0_init
```

#### pnpm

```bash
pnpm dlx prisma migrate resolve --applied 0_init
```

#### yarn

```bash
yarn dlx prisma migrate resolve --applied 0_init
```

#### bun

```bash
bunx --bun prisma migrate resolve --applied 0_init
```

The command will mark `0_init` as applied by adding it to the `_prisma_migrations` table.

You now have a baseline for your current database schema. To make further changes to your database schema, you can update your Prisma schema and use `prisma migrate dev` to apply the changes to your database.

2.6. Adjust the Prisma schema (optional) [#26-adjust-the-prisma-schema-optional]

Models that are generated via introspection currently *exactly* map to your database tables. In this section, you'll learn how you can adjust the naming of the Prisma models to adhere to [Prisma ORM's naming conventions](/orm/reference/prisma-schema-reference#naming-conventions).

All of these adjustment are entirely optional and you are free to skip to the next step already if you don't want to adjust anything for now. You can go back and make the adjustments at any later point.

As opposed to the current camelCase notation of Drizzle models, Prisma ORM's naming conventions are:

* PascalCase for model names
* camelCase for field names

You can adjust the naming by *mapping* the Prisma model and field names to the existing table and column names in the underlying database using `@@map` and `@map`.

Here's an example on how you could modify the model above:

```prisma title="prisma/schema.prisma" showLineNumbers
model Todo {
  id   Int     @id
  text String
  done Boolean @default(false)

  @@map("todo")
}
```

Step 3. Generate Prisma Client [#step-3-generate-prisma-client]

Now that you have installed Prisma Client in Step 1, you need to run `generate` in order to have your schema reflected in TypeScript types and autocomplete.

  

#### npm

```bash
npx prisma generate
```

#### pnpm

```bash
pnpm dlx prisma generate
```

#### yarn

```bash
yarn dlx prisma generate
```

#### bun

```bash
bunx --bun prisma generate
```

Step 4. Replace your Drizzle queries with Prisma Client [#step-4-replace-your-drizzle-queries-with-prisma-client]

In this section, we'll show a few sample queries that are being migrated from Drizzle to Prisma Client based on the example routes from the sample REST API project. For a comprehensive overview of how the Prisma Client API differs from Drizzle, check out the [comparison page](/orm/more/comparisons/prisma-and-drizzle#).

First, to set up the `PrismaClient` instance that you'll use to send database queries from the various route handlers. Create a new file named `prisma.ts` in the `db` directory:

```bash copy
touch db/prisma.ts
```

Now, instantiate `PrismaClient` and export it from the file so you can use it in your route handlers later:

```ts copy title="db/prisma.ts" showLineNumbers
import { PrismaClient } from "../generated/prisma/client";
import { PrismaPg } from "@prisma/adapter-pg";
import "dotenv/config";

const adapter = new PrismaPg({
  connectionString: process.env.DATABASE_URL,
});

export const prisma = new PrismaClient({
  adapter,
});
```

4.1. Replacing getData queries [#41-replacing-getdata-queries]

The fullstack Next.js app has several `actions` including `getData`.

The `getData` action is currently implemented as follows:

```ts title="actions/todoActions.ts" showLineNumbers
import db from "@/db/drizzle";
import { todo } from "@/db/schema";

export const getData = async () => {
  const data = await db.select().from(todo);
  return data;
};
```

Here is the same action implemented using Prisma Client:

```ts title="src/controllers/FeedAction.ts" showLineNumbers
import { prisma } from "@/db/prisma";

export const getData = async () => {
  const data = await prisma.todo.findMany();
  return data;
};
```

4.2. Replacing queries in POST requests [#42-replacing-queries-in-post-requests]

The [sample project](https://github.com/prisma/migrate-from-drizzle-to-prisma) has four actions that are utilized during `POST` requests:

* `addTodo`: Creates a new `Todo` record
* `deleteTodo`: Deletes an existing `Todo` record
* `toggleTodo`: Toggles the boolean `done` field on an existing `Todo` record
* `editTodo`: Edits the `text` field on an existing `Todo` record

addTodo [#addtodo]

The `addTodo` action is currently implemented as follows:

```ts title="actions/todoActions.ts" showLineNumbers
import { revalidatePath } from "next/cache";

import db from "@/db/drizzle";
import { todo } from "@/db/schema";

export const addTodo = async (id: number, text: string) => {
  await db.insert(todo).values({
    id: id,
    text: text,
  });
  revalidatePath("/");
};
```

Here is the same action implemented using Prisma Client:

```ts title="actions/todoActions.ts" showLineNumbers
import { revalidatePath } from "next/cache";

import { prisma } from "@/db/prisma";

export const addTodo = async (id: number, text: string) => {
  await prisma.todo.create({
    data: { id, text },
  });
  revalidatePath("/");
};
```

deleteTodo [#deletetodo]

The `deleteTodo` action is currently implemented as follows:

```ts title="actions/todoActions.ts" showLineNumbers
import { eq } from "drizzle-orm";
import { revalidatePath } from "next/cache";

import db from "@/db/drizzle";
import { todo } from "@/db/schema";

export const deleteTodo = async (id: number) => {
  await db.delete(todo).where(eq(todo.id, id));
  revalidatePath("/");
};
```

Here is the same action implemented using Prisma Client:

```ts title="actions/todoActions.ts" showLineNumbers
import { revalidatePath } from "next/cache";

import { prisma } from "@/db/prisma";

export const deleteTodo = async (id: number) => {
  await prisma.todo.delete({ where: { id } });
  revalidatePath("/");
};
```

toggleTodo [#toggletodo]

The `ToggleTodo` action is currently implemented as follows:

```ts title="actions/todoActions.ts" showLineNumbers
import { eq, not } from "drizzle-orm";
import { revalidatePath } from "next/cache";

import db from "@/db/drizzle";
import { todo } from "@/db/schema";

export const toggleTodo = async (id: number) => {
  await db
    .update(todo)
    .set({
      done: not(todo.done),
    })
    .where(eq(todo.id, id));
  revalidatePath("/");
};
```

Here is the same action implemented using Prisma Client:

```ts title="actions/todoActions.ts" showLineNumbers
import { revalidatePath } from "next/cache";

import { prisma } from "@/db/prisma";

export const toggleTodo = async (id: number) => {
  const todo = await prisma.todo.findUnique({ where: { id } });
  if (todo) {
    await prisma.todo.update({
      where: { id: todo.id },
      data: { done: !todo.done },
    });
    revalidatePath("/");
  }
};
```

Note that Prisma ORM does not have the ability to edit a boolean field "in place", so the record must be fetched before hand.

editTodo [#edittodo]

The `editTodo` action is currently implemented as follows:

```ts title="actions/todoActions.ts" showLineNumbers
import { eq } from "drizzle-orm";
import { revalidatePath } from "next/cache";

import db from "@/db/drizzle";
import { todo } from "@/db/schema";

export const editTodo = async (id: number, text: string) => {
  await db
    .update(todo)
    .set({
      text: text,
    })
    .where(eq(todo.id, id));

  revalidatePath("/");
};
```

Here is the same action implemented using Prisma Client:

```ts title="actions/todoActions.ts" showLineNumbers
import { revalidatePath } from "next/cache";

import { prisma } from "@/db/prisma";

export const editTodo = async (id: number, text: string) => {
  await prisma.todo.update({
    where: { id },
    data: { text },
  });
  revalidatePath("/");
};
```

More [#more]

Implicit many-to-many relations [#implicit-many-to-many-relations]

Unlike Drizzle, Prisma ORM allows you to [model many-to-many relations *implicitly*](/orm/prisma-schema/data-model/relations/many-to-many-relations#implicit-many-to-many-relations). That is, a many-to-many relation where you do not have to manage the [relation table](/orm/prisma-schema/data-model/relations/many-to-many-relations#relation-table-conventions) (also sometimes called JOIN table) *explicitly* in your schema. Here is an example comparing Drizzle with Prisma ORM:

```ts title="schema.ts"
import { boolean, integer, pgTable, serial, text } from "drizzle-orm/pg-core";

export const posts = pgTable("post", {
  id: serial("serial").primaryKey(),
  title: text("title").notNull(),
  content: text("content"),
  published: boolean("published").default(false).notNull(),
});

export const categories = pgTable("category", {
  id: serial("serial").primaryKey(),
  name: text("name").notNull(),
});

export const postsToCategories = pgTable("posts_to_categories", {
  postId: integer("post_id")
    .notNull()
    .references(() => users.id),
  categoryId: integer("category_id")
    .notNull()
    .references(() => chatGroups.id),
});
```

This schema is equivalent to the following Prisma schema:

```prisma title="schema.prisma"
model Post {
  id                Int                @id @default(autoincrement())
  title             String
  content           String?
  published         Boolean            @default(false)
  postsToCategories PostToCategories[]

  @@map("post")
}

model Category {
  id                Int                @id @default(autoincrement())
  name              String
  postsToCategories PostToCategories[]

  @@map("category")
}

model PostToCategories {
  postId     Int
  categoryId Int
  category   Category @relation(fields: [categoryId], references: [id])
  post       Post     @relation(fields: [postId], references: [id])

  @@id([postId, categoryId])
  @@index([postId])
  @@index([categoryId])
  @@map("posts_to_categories")
}
```

In this Prisma schema, the many-to-many relation is modeled *explicitly* via the relation table `PostToCategories`.

By instead adhering to the conventions for Prisma ORM relation tables, the relation could look as follows:

```prisma title="schema.prisma" showLineNumbers
model Post {
  id         Int        @id @default(autoincrement())
  title      String
  content    String?
  published  Boolean    @default(false)
  categories Category[]
}

model Category {
  id    Int    @id @default(autoincrement())
  name  String
  posts Post[]
}
```

This would also result in a more ergonomic and less verbose Prisma Client API to modify the records in this relation, because you have a direct path from `Post` to `Category` (and the other way around) instead of needing to traverse the `PostToCategories` model first.

> [!WARNING]
> If your database provider requires tables to have primary keys then you have to use explicit syntax, and manually create the join model with a primary key. This is because relation tables (JOIN tables) created by Prisma ORM (expressed via `@relation`) for many-to-many relations using implicit syntax do not have primary keys.

## Related pages

- [`Mongoose`](https://www.prisma.io/docs/guides/switch-to-prisma-orm/from-mongoose): Learn how to migrate from Mongoose to Prisma ORM
- [`SQL ORMs`](https://www.prisma.io/docs/guides/switch-to-prisma-orm/from-sql-orms): Learn how to migrate from Sequelize or TypeORM to Prisma ORM