Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to use multiple database in prisma orm

I am not able to use multiple database in same application . How can we use multiple data sources. Can we generate multiple "schema.prisma" for different database connections.

like image 890
Rakesh Kumar Srivastava Avatar asked Sep 05 '25 03:09

Rakesh Kumar Srivastava


2 Answers

You actually can with a workaround as specified here. Create two different schema.prisma in separate folders and initialise PrismaClient for each schema.prisma that will point to the specific database.

like image 77
Ryan Avatar answered Sep 09 '25 02:09

Ryan


Video reference from codeGrepper generate two prisma schema one by default scehma.prisma and another accoring to your will 2) in second scehema generate extra output path where prisma client will store //prisma/retspy.prisma

 generator client {
        provider = "prisma-client-js"
        output   = "client/retspy"
    }

datasource db {
    provider = "mysql"
    url      = env("RETSPY_DATABASE_URL")
}

3)Generate client

import { PrismaClient as NcomDBPrismaClient } from '@prisma/client';
import { PrismaClient as RetspyPrismaClient } from '../../prisma/client/retspy';

declare global {
  var ncomDBPrisma: NcomDBPrismaClient | undefined;
  var retspyPrisma: RetspyPrismaClient | undefined;
}   

const ncomDBClient = globalThis.ncomDBPrisma || new NcomDBPrismaClient();
const retspyClient = globalThis.retspyPrisma || new RetspyPrismaClient();

// Next.js hot reloading can cause issues with Prisma, so we store the clients globally.
if (process.env.NODE_ENV !== 'production') {
  globalThis.ncomDBPrisma = ncomDBClient;
  globalThis.retspyPrisma = retspyClient;
}

export { ncomDBClient, retspyClient };
export default ncomDBClient;

//use both client according to will

import { retspyClient } from "@/app/libs/prismadb";
 const fetchData = async () => {
    try {
      const data = await retspyClient.property_for_sale.findFirst({
        where: {
          state_or_province: {
            contains: "Albert",
          },
        },
      });
      // console.log(data);
      return data; // Return the fetched data
    } catch (err) {[enter link description here][1]
      console.log(err);
      return null; // Return null if there's an error
    }
  };
like image 29
Shirshak kandel Avatar answered Sep 09 '25 03:09

Shirshak kandel