# 🤓 Migrating from Knex to Prisma ORM

Migrating from Knex.js to Prisma involves several steps as Prisma is a full-fledged ORM with its own schema and migration system, while Knex is a SQL query builder.&#x20;

> <mark style="color:green;">**🎉 Migrating to Prisma removes a lot of boilerplate code from your projects, really simplifies your code and reduces the development time significantly!**</mark>  \ <mark style="color:orange;">**Prisma ORM makes developers a lot more productive! 🤓**</mark>\
> **Read more at** [**why prisma**](https://www.prisma.io/docs/orm/overview/introduction/why-prisma)**.**

Here's a high-level guide for a smooth migration:

1. **Adding Prisma in your existing project**

&#x20;No need to worry about how Prisma gets installed or configured in your project, the[GraphQL Rocket Generator](https://github.com/osstotalsoft/generator-graphql-rocket) will do everything for you and make you project "Prisma ready".&#x20;

2. **Prisma infrastructure overview**&#x20;

* First we have the `prisma` folder containing the `schema.prisma` file, where you will define your data models.
* Then we have the  `src/prisma` folder where would find some custom implementation for pagination or multi-tenancy and the most important, the `prisma()` function, that returns the instance of `PrismaClient`, which we will use everywhere and allows us to basically write the queries.

3. &#x20;**Database Connection**

* In `schema.prisma`, configure the database connection:

  ```prisma
  prismaCopy codedatasource db {
    provider = "sqlserver" # or your database provider (mysql, sqlite, etc.)
    url      = env("DATABASE_URL")
  }
  ```

Make sure the `DATABASE_URL` is set correctly in your `.env` file with your existing Knex database credentials. We usually use this pattern for database connection string configuration:

```properties
DATABASE_URL="sqlserver://{server}:{port};database={database};user={user};password={password};trustServerCertificate=true"
```

4. **Define Prisma Models**

* In Prisma, you define models to represent your tables. Prisma's models are more declarative compared to Knex migrations. Start by replicating your existing Knex schema into Prisma models. Here is an example for a `users` table:

  ```prisma
  prismaCopy codemodel User {
    id        Int      @id @default(autoincrement())
    name      String
    email     String   @unique
    posts     Post[]
  }
  ```

Prisma offers a rich set of features like relations, field constraints, and defaults. Carefully match these with your existing schema.

5. &#x20;**Introspect Existing Database (Optional)**

* If your database already exists, you can use Prisma's introspection tool to generate the schema:

  ```bash
  npx prisma db pull
  ```

This command introspects your database and generates Prisma models based on your current schema.

6. **Replace Knex Queries with Prisma Client**

* After setting up the schema, replace Knex queries with Prisma's type-safe client. For example, a Knex query like:

  ```js
  knex('users').select('*').where({ id: 1 })
  ```

Would become:&#x20;

```javascript
const user = await prisma.user.findUnique({ where: { id: 1 }, });
```

> <mark style="color:purple;">**📍Prisma queries should directly be written inside the GraphQL resolvers. No need for the old data-sources extra files.**</mark>\ <mark style="color:purple;">**📍**</mark><mark style="color:green;">**Prisma automatically handles the**</mark><mark style="color:green;">**&#x20;**</mark><mark style="color:green;">**`n+1 problem`**</mark><mark style="color:green;">**&#x20;**</mark><mark style="color:green;">**so the old dataloaders we had to write for knex will be removed! 🎉 Read more about it**</mark> [**here**](https://www.prisma.io/docs/orm/prisma-client/queries/query-optimization-performance#solving-the-n1-problem)<mark style="color:green;">**.**</mark>

You will notice that after migrating a feature to Prisma a few folders will be useless and must be removed. here is the full list of files and folders related to Knex that must be deleted after migrating to Prisma:

* /src/db/
* /middleware/db/
* &#x20;/messaging/middleware/dbInstance.js
* /startup/dataLoaders.js
* &#x20;/features/common/dbGenerators.js
* /features/\<your-feature>/dataLoaders.js
* /features/\<your-feature>/dataSources/\<old DataSource files>
* /utils/sqlDataSource.js

7. &#x20;**Handling Data Migrations**

* Prisma Migrate can be used for future data migrations. Create migration files, then run `prisma migrate dev` or `prisma migrate deploy` to apply them. You can also handle more complex migrations by writing custom SQL or scripts as needed.

8. **Unsupported Features**

* Prisma may not support certain SQL-level features you used with Knex (like raw SQL queries, partial indexes, or database-specific features). You can either replace or modify Prisma-generated SQL or use `prisma.$queryRaw` for raw SQL queries where necessary.

9. &#x20;**Testing and Deployment**

* Test the migration in a staging environment to ensure everything works as expected, then apply it to production using:

  ```bash
  prisma migrate deploy
  ```

This migration process ensures that you move to Prisma's more modern ORM capabilities while retaining control over your schema and data. Full guides and examples can be found on the ([Prisma](https://www.prisma.io/docs/orm/prisma-migrate/getting-started))


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://totalsoft.gitbook.io/graphql-rocket-generator/migrating-from-knex-to-prisma-orm.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
