3

当文本包含字符串“$(...)”时,我无法将文本插入数据库,因为我的代码返回错误:属性“...”不存在。

const pgp = require('pg-promise')({ promiseLib: bluebird });
const db = pgp(process.env.DATABASE_URL);
let values = [{text: 'this is fine'}, {text: 'this fails $(...)'}];
let cs = new pgp.helpers.ColumnSet(['text']);
let query = pgp.helpers.insert(values, cs);
db.manyOrNone(query);

我是否缺少某种“这只是文本”属性?

谢谢

编辑错误仅在使用 $() 语法将其他变量添加到整个 SQL 调用时发生

'use strict';
const bluebird = require('bluebird');
const pgp = require('pg-promise')({ promiseLib: bluebird });
const db = pgp('postgres://localhost/okeydokey-local');

db.any(
  'CREATE TABLE text_table ( ' +
    'text_column text ' +
  ')'
);
let values = [{ text_column: 'this is fine' }, { text_column: 'this fails $(test)' }];
let cs = new pgp.helpers.ColumnSet(['text_column'], {table: 'text_table'});
let query = pgp.helpers.insert(values, cs);
console.log(query);
db.manyOrNone(query +
  'some more SQL dependent on $(somethingElse)',
  {
    somethingElse: 'someValue'
  }
);

输出

insert into "text_table"("text_column") values('this is fine'),('this fails $(test)')
Unhandled rejection Error: Property 'test' doesn't exist.
4

1 回答 1

2

以下行生成您的最终查询:

let query = pgp.helpers.insert(values, cs);
//=>insert into "text_table"("text_column") values('this is fine'),('this fails $(test)')

它不是用于进一步格式化的查询模板,它应该直接执行。

在您的代码中,您试图格式化最终的查询字符串,这会破坏尝试test在格式化对象中定位属性。

于 2016-09-14T16:05:42.973 回答