const userPhoneNumber = await transaction.one(pgp.as.format(`${pgp.helpers.update({
modifiedById: login.objectId,
modifiedTimestamp: now,
phoneNumber
}, columnSets.userPhoneNumbers.forUpdateById)} WHERE object_id = $/objectId/ AND removed = $/removed/ AND userId = $/userId/ RETURNING *`, { objectId, removed: false, userId }));
现在我正在我的代码中执行此操作。我希望能够
- 利用列集
- 使用 pgp.update 方法和列集来生成 SQL
但是,我也不确定如何在这里使用查询文件。如何使用查询文件以避免在 JavaScript 代码中使用原始 SQL 字符串?
现在我只能想到像这样查询文件
{statement:raw} WHERE object_id = $/objectId/AND returned = $/removed/AND userId = $/userId/RETURNING *
但是注入(inject)部分原始语句感觉有点黑客。
最佳答案
首先,静态声明您的 ColumnSet ,根据您使用的列和表进行对象。例如:
const cs = new pgp.helpers.ColumnSet(['col1, col2', 'col3'], {table: 'my-table'});
当需要执行查询时,您可以像这样准备 WHERE
条件:
const where = pgp.as.format(' WHERE object_id = ${objectId} AND removed = ${removed} AND
userId = ${userId} RETURNING *', {objectId, removed, userId});
然后你可以生成一个完整的UPDATE
sql,如下所示:
const updateSql = pgp.helpers.update(data, cs) + where;
现在您可以执行该 SQL。
I am not sure how to utilize query file here
在您的示例中,使用外部查询文件没有多大意义,但如果您愿意,您可以这样做,如进一步解释的那样。
您可以创建以下文件:
${update:raw} WHERE object_id = ${objectId} AND removed = ${removed} AND
userId = ${userId} RETURNING *
然后像加载任何其他 QueryFile
一样加载它:
const qf = new pgp.QueryFile(path, options);
然后你可以生成一个完整的 SQL 查询,如下所示:
const updateSql = pgp.as.format(qf, {
update: pgp.helpers.update(data, cs),
objectId,
removed,
userId
});
关于javascript - 避免使用原始 SQL 进行使用列集的 PgPromise 内联查询格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47011482/