首页 > 解决方案 > 如何使用 prisma 和 postgresql 处理条件准备语句?

问题描述

我有一个搜索查询,它的参数根据客户端输入而变化。

await prisma.$queryRaw(`SELECT column FROM table ${condition ? `WHERE column = '${condition}'`  :' ' } `) 

如何使用准备好的语句编写此查询并避免重复查询。我想出的唯一解决方案如下:

const result = condition ? await prisma.$queryRaw(`SELECT column FROM table WHERE column = $1`,condition) : await prisma.$queryRaw(`SELECT column FROM table`)

这样做的目的是避免从第一个查询中注入 sql。

尝试@Ryan 建议的解决方案后编辑我收到以下错误

Raw query failed. Code: `22P03`. Message: `db error: ERROR: incorrect binary data format in bind parameter 1`

这是我的实现:

    const where = Prisma.sql`WHERE ${searchConditions.join(' AND ')}`;
    const fetchCount = await prisma.$queryRaw`
    SELECT 
      COUNT(id)
    FROM
      table
    ${searchConditions.length > 0 ? where : Prisma.empty}
  `;

这将在 prisma 日志中转换为以下内容:

Query: 
    SELECT 
      COUNT(id)
    FROM
      table
    WHERE $1
   ["column = something"]

解决方案 我必须做很多返工才能实现我想要的。这是它背后的想法:

对于每个搜索条件,您需要执行以下操作:

let queryCondition = Prisma.empty;
    if (searchFilter) {
      const searchFilterCondition = Prisma.sql`column = ${searchFilter}`;

      queryCondition.sql.length > 0
        ? (queryCondition = Prisma.sql`${queryCondition} AND ${streamingUnitCondition}`)
        : (queryCondition = searchFilterCondition);
    }

之后在最终的搜索查询中,您可以执行以下操作:

SELECT COUNT(*) FROM table ${queryCondition.sql.length > 0 ? Prisma.sql`WHERE ${queryCondition}` : Prisma.empty}

标签: node.jspostgresqlprisma

解决方案


你可以这样做:

import { Prisma } from '@prisma/client'

const where = Prisma.sql`where column = ${condition}`

const result = await prisma.$queryRaw`SELECT column FROM table ${condition ? where : Prisma.empty}`

推荐阅读