r/prismaorm • • Oct 05 '24

A better Prisma down migration flow for development

15 Upvotes

The native Prisma migration system has limited rollback / down migration functionality:

  • A separate command is required to create a down migration.

  • It can only roll back a migration when the migration fails.

Here is the current Prisma documentation about what's available for down migration.

Of course, down migrations should be avoided in production. However, I think it is a common operation during development. When working on database schema change, one can seldom get everything right the first time. And it is undesirable to create multiple migrations for a single schema change, or to manually edit the migration files and database schema to fix the mistake.

In my opinion, the golden migration experience is from Rails, in which one can always create an up migration and a down migration for each schema change. When a mistake is made, just rollback the last migration and write a new one.

I created two scripts to provide a similar dev experience for Prisma. The template repo is here: tuliren/prisma-template. The main scripts are in the bin directory.

The process is as follows:

  • Run the create-migration.sh script to generate a migration.

    • The normal migration.sql file is created by prisma migrate dev --create-only.

    • A down.sql file is created in the same directory by migrate diff.

  • Apply the migration to the database as usual.

  • If anything is not right, run the rollback-migration.sh script to completely revert the migration.

    • The down.sql file is run to revert the database schema changes.

    • The migration record in _prisma_migrations is deleted.

    • The reverted migration files are deleted.

  • Update the schema and start over.

TL;DR

The two scripts always create a down migration file for every migration, and can completely revert an applied migration.

Let me know if this is helpful. I am also curious how other Prisma users deal with down migration during development.


r/prismaorm • • Apr 28 '25

I made an internal tool for slow query detection in prisma+postgres, would it be useful for anyone here?

10 Upvotes

tldr: I made an internal tool for slow query detection, and am looking for validation of whether it is worth building it out as a tool for others.

Ever so often, the site goes down, and all hell breaks loose. When there is problems with the database, everything stops working, and all eyes are on me — the dev who volunteered to be the db guy — to fix it.

In the beginning, I didn't know a lot about postgres or databases, but I have learnt a bunch the last couple of years. From firefighting situations, I have done a few observations:

  • Often, 1 or 2 queries take 80% of the db load. DB problems are often triggered by a single bad query

  • When there is a bad query, throwing more money on the problem doesn't solve the issue

  • Fixing the bad query — often by re-writing it — is the only way to fix the problem

After a while, I learnt how to use `pg_stat_statements`. By querying SELECT * FROM pg_stat_statements you get an accurate view of the most demanding queries:

querymean (total)
SELECT col1, col2 from ...324ms (5hr 34min)
SELECT * from table_2 ...50ms (3hr)

I look at the slowest most problematic query, and go rewrite it in code. It works very well.

However, in some cases, it was hard to know where in code the query came from, because Prisma generates the SQL and we are not writing the queries by hand ourselves. One query we had was related to "table1", but we were interacting with "table1" through prisma from multiple different places in code, thus making debugging harder. Sometimes we removed or rewrote the query in several different places in code until finally figuring out the root bad query.

After a while, I started working on a tool to make my own life easier:

  • a service to ingest OpenTelemetry traces with ClickHouse

  • a simple web UI that queries `pg_stat_statements`

  • cross-check OpenTelemetry traces, and correlate the query from with the actual functions that were called in code

It looked like this (in a web UI):

querymean (total)where?
SELECT col1, col2 from ...324ms (5hr 34min)prisma.users.find(... in lib/user.ts:435
SELECT * from table_2 ...50ms (3hr)prisma.raw(... in lib/auth.ts:32

At the core, it is very similar to `pg_stat_statements`, but it adds: 1) more info about where a query originates and 2) has a web UI (makes it simpler for any dev to monitor)

Every time we had a problem with the DB, I would go to the tool, look at the query at the top. Instantly see where it was defined in code and which PR caused it. Go to my code editor. Push a fix.

This tool has been useful for us, and now I am considering making this into a tool that more people can use.

Would it would be useful for any of you?

If I go develop this tool, I would also like to add slack alerts, automatic EXPLAINS, and LLM suggestions for improvements.

Imagine the Slack alert:

The PR [pr title] by @ bob123 introduced a new query (prisma.users.find(xxx)) in `lib/user.ts` that now takes more than 55% of the DB load!

----

Do you have similar experiences with slow queries in postgres? Would a tool like this be useful in your dev team?


r/prismaorm • • Apr 25 '25

I get an error when I initialize Prisma like they do in the docs.

5 Upvotes

Hi, I have a question. I'm new to prisma.

The documentation suggests for Prisma that you import it in your index.ts file like this:

import { PrismaClient } from "@prisma/client"
const prisma = new PrismaClient()

But when I run the index.ts this doesn't work. It says:

Error: @prisma/client did not initialize yet. Please run "prisma generate" and try to import it again.

this is even after I used npx prisma generate. However, it works when I do it like this:

import { PrismaClient } from "./generated/prisma"
const prisma = new PrismaClient()

Is this OK to do? Why doesn't it work when I do it like the documentation suggests it?


r/prismaorm • • Apr 21 '21

prisma is production ready now

Thumbnail
prisma.io
5 Upvotes

r/prismaorm • • Oct 30 '24

Repository Pattern for Prisma

4 Upvotes

Hey Prisma Community,

I’m excited to share a library I’ve been working on to bring a clean, strongly-typed implementation of the Repository Pattern to Prisma – PrismaVault! 🎉 The goal is to consolidate data access logic, centralizing database interactions into well-defined repositories to make large Prisma codebases more maintainable and resilient.

Why PrismaVault?

If you've ever felt the need to centralize database operations or have encountered pain points with scattered data logic across services, this might resonate. PrismaVault is designed to:

  1. Encapsulate Database Logic: Reduces coupling between your service and data layers by exposing high-level repository methods, so services don’t directly interact with Prisma’s API.

  2. Return Translated Entities: Favors returning custom data structures (DTOs) rather than raw Prisma records, giving you a more flexible interface between layers.

  3. Promote Centralization: Consolidates all data operations within repository classes, keeping database logic organized and making it easier to refactor or add transactional workflows in one place.

This has been a recurring topic for the Prisma community (reference GitHub issue), and it's definitely been a pain point in some of our own projects.

Try PrismaVault

I’d love for the community to give it a try and let me know your thoughts, issues, or suggestions! You can find the library and documentation here:

🔗 GitHub Repository: PrismaVault – Repository Pattern for Prisma

Please feel free to open issues if you encounter any integration challenges or have ideas for improvement. Thanks in advance for any feedback.


r/prismaorm • • Apr 02 '25

A Gentle Introduction to Database Migrations in Prisma with Visuals | Wasp

Thumbnail
wasp.sh
3 Upvotes

r/prismaorm • • Mar 24 '25

Introduction to Prisma Tutorial

3 Upvotes

Hi, everyone

I made a simple introduction to Prisma Tutorial video series, feel free to check it out!

https://youtube.com/playlist?list=PLdQKeVpmXd7_7oatJw1tTeX_E6uQJ8A5D&si=eOktoBGRHQWF6oHr

I cover the following topics:

  • Creating Schemas

  • Creating Records

  • Reading Records

  • Updating Records

  • Deleting Records

  • Migrations

  • Selecting Fields

  • Filtering

  • Seeding

  • Sorting

The tutorial source code is all shared and each video has its own branch. I use Node, TypeScript, and sqlite.


r/prismaorm • • Jan 22 '25

Workaround for interval Type in Prisma

3 Upvotes

Prisma does not support the interval type. What are the possible workarounds I can use?


r/prismaorm • • Nov 13 '24

Help me understand the odd difference between findFirst and findUnique

3 Upvotes

I just spent 2-3 days banging my head against an intermittent bug in our production web app. Now, I generally consider that there are two types of bugs that take this long to fix:

  • Type 1 bugs: Where it's something monumentally stupid, like a typo that is hard to find, and hence an easy to understand fix

  • Type 2 bugs: Where the root cause is nuanced, interesting, hard to debug, but in the end, you understood the root cause

This bug was new for me, a true type 3 situation where I eventually found the root cause and implemented a fix, however I have no idea why it worked.

In our authorization hook, we check a table to see if a user has verified their email. There are better ways to handle this most likely, but like implementing any kind of testing...that is a problem for another day ;) So anyway, the relevant table(s) have the following schema:

model EmailVerified {
  id        Int     @id @default(autoincrement())
  sub       String @unique
  verified Boolean
  verifiedAt DateTime @default(now())
}

model Annotation {
  id          Int          @id @default(autoincrement())
  sub         String
  projectId   Int
  shape       String
  createdAt   DateTime     @default(now())
  confidence  Float        @default(1)
  labelId     Int
  label       Label        @relation(fields: [labelId], references: [id], onDelete: Cascade)
  project     Project      @relation(fields: [projectId], references: [id], onDelete: Cascade)
  coordinates Coordinate[]
  modifiedAt DateTime @default(now())
}

Notice that the EmailVerified table has a unique constraint on the sub field, this is the user id. As the user can only appear in the table once, this made sense to add during the setup. Now, as we have a nice unique field, we can lookup the user id using the following prisma call.. or so i thought.

let cachedVerification = await prisma.emailVerified.findUnique({
  where: {
    sub: sub
  }
});

After some confusing debugging, we found that this call seemed to be causing a major hangup, which we only found by disabling the email verification part of the auth hook as part of a long campaign of commenting out all the code until it stops failing!

Eventually, I had the idea to replace the call with this, and the problem went away entirely:

let cachedVerification = await prisma.emailVerified.findFirst({
  where: {
    sub: sub
  }
});

But why did this make such a difference? I'm confident that at this point, some readers of this post will be smugly reaching for their mechanical keyboards, ready to roast my stupidity, and i invite you to please educate this idiot on what I did wrong.

In a vein effort to understand the issue, i started logging the queries executed for the above calls and found the following:

prisma.emailVerified.findFirst:

SELECT "public"."EmailVerified"."id", "public"."EmailVerified"."sub", "public"."EmailVerified"."verified", "public"."EmailVerified"."verifiedAt" FROM "public"."EmailVerified" WHERE "public"."EmailVerified"."sub" = $1 LIMIT $2 OFFSET $3

prisma.emailVerified.findUnique:

SELECT "public"."EmailVerified"."id", "public"."EmailVerified"."sub", "public"."EmailVerified"."verified", "public"."EmailVerified"."verifiedAt" FROM "public"."EmailVerified" WHERE ("public"."EmailVerified"."sub" = $1 AND 1=1) LIMIT $2 OFFSET $3

SELECT "public"."Annotation"."id", "public"."Annotation"."sub", "public"."Annotation"."projectId", "public"."Annotation"."shape", "public"."Annotation"."createdAt", "public"."Annotation"."confidence", "public"."Annotation"."labelId", "public"."Annotation"."modifiedAt" FROM "public"."Annotation" WHERE "public"."Annotation"."projectId" = $1 OFFSET $2

Like me, I hope at least some readers are wondering what the cinnamon toast fuck is going on. Why does a select query on a small table suddenly become a select on a busy table with hundreds of thousands of rows when FindUnique is used.

I am still scratching my head at this bug, and I would love to be roasted, in exchange for enlightenment.


r/prismaorm • • Nov 05 '24

React-admin is now officially listed as a Prisma integration!

3 Upvotes

Hi Prisma community!

We're excited to announce that React-admin is now officially listed as an integration on Prisma's website! 🥳

React-admin is an open-source, low-code framework that accelerates the development of admins, dashboards, and B2B apps. From authorization to internationalization, including theming and logs, all the usual requirements of B2B applications are covered by react-admin. And it supports Prisma!

We’re proud of this collaboration, bringing together two amazing open-source projects to offer even more value to the community. 🤝

If you're interested in react-admin or want to contribute, check out our GitHub page.

We'd love to hear your feedback!


r/prismaorm • • Sep 26 '24

Access Prisma Studio via Docker

3 Upvotes

hello devs i am having quite trouble in accessing prisma studio.. can anyone help me i have spin up the postgres and nextjs container and access it locally successfully. but have no idea how to access prisma studio : when you run bunx prisma studio.

services:
  nextjs:
    container_name: nextjs-0.1
    build:
      context: .
      dockerfile: Dockerfile.dev
    command: sh -c "bunx prisma db push && bun run dev --turbo"
    volumes:
      - .:/app
    env_file:
      - .env
    ports:
      - 3000:3000

    depends_on:
      postgresql:
        condition: service_healthy
  
  postgresql:
    container_name: postgresql-database
    image: postgres:15-alpine
    env_file:
      - .env
    healthcheck:
      test: ["CMD-SHELL", "pg_isready"]
      interval: 1m30s
      timeout: 30s
      retries: 5
      start_period: 30s
    ports:
      - 5432:5432
    expose:
      - 5432
    volumes:
      - pgvolume:/var/lib/postgresql/data

volumes:
  pgvolume:

r/prismaorm • • Sep 04 '24

What's wrong with all the Prisma GitHub issues? 3,021 opening now!

3 Upvotes

r/prismaorm • • Feb 26 '23

Need Some Help in Schema

3 Upvotes

i want i unique id field in my schema which will be like P00001 and the number in the end will be the id itself with default as autoincrement(). can i achieve this using prisma orm on schema level?

PS - i am using mysql and nodejs and latest version of prisma


r/prismaorm • • Apr 26 '25

Has any one deployed Nuxt + Prisma?

Thumbnail reddit.com
2 Upvotes

r/prismaorm • • Apr 24 '25

Prisma in 14mins | basic implementation of Primsa using express js, and ...

Thumbnail
youtube.com
2 Upvotes

This is the video I made on installing and integrating Prisma orm with mysql check it out


r/prismaorm • • Apr 20 '25

Is Prisma pulse service not available now as not able to use stream function which pulse provided previously. Help me what should I do?

2 Upvotes

Do give alternative to it if not available then.


r/prismaorm • • Mar 11 '25

How to build an admin panel with react-admin & Prisma

2 Upvotes

Hey everyone! Prisma just dropped an awesome tutorial on how to use Prisma with react-admin to build powerful admin panels.

If you haven’t heard of it, react-admin is an open source project which helps to simplify building admin panels and dashboard. Prisma can be paired with it as a datasource to power these panels with the help of an extra library and some config.

You can find the full tutorial here - enjoy! :)


r/prismaorm • • Feb 17 '25

Implementing Prisma RBAC: Fine-Grained Prisma Permissions

Thumbnail
permit.io
2 Upvotes

r/prismaorm • • Feb 11 '25

PRISMA & UUIDs

2 Upvotes

does prisma UUID support the current timestamp and the machine’s MAC address now?


r/prismaorm • • Feb 06 '25

How do I `prisma migrate deploy` in a production environment..?

2 Upvotes

Feel like I'm missing something really basic here; I've massively changed my Prisma schema between production and dev as I decided to completely rethink my logic.

I have an existing Vercel deployment - but I actually have no idea how to run `prisma migrate deploy` in production. I'm thinking of just adding it to the build command as a one off, and then drop it for further deployments.

Does that sound right or is there a more sensible/elegant way to run the command in my production environment?


r/prismaorm • • Feb 03 '25

How to ensure the 'right' schema binary is downloaded

2 Upvotes

Hi,

Trying to cross-build the migrations. Building on a M-based Mac, while the actual code will run in production on AWS Lambda.

For the query-engine, I can force the correct binaries by either adding them to the prisma schema in the client section. Or by setting the environment variables PRISMA_CLI_BINARY_TARGETS.

But for some reason, this is ignored for the schema engine.

What would be the recommended way to make sure that I get an rhel-openssl-3.0.x compatible binary downloaded for the schema binary as well?


r/prismaorm • • Jan 11 '25

Seeking Feedback: TypeScript Interface/Zod Schema Generator for Prisma

2 Upvotes

Hey Prisma devs,

I’ve been struggling with Prisma Client types, especially for contract and form validation. The deeply nested types and slow IntelliSense have been a real pain point.

To address this, I’ve started building a TypeScript interface / Zod schema generator and wanted to share it with others who might be facing similar challenges.

Here’s the project: prisma-dto-gen

I’d love your feedback—whether it’s about current pain points or how this tool could work better as a solution.

Thanks for taking a look! 🙌


r/prismaorm • • Oct 24 '24

Can't find properly types of Models in Prisma

2 Upvotes

Hello everyone, I'm new using typecript but have some experiencie using javascript.
I'm developing an api and I want to create a funciontion that retrieves a middleware.

It's for pagination and filtering porpuse, I dont wanna repeat my code in every single controller.

So, this function called paginateAndFilter take a prisma Model and retrieves a middleware with all the logic apllied to that model.

I tried to use PrismaModelDelegate but isnt correct. any ideas?

error:
'Prisma' has no exported member 'ModelDelegate'.

this is my code:

export const paginateAndFilter = <T>(
  model: Prisma.ModelDelegate<T> 
) => {
  return async (req: Request, res: Response) => {
    const { page = 1, limit = 10, ...filters } = req.query;

    const parsedPage = parseInt(page as string, 10) || 1;
    const parsedLimit = parseInt(limit as string, 10) || 10;

    const parseFilters = Object.fromEntries(
      Object.entries(filters).map(([key, value]) => [
        key,
        key === 'id' ? Number(value) : value, 
      ])
    );

    req.pagination = {
      page: parsedPage,
      limit: parsedLimit,
      filters: parseFilters,
    };

    try {
      const { page, limit, filters } = req.pagination;

      const startIndex = (page - 1) * limit;
      const endIndex = page * limit;

      const results: PaginatedResult<T> = {
        total: 0,
        results: [],
      };

      results.results = await model.findMany({
        where: filters, 
        skip: startIndex,
        take: limit,
      });

      const total = await model.count({ where: filters });
      results.total = total;

      if (endIndex < total) {
        results.next = {
          page: page + 1,
          limit: limit,
        };
      }

      if (startIndex > 0) {
        results.previous = {
          page: page - 1,
          limit: limit,
        };
      }

      if (total === 0) {
        return res.status(404).json({ message: `No se encontraron registros` });
      }

      res.status(200).json(results);
    } catch (error) {
      console.error('Error fetching data:', error);
      res.status(500).json({ message: 'Internal server error' });
    }
  };
};

r/prismaorm • • Aug 11 '24

Best practice for creating a model

2 Upvotes

I have a model called User with the following fields -

model User {
  id       Int u/id u/default(autoincrement())
  email    String
  password String
  name     String
  tag      String
}

Now, the name and tag params are not passed in the inital API when the user is created. But they are mandatory for every user. So how do I go about handling this? So far I have two options in mind

Option A: Make the fields name and tag as optional. Handle the logic during API calls to make sure they are added before a user can use the app.

Option B: Add @default("def_user_name") and @default("def_user_tag") in schema and keep both fields mandatory.

I dont like Option A because every developer needs to carefully look through to make sure they dont mess up anywhere. I dont like Option B because I have to add logic again to make sure def_user_name and def_user_tag are not actual values the user selects.

What is the best way to deal with this?


r/prismaorm • • Jul 24 '24

Lessons learned from building a Serverless NodeJS API with Vercel, Neon, and Prisma ORM

Thumbnail
rafaelcamargo.com
2 Upvotes