Create new Schema in Postgres when new user register, using Prisma

Viewed 349

I am working on an application in which every user has own schema(Postgres schema), I am using postages, nestJs, and Prisma Orm. I have developed a schema-based multi-tenant, that works fine but I have to generate a Prisma client every time when new schema required. I want to create a new schema or database when a new user register.

In conclusion, I want to create schema dynamically(Programmatically).

in this question whenever, I have use word schema means postgres schema.

Thanks in advance

1 Answers

You can use Raw Query to create schema programmatically.

Consider this function for creating schema if the schema doesn't exist.

You can invoke this function any time you need to create a new schema.

import { PrismaClient, User } from '@prisma/client';

const prisma = new PrismaClient();

async function main() {
  // ... you will write your Prisma Client queries here
  const result = await prisma.$executeRaw`CREATE SCHEMA IF NOT EXISTS prisma`;

  console.log('result', result);
}

main()
  .catch((e) => {
    throw e;
  })
  .finally(async () => {
    await prisma.$disconnect();
  });
Related