避免使用原始 SQL 用于使用列集的 PgPromise 内联查询格式化
Avoid using raw SQL for PgPromise inline query formatting using columnset
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 代码中使用 RAW SQL 字符串?
现在我只能想到这样查询文件
{statement:raw} WHERE object_id = $/objectId/ AND removed = $/removed/ AND userId = $/userId/ RETURNING *
但是注入部分原始语句感觉有点老套。
首先,根据您使用的列和 table 静态声明您的 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
});
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 代码中使用 RAW SQL 字符串?
现在我只能想到这样查询文件
{statement:raw} WHERE object_id = $/objectId/ AND removed = $/removed/ AND userId = $/userId/ RETURNING *
但是注入部分原始语句感觉有点老套。
首先,根据您使用的列和 table 静态声明您的 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
});