Skip to content

Multiple Connections / Databases / Datasources #2443

Open

Description

@FredericLatour

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

  1. WellFail commented on May 15, 2020

    @WellFail

    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 ()

  2. FredericLatour commented on May 15, 2020

    @FredericLatour
    Author

    @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 models property.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.

    • It's verbose. Why having the database name hanging around when using only one?
    • it breaks compatibility with the current approach
    • moreover if you like this kind of approach, nothing prevents you from having an additional layer that handles connections that way in your application.
  3. srvmux commented on May 15, 2020

    @srvmux

    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?

  4. WellFail commented on May 15, 2020

    @WellFail

    @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.

  5. FredericLatour commented on May 15, 2020

    @FredericLatour
    Author

    @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.

  6. FredericLatour commented on May 15, 2020

    @FredericLatour
    Author
  7. srvmux commented on May 15, 2020

    @srvmux
  8. janpio commented on May 15, 2020

    @janpio
  9. FredericLatour commented on May 16, 2020

    @FredericLatour
    Author
  10. WellFail commented on May 18, 2020

    @WellFail

    @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.prisma files 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.

  11. FredericLatour commented on May 18, 2020

    @FredericLatour
    Author

    @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 :

    • the model property at the datasource level is not necessary
    • the parameter representing the datasource when instantiating PrismaClient is not necessary.

    Please, provide some example of what is wrong in your mind and how you see things should work.

  12. 131 remaining items

  13. NOOBBase commented on Nov 11, 2024

    @NOOBBase
    npx prisma migrate dev --schema prisma/db-2/schema.prisma --name initial

    you should add schema like this npx prisma migrate deploy --schema prisma/db-2/schema.prisma

    when deploying

  14. lukenas commented on Nov 11, 2024

    @lukenas
    npx prisma migrate dev --schema prisma/db-2/schema.prisma --name initial

    you should add schema like this npx prisma migrate deploy --schema prisma/db-2/schema.prisma

    when deploying

    this command wont work with mongodb provider which is one of my databases

  15. Hongdeshuai commented on Nov 27, 2024

    @Hongdeshuai

    migrations files are mixed and causes mess

  16. oadrianrabelo commented on Dec 19, 2024

    @oadrianrabelo

    Having this issue when trying to run project after running prisma generate:

    node:internal/modules/cjs/loader:1252
      throw err;
      ^
    
    Error: Cannot find module '../../../../prisma/generated/gsan'
    Require stack:
    - C:\Users\adria\projetos\CAERD\caerd-mobile-api\dist\src\modules\cliente-gsan\service\clientes-gsan.service.js
    - C:\Users\adria\projetos\CAERD\caerd-mobile-api\dist\src\modules\clientes\service\clientes.service.js
    - C:\Users\adria\projetos\CAERD\caerd-mobile-api\dist\src\modules\clientes\controller\clientes.controller.js
    - C:\Users\adria\projetos\CAERD\caerd-mobile-api\dist\src\modules\clientes\clientes.module.js
    - C:\Users\adria\projetos\CAERD\caerd-mobile-api\dist\src\app.module.js
    - C:\Users\adria\projetos\CAERD\caerd-mobile-api\dist\src\main.js
        at Function._resolveFilename (node:internal/modules/cjs/loader:1249:15)
        at Function._load (node:internal/modules/cjs/loader:1075:27)
        at TracingChannel.traceSync (node:diagnostics_channel:315:14)
        at wrapModuleLoad (node:internal/modules/cjs/loader:218:24)
        at Module.require (node:internal/modules/cjs/loader:1340:12)
        at require (node:internal/modules/helpers:141:16)
        at Object.<anonymous> (C:\Users\adria\projetos\CAERD\caerd-mobile-api\src\modules\cliente-gsan\service\clientes-gsan.service.ts:5:5)    
        at Module._compile (node:internal/modules/cjs/loader:1546:14)
        at Object..js (node:internal/modules/cjs/loader:1689:10)
        at Module.load (node:internal/modules/cjs/loader:1318:32) {
      code: 'MODULE_NOT_FOUND',
      requireStack: [
        'C:\\Users\\adria\\projetos\\CAERD\\caerd-mobile-api\\dist\\src\\modules\\cliente-gsan\\service\\clientes-gsan.service.js',
        'C:\\Users\\adria\\projetos\\CAERD\\caerd-mobile-api\\dist\\src\\modules\\clientes\\service\\clientes.service.js',
        'C:\\Users\\adria\\projetos\\CAERD\\caerd-mobile-api\\dist\\src\\modules\\clientes\\controller\\clientes.controller.js',
        'C:\\Users\\adria\\projetos\\CAERD\\caerd-mobile-api\\dist\\src\\modules\\clientes\\clientes.module.js',
        'C:\\Users\\adria\\projetos\\CAERD\\caerd-mobile-api\\dist\\src\\app.module.js',
        'C:\\Users\\adria\\projetos\\CAERD\\caerd-mobile-api\\dist\\src\\main.js'
      ]
    }
    
    Node.js v22.11.0
    

    The code from the external database:

    import { Injectable } from '@nestjs/common';
    import { PrismaClient } from 'prisma/generated/gsan';
    
    @Injectable()
    export class ClienteGsanService {
      private prismaGsan = new PrismaClient();
    
      async getData() {
        return this.prismaGsan.clienteGsan.findMany({
           ...
        })
         
    }
  17. NOOBBase commented on Feb 7, 2025

    @NOOBBase

    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...

  18. jpope19 commented on Feb 11, 2025

    @jpope19

    @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

  19. Firgrep commented on Feb 19, 2025

    @Firgrep

    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.

  20. jpope19 commented on Feb 22, 2025

    @jpope19

    @Firgrep how are you handling migrations with the multi-client approach?

  21. Firgrep commented on Feb 22, 2025

    @Firgrep

    @jpope19 we just have a script in package.json that runs db push for each schema.

  22. owaiszafar92 commented on May 4, 2025

    @owaiszafar92

    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

  23. moublini commented on May 11, 2025

    @moublini

    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.schema and companies.schema files. 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:

    // prisma/schema.prisma
    generator client {
      provider = "prisma-client-js"
    }
    // prisma/schema/users
    datasource users {
      provider = "postgresql"
      url = env("PG_URL")
    }
    
    model User {
      id    Int     @id @default(autoincrement())
      email String  @unique
      name  String?
      settings UserSettings?
    }
    
    model UserSettings {
      id    Int     @id @default(autoincrement())
      user User @relation(fields: [id], references: [id])
    
      setting1 String
      setting2 String
      setting3 String
    }
    // prisma/schema/companies
    
    datasource companies {
      provider = "mongodb"
      url      = env("MONGODB_URL")
    }
    
    model Company {
      id Int @id @default(autoincrement())
      name String
      createdAt @default(now())
    }

    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:

    generator client {
      provider = "prisma-client-js"
    }
    
    datasource users {
      provider = "postgresql"
      url = env("PG_URL")
    
      // Specify models here
      models = [User, UserSettings]
    }
    
    datasource companies {
      provider = "mongodb"
      url      = env("MONGODB_URL")
    }
    
    model User {
      id    Int     @id @default(autoincrement())
      email String  @unique
      name  String?
      settings UserSettings?
    }
    
    model UserSettings {
      id    Int     @id @default(autoincrement())
      user User @relation(fields: [id], references: [id])
    
      setting1 String
      setting2 String
      setting3 String
    }
    
     // Alternative syntax for specifying the datasource to put Company into
    model companies.Company {
      id Int @id @default(autoincrement())
      name String
      createdAt @default(now())
    }

    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:

    // Incorrect
    model companies.Client {
      id Int @default(autoincrement())
      
      company_id Int
      company Company @relation(fields: [company_id], references: [id]) // Allowed
    
      user_id Int
      user User @relation(fields: [user_id], references: [id]) // Error: User model is not in companies datasource
    }
    
    // Correct
    model companies.Client {
      id Int @default(autoincrement())
    
      user_id Int  
      company_id Int
      company Company @relation(fields: [company_id], references: [id])
    }

    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:

    1. a new PrismaClient instance is created, it does not automatically connect to the databases when created.
    2. Somewhere in the code, a query would be made against the User model. Prisma knows this is connected to Postgres and does not see any previous connection to Postgres, thus it creates a new one and keeps it for future queries in that Postgres database.
    3. Somewhere else in the code, the Company model would be queried. Prisma knows this is connected to MongoDB and does not see any previous connection to MongoDB, thus it creates a new one and keeps it for future queries in that MongoDB database.

    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.

    import { PrismaClient } from "@prisma/client";
    
    const client = new PrismaClient(); // Provides the API, does not connect to Postgres or MongoDB yet
    
    async function main() {
      const user = await client.user.findUnique({
        where: { id: 1 },
      }); // Connect to postgres
    
      const userSettings = await client.userSettings.findUnique({
        where: { id: 1 },
      }); // Reuse the postgres connection
    
      const company = await client.company.findUnique({ where: { id: 2 } }); // Connect to MongoDB at this point
    
      console.log(user, userSettings, company);
    }
    
    main();

    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.

  24. renenielsendk commented on Aug 3, 2025

    @renenielsendk

    Any news on this??

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions