【发布时间】:2020-12-03 01:47:43
【问题描述】:
我一直在使用 slick 进行 DB 交互,并使用 h2 内存数据库进行测试。所以,我刚刚添加了一个新方法,在该方法中,我编写了一个普通的 SQL 查询而不是一个漂亮的查询。
Slick 版本:3.3.0 HikariCp:3.3.0 H2:1.4.200
所以它会因普通 sql 查询而失败,并出现语法错误异常。
def filterTasksByGivenConstraints(taskIds: List[Long], constraints: String): Future[Vector[Int]] = {
val ids = taskIds.mkString("'", "','", "'")
println(s"SELECT id FROM task where id in ($ids) and $constraints")
val query = sql"""SELECT "id" FROM "task" WHERE "id" IN (#$ids) and #$constraints""".as[Int]
db.get.run(query)
.recover {
case ex: Exception =>
logger.error(s"An exception has occurred while fetching filtered tasks $ids for given constraints $constraints and exception is: $ex")
throw ex.getCause
}
}
在 println 中打印的查询:
SELECT id FROM task where id in ('1') and ("expire_on" <= '2020-07-18') and (("expire_on" at time zone 'EST')::date >= '2020-07-16'::date and ("expire_on" at time zone 'EST')::date <= '2020-07-18'::date) and (("claim_number" = 'foo20') or ("referred_to" = '21'))
例外:
15:16:01.063 [scala-execution-context-global-23] ERROR io.inbox.stream.db.DBOperations - {"Level":"ERROR","Message":"An exception has occurred while fetching filtered tasks '1' for given constraints (\"expire_on\" <= '2020-07-18') and ((\"expire_on\" at time zone 'EST')::date >= '2020-07-16'::date and (\"expire_on\" at time zone 'EST')::date <= '2020-07-18'::date) and ((\"claim_number\" = 'foo20') or (\"referred_to\" = '21')) and exception is: org.h2.jdbc.JdbcSQLException: Syntax error in SQL statement \"SELECT \"\"id\"\" FROM \"\"task\"\" WHERE \"\"id\"\" IN ('1') AND (\"\"expire_on\"\" <= '2020-07-18') AND ((\"\"expire_on\"\" AT[*] TIME ZONE 'EST')::DATE >= '2020-07-16'::DATE AND (\"\"expire_on\"\" AT TIME ZONE 'EST')::DATE <= '2020-07-18'::DATE) AND ((\"\"claim_number\"\" = 'foo20') OR (\"\"referred_to\"\" = '21')) \"; expected \"(, ., [, ::, *, /, %, +, -, ||, ~, !~, NOT, LIKE, ILIKE, REGEXP, IS, IN, BETWEEN, AND, OR, ,, )\"; SQL statement:\nSELECT \"id\" FROM \"task\" WHERE \"id\" IN ('1') and (\"expire_on\" <= '2020-07-18') and ((\"expire_on\" at time zone 'EST')::date >= '2020-07-16'::date and (\"expire_on\" at time zone 'EST')::date <= '2020-07-18'::date) and ((\"claim_number\" = 'foo20') or (\"referred_to\" = '21')) [42001-197]","TimeStamp":"2020-08-13 15:16:01.063","api_app_log":"io.inbox.stream.db.DBOperations"}
我什至在 Postgres 上运行,打印的查询工作正常。我找不到 h2 的问题。
【问题讨论】:
-
AT TIME ZONE仅从 H2 1.4.200 起受支持。 -
另一个很好的例子说明为什么在不同于生产数据库的东西上进行测试没有真正意义。
-
@EvgenijRyazanov 感谢您的回复。我升级了版本,但还是一样的错误。
-
@a_horse_with_no_name 是的,我同意你的看法。
-
请编辑您的问题并将异常消息替换为新版本的消息。