6

我正在使用 PostgreSQL 9.4 和很棒的 JSONB 字段类型。我正在尝试查询文档中的字段。以下工作在 psql CLI

SELECT id FROM program WHERE document -> 'dept' ? 'CS'

当我尝试通过我的 Scala 应用程序运行相同的查询时,我收到以下错误。我正在使用 Play 框架和 Anorm,所以查询看起来像这样

SQL(s"SELECT id FROM program WHERE document -> 'dept' ? {dept}")
.on('dept -> "CS")
....

SQLException: : 没有为参数 5 指定值。(SimpleParameterList.java:223)

(在我的实际查询中有更多参数)

我可以通过将我的参数转换为类型jsonb并使用@>运算符来检查包含情况来解决这个问题。

SQL(s"SELECT id FROM program WHERE document -> 'dept' @> {dept}::jsonb")
.on('dept -> "CS")
....

我不太热衷于周围的工作。我不知道演员表是否有性能损失,但这是额外的打字,而且不明显。

还有什么我可以做的吗?

4

4 回答 4

7

作为避免 ? 运算符,您可以创建一个完全相同的新运算符。

这是原始运算符的代码:

CREATE OPERATOR ?(
  PROCEDURE = jsonb_exists,
  LEFTARG = jsonb,
  RIGHTARG = text,
  RESTRICT = contsel,
  JOIN = contjoinsel);

SELECT '{"a":1, "b":2}'::jsonb ? 'b'; -- true

使用不同的名称,没有任何冲突,例如 #-# 并创建一个新名称:

CREATE OPERATOR #-#(
  PROCEDURE = jsonb_exists,
  LEFTARG = jsonb,
  RIGHTARG = text,
  RESTRICT = contsel,
  JOIN = contjoinsel);

SELECT '{"a":1, "b":2}'::jsonb #-# 'b'; -- true

在您的代码中使用这个新的运算符,它应该可以工作。

检查 pgAdmin -> pg_catalog -> Operators 以了解所有使用 ? 在名字里。

于 2014-12-20T12:14:18.863 回答
5

在 JDBC(和标准 SQL)中,问号保留为参数占位符。不允许其他用途。

请参阅JDBC 规范是否阻止“?” 从被用作运算符(引号之外)?以及关于 jdbc-spec-discuss 的讨论

当前的 PostgreSQL JDBC 驱动程序会将所有出现的问号(文本或注释之外)转换为 PostgreSQL 特定的参数占位符。我不确定 PostgreSQL JDBC 项目是否已经做了任何事情(比如在上面的链接中讨论引入转义)来解决这个问题。快速查看代码和文档表明他们没有,但我没有深入挖掘。

附录:如bobmarksie 的回答所示,当前版本的 PostgreSQL JDBC 驱动程序现在支持通过加倍来转义问号(即:使用??而不是?)。

于 2014-12-20T08:51:52.693 回答
2

I had the same issue a couple of days ago and after some investigation I found this.

https://jdbc.postgresql.org/documentation/head/statement.html

In JDBC, the question mark (?) is the placeholder for the positional parameters of a PreparedStatement. There are, however, a number of PostgreSQL operators that contain a question mark. To keep such question marks in a SQL statement from being interpreted as positional parameters, use two question marks (??) as escape sequence. You can also use this escape sequence in a Statement, but that is not required. Specifically only in a Statement a single (?) can be used as an operator.

Using 2 question marks seemed to work well for me - I was using the following driver (illustrated using maven dependency) ...

    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>9.4-1201-jdbc41</version>
    </dependency>

... and MyBatis for creating the SQL queries and it seemed to work well. Seemed easier / cleaner than creating an PostgreSQL operator.

SQL went from e.g.

select * from user_docs where userTags ?| array['sport','property']

... to ...

select * from user_docs where userTags ??| array['sport','property']

Hopefully this works with your scenario!

于 2016-02-12T09:54:53.183 回答
0

正如鲍勃所说,只需使用??而不是?

SQL(s"SELECT id FROM program WHERE document -> 'dept' ?? {dept}")
.on('dept -> "CS")
于 2019-05-30T03:06:13.680 回答