r/prismaorm • • Dec 17 '24

How to connect a NestJS + Prisma API to an external database?

0 Upvotes

I'm trying to connect my NestJS + Prisma API to an external database to fetch its data. How can I achieve this?

For context, I already have a primary database that manages the data for the API itself. However, I need to connect to another database in order to create a specific route where the data exists only in that external database.

What's the best way to do this? I've tried using two schemas, but I couldn't get it working. The application only recognizes the schema I run npx prisma generate on.


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 • • 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 • • 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 • • Mar 12 '24

Autocomplete with Prisma, Next, and MongoDb

1 Upvotes

All of the docs related to this issue are depracted. I have created an atlas search autocomplete index to search listings that a user creates on a site I am developing. The autocomplete works on atlas using query testing but I can't find any guidance anywhere creating the get route and front end component. Has anyone achieved this functionality in Next 13+? I would greatly appreciate some guidance as to whether or not this is even possible.


r/prismaorm • • Nov 03 '24

Prisma+Postgres not working?

1 Upvotes

Helo everyone!

So prisma postgres launched early access a couple of days ago, the setup looked fairly simple so I wanted to try it out. However, even at the first stepping stone, it doesn't seem to work for me.

In the quick start you are supposed to run this command to create a project

$ npx try-prisma@latest --template databases/prisma-postgres --name hello-prisma --install npm
'try-prisma' is not recognized as an internal or external command,
operable program or batch file.

but every time I run it, I get the exact same output. I tried different variations, of steps, and it was still the same.

is the command broken? or am I missing something here? because I didn't seem to find anything else in the quick start guide nor the documentation.

I could use some help and enlightenment, thank you very much!

edit: here are my environment settings

$ node -v
v20.11.1

$ npm -v
10.9.0

edit 2: I figured it out, just clear npm cache

npm cache clean --force

r/prismaorm • • Feb 04 '24

GraphQL/Yoga/Prisma Help

Thumbnail self.graphql
1 Upvotes

r/prismaorm • • Sep 22 '22

From UML to Prisma

2 Upvotes

Hi, is there a tool to generate UML ( visually ) and export it to prisma?

Thank you


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 • • 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 11 '25

PRISMA & UUIDs

2 Upvotes

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


r/prismaorm • • Mar 01 '25

How do I model a partnership between two users?

1 Upvotes

How do I model this:

  • a user can have a partner and that partner user must partner them back

  • users can have dependents. If the user has a partner, the dependents are shared. But they can not have a partner and still have dependents.


r/prismaorm • • Feb 17 '24

How do I optimize my query for a table with filters on two columns that has a `one-to-many` relationship

Thumbnail self.postgresql
1 Upvotes

r/prismaorm • • Oct 23 '24

Prisma Lambda Layer - Folder Structure?!?

1 Upvotes

Has anyone had better luck than me trying to get Prisma working in a Lambda Layer.

I consistently get

PrismaClientInitializationError: Prisma Client could not locate the Query Engine for runtime \"rhel-openssl-3.0.x\".\n\nThis is likely caused by a bundler that has not copied \"libquery_engine-rhel-openssl-3.0.x.so.node\" next to the resulting bundle.\nEnsure that \"libquery_engine-rhel-openssl-3.0.x.so.node\" has been copied next to the bundle or in \"node_modules/.prisma/client\".\n\nWe would appreciate if you could take the time to share some information with us.\nPlease help us by answering a few questions: https://pris.ly/engine-not-found-bundler-investigation\n\nThe following locations have been searched:\n /var/task/node_modules/.prisma/client\n /var\n /asset-input/node_modules/@prisma/client\n /.prisma/client\n /tmp/prisma-engines\n /var/task

I've tried a whole bunch of folder combinations and it never seemingly gets found..

nodejs/
    ├── node_modules/
    │   ├── @prisma/
    │   │   └── client/
    │   │       └── libquery_engine-rhel-openssl-3.0.x.so.node
    │   │       └── schema.prisma
    │   ├── .prisma/
    │   │   └── client/
    │   │       └── libquery_engine-rhel-openssl-3.0.x.so.node
    │   │       └── schema.prisma
    │   └── prisma/
    │       └── libquery_engine-rhel-openssl-3.0.x.so.node
    │       └── schema.prisma  # (Optional, if you need to include the schema)
    └── package.json

nodejs/
    ├── node_modules/
    │   ├── @prisma/
    │   │   └── client/
    │   │       └── libquery_engine-rhel-openssl-3.0.x.so.node
    │   ├── .prisma/
    │   │   └── client/
    │   │       └── libquery_engine-rhel-openssl-3.0.x.so.node
    │   └── prisma/
    │       └── schema.prisma  # (Optional, if you need to include the schema)
    └── package.json


layer/
└── nodejs/
    ├── node_modules/
    │   ├── @prisma/
    │   │   └── client/
    │   │       └── libquery_engine-rhel-openssl-3.0.x.so.node
    │   ├── .prisma/
    │   │   └── client/
    │   │       └── libquery_engine-rhel-openssl-3.0.x.so.node
    │   └── prisma/
    │       └── schema.prisma  # (Optional, if you need to include the schema)
    └── package.json

nodejs/
    │└── libquery_engine-rhel-openssl-3.0.x.so.node
     ── schema.prisma
    ├── node_modules/
    │   ├── @prisma/
    │   │   └── client/
    │   │       └── libquery_engine-rhel-openssl-3.0.x.so.node
    │   │       └── schema.prisma
    │   ├── .prisma/
    │   │   └── client/
    │   │       └── libquery_engine-rhel-openssl-3.0.x.so.node
    │   │       └── schema.prisma
    │   └── prisma/
    │       └── libquery_engine-rhel-openssl-3.0.x.so.node
    │       └── schema.prisma  # (Optional, if you need to include the schema)
    └── package.json

nodejs/
    ├── asset-input/node_modules/
    │   ├── @prisma/
    │   │   └── client/
    │   │       └── libquery_engine-rhel-openssl-3.0.x.so.node
    │   │       └── schema.prisma
    │   ├── .prisma/
    │   │   └── client/
    │   │       └── libquery_engine-rhel-openssl-3.0.x.so.node
    │   │       └── schema.prisma
    │   └── prisma/
    │       └── libquery_engine-rhel-openssl-3.0.x.so.node
    │       └── schema.prisma  # (Optional, if you need to include the schema)
    └── package.json

And the same again without the nodejs/ folder

I'd love a hand if someone has been through this before!


r/prismaorm • • Dec 18 '23

How do I get return type for a wrapper function?

1 Upvotes

I have a wrapper function around my Prisma query. While I get type-safety when call the function, I get errors on the return type. Please see my code below.

import "server-only";

import { prisma } from "@/lib/prisma/db";
import { Prisma } from "@prisma/client";

export async function getOfferings({
  where,
  select,
}: {
  where?: Prisma.OfferingWhereInput;
  select?: Prisma.OfferingSelect;
} = {}) {
  const offerings = await prisma.offering.findMany({
    where: {
      isPrivate: false,
      archivedAt: null,
      publishedAt: {
        not: null,
      },
      ...where,
    },
    select: select,
  });

  if (!offerings) {
    throw new Error('No offerings found.');
  }

  return offerings;
}

Here's where I call the function.

const offerings = await getOfferings({ 
  select: {
    cuid: true, 
    provider: {
      select: {
        slug: true
      },
    }
  }
}
)

I get a typescript error when I try to access offerings.provider.slug.

How do I get dynamic return types based on what I pass to the function?


r/prismaorm • • Feb 17 '25

Implementing Prisma RBAC: Fine-Grained Prisma Permissions

Thumbnail
permit.io
2 Upvotes

r/prismaorm • • Jan 09 '24

Creating db accessor library using prisma

1 Upvotes

Hi all. please take a look, and try to run this github repo https://github.com/gordon-ero/prisma-help Basically, im trying to create a db accessor library, where i can access a prisma instance of any database in my org. all of the prisma files and client generate correctly, but once i try to instantiate the prisma client it hangs.

Thoughts?


r/prismaorm • • Nov 28 '23

I am facing performance issues with Prisma with MONGODB. How can I improve the performance?

1 Upvotes

I used to use only MONGODB as database and mongoose in NodeJs to access it. I recently started using POSTGRES and MONGODB both in my recent project and then learnt about wonders of PRISMA. I integrated it into my project and created schemas. Once I started using it I noticed that MONGODB crud operations were exponentially slower than mongoose calls.

Few of the reasons I think might the issue be are:

  1. For Prisma to support NoSQL databases, they added an extra layer of validation, this extra layer is slowing it down.

  2. Every time I run a query will it create a new connection with database and then perform action. If so that is an expensive operation.

  3. We might have many indexes or uniques which might slow down the database.

These are few of the reasons that I can think of and if there are any other reasons, feel free to suggest.

I tried creating a 1000 documents using PRISMA and Mongoose. The results are:

PRISMA took 1 min 31 sec Mongoose took 10.91 sec 

I tried creating 1000 records in POSTGRES. The result is:

PRISMA took 4.37 sec

I expected the output to be faster in MONGODB because I will be saving something like transactions which happen quiet often in this environment. Hence if there is a lag then it will slowdown the whole server.

I used thunder client to benchmark these results and performed API calls to test it.

What might me the possible resolutions for this problem?

If there are any queries feel free to ask.

Environment:

Prisma: 5.4.2 TypeScript: 5 u/types/express: ^4.17.19, u/types/node: ^20.8.4


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 • • Jul 13 '24

Cleaner Way to Write Prisma Schema for Badge System

1 Upvotes

I'm working on a badge system for my web app and would appreciate any suggestions for cleaning up this Prisma schema

https://pastebin.com/raw/xnLW95g8


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 • • Jul 09 '24

Mixing Prisma Accelerate with Supabase pgbouncer

Thumbnail self.supabase
1 Upvotes

r/prismaorm • • Jan 12 '24

Building a schema for a family tree

1 Upvotes

I want to build a small family tree but I'm having issues creating the self references. how would you do it? My model should look like this:

model Member {
id String u/id u/default(uuid())
father Member
mother Member
children Member[]

}

Whenever I try that I get the error: opposite relation field on the model `Member`.

In the end, what I want to achieve is that, when Member A adds member B as father, then member A appears among the children of member B


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?