Repository navigation
Description
Problem
An application may need to access different connections/databases.
One use case could be having the exact same set of tables into different databases (multi-tenant approach).
Another use case could be having to access punctually some specific data in a separate database/server.
In any cases "a single connection" for the entire application is a really strong limitation.
Any SQL driver or ORM is capable of connecting to multiple databases either by direct support (TypeOrm) or by creating 2 instances. Unless I missed something this is not possible with Prisma client.
Suggested solution
I believe that it can be easily achieved with the following approach that does not change much both on the schema and client side of things.
datasource proj01 {
provider = "postgresql"
url = env("DATABASE_URL_PROJ01")
models = [Post, User]
}
datasource proj02 {
provider = "postgresql"
url = env("DATABASE_URL_PROJ02")
models = [Post, User]
}
datasource common {
provider = "postgresql"
url = env("DATABASE_URL_COMMON")
models = [Config]
}
generator client {
provider = "prisma-client-js"
}
model Post {
id Int @id @default(autoincrement())
title String
content String?
published Boolean @default(false)
author User? @relation(fields: [authorId], references: [id])
authorId Int?
}
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
posts Post[]
}
model Config {
id Int @id @default(autoincrement())
field string
}You would then need to make it possible to use one connection/db or another:
import { PrismaClient } from '@prisma/client'
const proj01= new PrismaClient('proj01')
const proj02= new PrismaClient('proj02')
const proj01Users = await proj01.user.findMany()
const proj02Users = await proj02.user.findMany()Additional context
Please note that it has nothing to do with having a dynamic url for being able to point to a different database when in development and/or staging. This feature is also needed but it's a different matter.
Note also that this is not exclusively to solve "multi-tenant" scenarios. I may need to access a database on another server whatever the reason.
Update 01: different database per environment use case
Thinking a bit more about it, this feature also provides a solution to the problem of having a different database (sqlite vs other database in prod for instance) depending on the environment (prod, staging, dev).
Adding on my previous example, you could have :
datasource proj01 {
provider = "postgresql"
url = env("DATABASE_URL_PROJ01")
models = [Post, User]
}
datasource proj01-dev {
provider = "sqlitel"
url = env("DATABASE_URL_PROJ01")
models = [Post, User]
}And then depending on the environment:
import { PrismaClient } from '@prisma/client'
const proj01 = ( process.env.NODE_ENV === 'prod') ?
new PrismaClient('proj01') :
new PrismaClient('proj01-dev')
Activity
WellFail commentedon May 15, 2020
I think it would be nice to put each database in a separate file and have one file to which they will be connected. It also seems to me that it would be more convenient to have one client for all databases, something like this:
prisma.database_name.model.query ()FredericLatour commentedon May 15, 2020
@WellFail I'm not completely sure of what you mean by putting each database in a separate file.
Models are not specific to a database. You associate the model to a database/connection through the
modelsproperty.In that respect the separation, as far as database/connection is concerned, does not really make sense.Your
prisma.database_name.model.query ()does not sound like a sensible choice in my opinion.srvmux commentedon May 15, 2020
I'm not sure if this would work, but have considered creating a model and a client for each datasource and then creating the contexts for them?
WellFail commentedon May 15, 2020
@FredericLatour I meant that the data set may differ depending on the database, and it is not very correct to store them all in one file, this complicates the understanding. I understand that in your case this is not necessary. But a similar approach will be more flexible.
As for my
prisma.database_name.model.query ()I agree that this is not the best solution, indeed it can be processed already at the level of my application.FredericLatour commentedon May 15, 2020
@WellFail Having entirely different models for different databases/connection is a specific use case. In a multi tenant application, models will be shared by databases/connection.
You may want some flexibility for defining a schema over multiple files (is that currently possible?) but a rules based on the databases/connection does not work.
FredericLatour commentedon May 15, 2020
srvmux commentedon May 15, 2020
janpio commentedon May 15, 2020
FredericLatour commentedon May 16, 2020
WellFail commentedon May 18, 2020
@FredericLatour Different databases for different environments currently work depending on environment variables and do it perfectly, what you offer is unnecessary. If we are talking about the possibility of several databases within the same application, then I understand what it is about, but the best approach would be to create several
schema.prismafiles and the client will be generated one for all connections (in this case, we forbid storing the same models in different databases), or in the generated client, it should be possible to select the necessary database when generating the request, but in any case, the generation of several clients of the prisma is unnecessary.FredericLatour commentedon May 18, 2020
@WellFail
How do you currently make it possible to use Sqlite in development while using say Postgres in production?
Regarding using multiple databases/connections, I don't get what you are proposing. Would you mind elaborating?
Keep in mind that in a multi-tenant scenario, you certainly don't want to repeat your model that are identical whatever the database/connection.
In my solution, you are not generating multiple clients: you are instantiating a client for the desired connection. I can't see what is wrong with this approach. This is the same approach you will be using with whatever Driver ORM in the Node ecosystem.
The approach I'm proposing has the advantage to be fully compatible with the existing approach. When defining a single datasource (like this is the case now) in your schema, then :
Please, provide some example of what is wrong in your mind and how you see things should work.
131 remaining items
NOOBBase commentedon Nov 11, 2024
you should add schema like this npx prisma migrate deploy --schema prisma/db-2/schema.prisma
when deploying
lukenas commentedon Nov 11, 2024
this command wont work with mongodb provider which is one of my databases
Hongdeshuai commentedon Nov 27, 2024
migrations files are mixed and causes mess
oadrianrabelo commentedon Dec 19, 2024
Having this issue when trying to run project after running
prisma generate:The code from the external database:
NOOBBase commentedon Feb 7, 2025
Here I am again. So we are 4 years further. The initial request was when does Prisma add multiple databases? 4 years!! Wow in the meantime I build 5 other companies. How on earth with one focus (databases) can development take 4 years??? there are many threads about this topic. This one started in 2020. I am now wondering if prisma is the best solution to prcoeed with. If this is the delivery time. Then just wow...... No offense and no intention to bash. But we need to be realistic here...
jpope19 commentedon Feb 11, 2025
@NOOBBase drizzle supports it.. I'm thinking of migrating to them if this isn't resolved here soon.
https://github.com/rphlmr/drizzle-playground/tree/main
Firgrep commentedon Feb 19, 2025
Would also like to see this implement properly into Prisma. We're currently using a multi-client approach, which works fine, but it's clunky and heavy-handed, especially when we have many databases to connect to. At least an update on a possible timeline would be nice.
jpope19 commentedon Feb 22, 2025
@Firgrep how are you handling migrations with the multi-client approach?
Firgrep commentedon Feb 22, 2025
@jpope19 we just have a script in package.json that runs db push for each schema.
owaiszafar92 commentedon May 4, 2025
I have a situation where i need to save users data by state and into different databases state wise. but whole schema for users state wise will be same.. then do i need to create multiple schema files with different db connection strings ? any help would be great
moublini commentedon May 11, 2025
If the prisma team were to implement a single prisma client but multiple database api I would say that using prisma would absolutely be one of the best developer experiences any ORMs could provide. Also now that finally prisma.schema folder support has officially come, here's what my proposal, after reading the solutions of other people in this issue, to make multiple databases work would be:
in a prisma schema folder, there will be
users.schemaandcompanies.schemafiles. For users we're gonna have a User and UserSettings model in a Postgres database, for companies instead we have a Company model in a MongoDB database. One of probably the cleanest way to make this work would be the following:Alternatively, if we were working on a single schema.prisma file, thus creating ambiguity on what models go where, the code would be the following:
For correctness, the schema.prisma file would only allow relationships on models that are inside the same datasource, this means there cannot be something like a Client model referencing the User and Company model:
Then, in an index.ts file, the prisma client would be created as always. However, to mitigate the issue of having unnecessary database connections, lazy database connections would be perhaps a nice solution. The following would happen:
This solution would not cause an unnecessary connection problem and thus would be not only extremely easy to use, as the code has not changed a single bit. If prisma were to be used in a microservices project with 4 different databases, every service could very easily use a single prisma client and use only the database that service needs.
The only possible drawback I see coming from this approach is the absolute ease of using databases you're probably not meant to use. If a person unknowingly queries a model like Company in the users service that for some reason has credentials for mongodb, then it could cause general slow down. But I guess this is up to the developer instead of the library itself, so I would not mind this much.
renenielsendk commentedon Aug 3, 2025
Any news on this??