Search code examples
postgresqlprisma

Prisma: get name of active Postgresql schema for the connection


I run tests with a test environment where migrations are run against a randomly named Postgresql schema. However, it is hard to test APIs using queryRaw because those queries do not run against the right schema, apparently..? Is there a Prisma method for "get name of the Postgresql schema used for this connection"?


Solution

  • At the moment, there is no API to get the randomly generated schema but you can use current_schema() function to get the current schema, store it in a variable and then use it in the subsequent raw query:

    import { Prisma } from '@prisma/client';
    
    const result = await prisma.$queryRaw(`SELECT current_schema()`) as [{ current_schema: string }];
    const schema = result[0].current_schema;
    
    await prisma.$queryRaw(`SELECT * FROM "${Prisma.raw(schema)}".tableName`);