简体   繁体   English

如何运行从 Knex toNative 返回的查询?

[英]How to run the query that gets returned from Knex toNative?

Knex toNative() might return something like this: Knex toNative() 可能会返回如下内容:

{
  sql: 'select "firstName", "lastName" from "table1" where (("age" >= $1 and "country" = $2) or ("age" < $3))',
  bindings: [ 25, 'NL', 25 ]
}

and naively, I thought I could run that like:天真地,我以为我可以这样运行:

knex.raw(q.sql, q.bindings)

which doesn't work:这不起作用:

Expected 3 bindings, saw 0预期 3 个绑定,看到 0

I use raw queries quite a lot, but always with?我经常使用原始查询,但总是使用? and not $1 etc, so I figured this was the difference, and indeed, it works fine if I replace them.而不是 1 美元等,所以我认为这就是区别,事实上,如果我更换它们,它就可以正常工作。 That is not so nice though.但这不是很好。

What am I missing?我错过了什么? How can I run the raw query as-is?如何按原样运行原始查询?

This seems to be an issue with .toNative() when using Postgres.使用 Postgres 时,这似乎是.toNative()的问题。 The reason appears to be because knex.raw only expects ?原因似乎是因为knex.raw只期望? and ???? to be used for positional arguments regardless of the underlying SQL dialect being used but .toNative() uses the postgres positional argument syntax of $ .用于位置 arguments ,无论使用底层 SQL 方言,但.toNative()使用 postgres 位置参数语法$

If you remove the .toNative() call, so you only call .toSQL() on your query, that should give you the sql and bindings that you can pass directly to knex.raw .如果您删除.toNative()调用,因此您只在查询中调用.toSQL() ,那应该会为您提供sql和可以直接传递给knex.rawbindings

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM