【问题标题】:pg-promise: SQL Names ~ or :name does not seem to work with ParameterizedQuerypg-promise: SQL Names ~ or :name 似乎不适用于 ParameterizedQuery
【发布时间】:2020-12-22 11:17:01
【问题描述】:

我正在尝试在其text 参数中使用带有SQL NamesParameterizedQuery

我知道文档读到此参数必须是 stringQueryFile

基本上,我想做的是:

import pgPromise from 'pg-promise';

const pgp = pgPromise();
const pq = new pgp.ParameterizedQuery({
      text: `
        SELECT $1:name from my_table
        where $2:name = $3;
        `,
      rowMode: 'array'
    });
const params = {user_col: 'user', id_col: 'id', id_value: 'XXX'};
try {
  return await this.db.any(pq, Object.values(params));
} catch (e) {
  console.error(e);

  return e;
}

我得到的是这样的错误:

QUERY: {
[start:run]   text: '\n' +
[start:run]     '        SELECT $1:name from my_table\n' +
[start:run]     '        where $2:name = $3;\n' +
[start:run]     '        ',
[start:run]   values: [ 'user', 'id', 'XXX' ],
[start:run]   rowMode: 'array'
[start:run] }
[start:run] error: syntax error at or near ":"

是否可以在ParameterizedQuery 中使用:name(或~)?问题是,我真的希望我的查询结果是行数组而不是行对象数组,而 ParameterizedQuery 的参数 rowMode 设置为 array 似乎是我能做到这一点的唯一方法。

【问题讨论】:

  • 我想这是不可能的,因为文本查询为Only the basic variables ($1, $2, etc) can be used in the query, because Parameterized Queries are formatted on the server side.(见here)。我对吗?是否有任何替代方法可以从查询中返回行数组而不是行对象数组?
  • Formatting Filters 在参数化查询或准备好的语句中不起作用,因为它们是在服务器端格式化的。

标签: javascript postgresql postgresql-10 pg-promise


【解决方案1】:

来自Formatting Filters 文档:

请注意,格式化过滤器仅适用于普通查询,不适用于 PreparedStatementParameterizedQuery,因为根据定义,这些是在服务器端格式化的。

官方文档中的注释是在这个问题之后添加的,因为它之前出现过几次。希望从现在开始会更清楚。

【讨论】:

  • 谢谢,这澄清了问题,很高兴您甚至更新了文档
猜你喜欢
  • 1970-01-01
  • 2020-04-04
  • 2023-04-06
  • 2017-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多