Agik Setiawan - October 13, 2022

Setup MySQL with Prisma Multiple Database,

Pada tutorial sebelumnya kita sudah membahas apa itu Prisma, dan bagaimana cara memakai Prisma, kali ini kita kan membuat Setup Prisma dengan Multiple Database.


Masuk ke dalam folder project sebelumnya

cd express_prisma

Buat folder “db” di dalam root project lalu di dalam db buat folder “db1, db2”



db1/schema.prisma

generator client {
  provider = "prisma-client-js"
  output   = "../../node_modules/@generated/db1"
}

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

model User {
  id        Int      @id @default(autoincrement())
  createdAt DateTime @default(now())
  email     String   @unique
  name      String?
}


db2/schema.prisma

generator client {
  provider = "prisma-client-js"
  output   = "../../node_modules/@generated/db2"
}

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

model User {
  id        Int      @id @default(autoincrement())
  createdAt DateTime @default(now())
  email     String   @unique
  name      String?
}

Edit .env

DATABASE_URL="mysql://root:mysql@localhost:3307/express_prisma"
DATABASE_URL2="mysql://root:mysql@localhost:3307/express_prisma2"

Jalankan perintah

npx prisma db push --schema ./db/db1/schema.prisma
npx prisma db push --schema ./db/db2/schema.prisma

npx prisma generate --schema ./db/db1/schema.prisma
npx prisma generate --schema ./db/db2/schema.prisma

Edit file db.js

const prisma = require("@prisma/client")
const db = new prisma.PrismaClient()

const DB1 = require("./../node_modules/@generated/db1").PrismaClient
const DB2 = require("./../node_modules/@generated/db2").PrismaClient

const db1 = new DB1()

const db2 = new DB2()

module.exports = { db, db1, db2 }


Untuk melakukan query cukup panggil db1,db2 sesuai dengan kebutuhan kita. pada contoh dibawah ini adalah contoh penggunaan Querynya

const { db1, db2 } = require("./db.js")

const getDb1 = async () => {
  const user1 = await db1.user.findMany()
  console.log(user1)
}

const getDb2 = async () => {
  const user2 = await db2.user.findMany()
  console.log(user2)
}

getDb1()
getDb2()

Share


Comments