0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【PostgreSQL】パラメータでnull値が指定される際にcoalesceを使用してエラー回避する

Posted at

概要

PostgreSQLでアプリケーションからパラメータを指定する際、値がnullである場合にどのように対応するかというのが今回のテーマです。パラメータにnullが指定された際Postgres Sql could not determine data type of parameter by Hibernateのstackoverflowの記事で紹介されている通り、is nullの条件を入れてもERROR: could not determine data type of parameterというエラーが発生します。
回避するにはエラー内容に沿って、null値が入りうるパラメータにcastで型指定すれば回避はできます。ただ、そもそもnull判定に、coalesceを使ったらどうなるかを確認してみました。

前提

  • 使用したPostgreSQLのバージョンは17.2になります。

確認結果

SpringBootのJPQLで、以下のようにnull値が入るうるパラメータ(:startDateTime:endDateTime)にcoalesceを使ってみたところ、null値でもエラーを回避できました。理由についてAIで確認したところ、coalesceの第二引数で型推論が効くからではとのこと。

@Query("""
    select t from TaskExecuteEntity t 
    where t.taskDefinitionId = :taskDefinitionId 
    and t.executeUserId = :executeUserId
    and t.executeDateTime >= coalesce(:startDateTime, t.executeDateTime)
    and t.executeDateTime <= coalesce(:endDateTime, t.executeDateTime)
    order by t.executeDateTime desc
    limit 300
    """)
List<TaskExecuteEntity> findTaskExecuteList(
    @Param("taskDefinitionId") String taskDefinitionId,
    @Param("executeUserId") String executeUserId,
    @Param("startDateTime") OffsetDateTime startDateTime,
    @Param("endDateTime") OffsetDateTime endDateTime);
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?