Prisma: get name of active Postgresql schema for the connection

2 min read 05-10-2024
Prisma: get name of active Postgresql schema for the connection


Getting the Active PostgreSQL Schema Name with Prisma

Prisma, a popular ORM (Object-Relational Mapper) for Node.js, provides a convenient way to interact with databases. But sometimes you need more than just querying data - you might want to know the current schema your Prisma client is connected to, especially when working with multiple schemas in PostgreSQL.

Let's say you have two PostgreSQL schemas: public and users. You're using Prisma to interact with both, but you need a way to dynamically determine the current schema during runtime. This is where the challenge lies.

The Original Approach and its Limitations

Prisma doesn't provide a direct way to access the current schema name. You might think of querying the pg_catalog.current_schema() system table, but Prisma doesn't expose that functionality out-of-the-box.

// This code won't work
const currentSchema = await prisma.$queryRaw`SELECT current_schema()`;
console.log(currentSchema);

This approach won't work because Prisma doesn't handle raw SQL queries in the same way as a regular database client.

The Solution: Using a Custom Prisma Client

The solution involves creating a custom Prisma client with a custom function to retrieve the active schema name. This function will use raw SQL to query the pg_catalog.current_schema() table.

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

// Define a custom PrismaClient
const prisma = new PrismaClient({
  // ... (Your Prisma client configuration)
  // Define a custom function to retrieve the active schema
  activeSchema: {
    // Use a raw SQL query to get the current schema
    query: `SELECT current_schema()`,
    // Define the function to use this query
    function: async () => {
      const result = await prisma.$queryRaw<string>(`SELECT current_schema()`);
      return result[0];
    },
  },
});

// Use the custom function to get the active schema
const currentSchema = await prisma.activeSchema();
console.log(currentSchema);

This approach provides a clear and concise solution to retrieve the active schema name in Prisma. It leverages the power of raw SQL queries while maintaining the convenience of Prisma's ORM capabilities.

Key Takeaways

  • Prisma doesn't have a built-in method to directly access the active schema name.
  • You can create a custom Prisma client with a custom function that uses raw SQL to retrieve the schema name.
  • This approach offers a flexible and reliable way to dynamically determine the current schema within your Prisma application.

Additional Resources

By understanding this approach, you can seamlessly manage multiple schemas in your Prisma projects, adding another layer of control and flexibility to your database interactions.