在带有 pg-promise 查询的模板文字上使用 $1 有好处吗?
Is there a benefit to using $1 over a Template Literal with pg-promise queries?
使用 pg-promise,使用 </code> 比模板文字有什么好处吗?模板文字对我来说更加熟悉,但我不得不假设他们出于这个包的原因而采取不同的方式。 </p>
<p><strong>"Normal"方式:</strong></p>
<pre><code>db.any('SELECT * FROM users WHERE active = ', [true])
我的做法:
const isTrue = true;
db.any(`SELECT * FROM users WHERE active = ${isTrue}`)
已更新我的做法:
const isTrue = true;
const name = 'Matt'
db.any('SELECT * FROM users WHERE active = AND name = ', [isTrue, name])
或
const isTrue = true;
const name = 'Matt'
db.any(`SELECT * FROM users WHERE active = $/isTrue/ AND name = $/name/`, {isTrue, name})
is there any benefit to using over Template Literals?
您不能使用模板文字,documentation emphasizes:
IMPORTANT: Never use the reserved ${}
syntax inside ES6 template strings, as those have no knowledge of how to format values for PostgreSQL. Inside ES6 template strings you can only use one of the 4 alternatives - $()
, $<>
, $[]
or $//
.
你应该使用 Named Parameters, they offer a lot of benefits over the Index Variables:
- 支持nested names
- 支持
this
参考资料
- 内部更易于阅读和维护SQL files
对于你自己的例子,如果你真的需要模板字符串:
const isTrue = true;
await db.any(`SELECT * FROM users WHERE active = $/isTrue/`, {isTrue});
或者您可以只使用标准字符串:
await db.any('SELECT * FROM users WHERE active = ${isTrue}', {isTrue});
使用 pg-promise,使用 </code> 比模板文字有什么好处吗?模板文字对我来说更加熟悉,但我不得不假设他们出于这个包的原因而采取不同的方式。 </p>
<p><strong>"Normal"方式:</strong></p>
<pre><code>db.any('SELECT * FROM users WHERE active = ', [true])
我的做法:
const isTrue = true;
db.any(`SELECT * FROM users WHERE active = ${isTrue}`)
已更新我的做法:
const isTrue = true;
const name = 'Matt'
db.any('SELECT * FROM users WHERE active = AND name = ', [isTrue, name])
或
const isTrue = true;
const name = 'Matt'
db.any(`SELECT * FROM users WHERE active = $/isTrue/ AND name = $/name/`, {isTrue, name})
is there any benefit to using over Template Literals?
您不能使用模板文字,documentation emphasizes:
IMPORTANT: Never use the reserved
${}
syntax inside ES6 template strings, as those have no knowledge of how to format values for PostgreSQL. Inside ES6 template strings you can only use one of the 4 alternatives -$()
,$<>
,$[]
or$//
.
你应该使用 Named Parameters, they offer a lot of benefits over the Index Variables:
- 支持nested names
- 支持
this
参考资料 - 内部更易于阅读和维护SQL files
对于你自己的例子,如果你真的需要模板字符串:
const isTrue = true;
await db.any(`SELECT * FROM users WHERE active = $/isTrue/`, {isTrue});
或者您可以只使用标准字符串:
await db.any('SELECT * FROM users WHERE active = ${isTrue}', {isTrue});