You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 10:54:49