3-setting-up-a-multi-tenant-postgresql-database-with-prisma-orm.html

Setting Up a Multi-Tenant PostgreSQL Database with Prisma ORM

In the world of software development, multi-tenancy has become a crucial architectural approach for applications that serve multiple clients or organizations from a single codebase. This article will guide you through the process of setting up a multi-tenant PostgreSQL database using Prisma ORM, providing actionable insights and clear code examples along the way.

What is Multi-Tenancy?

Multi-tenancy is an architectural pattern where a single instance of a software application serves multiple tenants. Each tenant can be a different user, organization, or entity that operates independently of one another. This approach can significantly reduce operational costs and increase efficiency.

Use Cases for Multi-Tenancy

  • SaaS Applications: Software as a Service platforms often utilize multi-tenancy to serve various businesses from a single codebase.
  • Enterprise Solutions: Large organizations may require multi-tenancy to manage different departments or subsidiaries.
  • Cost Efficiency: Reduces infrastructure costs by sharing resources like databases and servers.

Why Use Prisma ORM?

Prisma is a modern ORM that simplifies database interaction in Node.js and TypeScript applications. It provides a type-safe API, making it easier to work with databases while eliminating common pitfalls associated with raw SQL queries. Prisma also supports migrations and generates the schema for your database, making it an excellent choice for multi-tenant setups.

Setting Up Your Environment

Before we dive into the code, let’s ensure you have the necessary tools installed:

  1. Node.js: Ensure you have Node.js installed on your machine.
  2. PostgreSQL: Install PostgreSQL and set up a database.
  3. Prisma: You can install Prisma globally using npm:

bash npm install -g prisma

  1. Initialize Your Project: Create a new directory for your project and initialize it:

bash mkdir multi-tenant-app cd multi-tenant-app npm init -y

  1. Install Required Packages:

bash npm install prisma @prisma/client

Step 1: Configure Your Prisma Schema

Create a new file named schema.prisma in your project directory:

// schema.prisma

generator client {
  provider = "prisma-client-js"
}

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

model Tenant {
  id          Int      @id @default(autoincrement())
  name        String
  users       User[]
}

model User {
  id        Int     @id @default(autoincrement())
  email     String  @unique
  tenantId  Int
  tenant    Tenant  @relation(fields: [tenantId], references: [id])
}

Explanation of the Schema

  • Tenant Model: Represents each individual tenant with a unique ID and name.
  • User Model: Represents users associated with each tenant, linked via tenantId.

Step 2: Setting Up the Database

Next, you need to configure your database connection. Create a .env file in your project directory and add your PostgreSQL connection string:

DATABASE_URL="postgresql://USER:PASSWORD@localhost:5432/mydatabase"

Replace USER, PASSWORD, and mydatabase with your actual PostgreSQL credentials and database name.

Run Prisma Migrations

With your schema and database configured, run the following commands to create your database tables:

npx prisma migrate dev --name init

This command will generate the necessary SQL migration files and apply them to your PostgreSQL database.

Step 3: Seed the Database

To test your multi-tenant setup, you might want to seed your database with some initial data. Create a file named seed.js:

// seed.js

const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();

async function main() {
  const tenant1 = await prisma.tenant.create({
    data: {
      name: 'Tenant 1',
      users: {
        create: { email: 'user1@tenant1.com' },
      },
    },
  });

  const tenant2 = await prisma.tenant.create({
    data: {
      name: 'Tenant 2',
      users: {
        create: { email: 'user1@tenant2.com' },
      },
    },
  });

  console.log({ tenant1, tenant2 });
}

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

Run the seed script:

node seed.js

Step 4: Querying the Database

Now that you have your multi-tenant setup ready, let’s see how to query the database for tenant-specific data. Create a file named index.js:

// index.js

const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();

async function getUsersByTenant(tenantId) {
  const users = await prisma.user.findMany({
    where: { tenantId: tenantId },
  });
  console.log(users);
}

getUsersByTenant(1) // Fetch users for Tenant 1
  .catch(e => console.error(e))
  .finally(async () => {
    await prisma.$disconnect();
  });

Troubleshooting Common Issues

  • Database Connection Errors: Ensure that your PostgreSQL server is running and that the connection string is correct.
  • Prisma Migrations Failing: Check your schema for syntax errors, and ensure your database is accessible.

Conclusion

Setting up a multi-tenant PostgreSQL database with Prisma ORM can streamline your application development process while providing a scalable architecture. By following the steps outlined in this article, you can create a robust multi-tenant system that efficiently manages data for various tenants.

With Prisma, you gain the benefits of type safety and simplified database interactions, making it a powerful tool in your development arsenal. Happy coding!

SR
Syed
Rizwan

About the Author

Syed Rizwan is a Machine Learning Engineer with 5 years of experience in AI, IoT, and Industrial Automation.