如何通过Prisma获取PostgreSQL连接的当前活跃Schema名称?
获取Prisma连接的PostgreSQL当前Schema名称的方法
通过PostgreSQL内置查询直接获取
可以使用queryRaw执行PostgreSQL的原生查询,获取当前会话使用的Schema:const currentSchemaResult = await prisma.$queryRaw`SELECT current_schema();`; const currentSchema = currentSchemaResult[0].current_schema;这个方式能准确拿到当前连接实际使用的Schema,不管是通过Prisma配置静态指定还是动态切换的场景都适用。
从Prisma客户端配置中解析(动态指定Schema时)
如果你是通过数据库URL动态指定Schema(比如测试环境用随机名称),可以直接从客户端的数据源配置里解析:// 动态创建Prisma客户端时指定随机Schema const randomSchemaName = "test_schema_123"; const prisma = new PrismaClient({ datasources: { db: { url: `postgresql://user:password@localhost:5432/mydb?schema=${randomSchemaName}` } } }); // 从URL中提取Schema名称 const dbUrl = new URL(prisma.$datasources.db.url); const currentSchema = dbUrl.searchParams.get('schema') || 'public';
内容的提问来源于stack exchange,提问作者hallvors
相关产品推荐
相关产品推荐

