node.js - 如何使用 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}
解决方案
你可以这样做:
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}`
推荐阅读
- amazon-web-services - 在 AppSync 上,如何查询模型按多对多关系排序?
- angular - 如何修复 Angular 10 中的“Type '{ }[]' is missing the following properties from type and 3 more”?
- web - 仅水平响应
- python - 如何在 Python 的列表中获取字符串的位置?
- java - Java Vectors : 使用 Vectors 实现 Pop 功能
- serilog - 使用 Serilog 记录异常
- python - 从 .txt 文件重塑矩阵
- cobol - EXIT 关键字的用途是什么?
- r - 解决承诺后 R Shiny 下载 xlsx
- javascript - dayGridMonth 中的 Fullcalendar v5 第一天不起作用