PostgreSQL
 sql >> Datenbank >  >> RDS >> PostgreSQL

Spring Data Rest:Date is null query löst eine Postgres-Ausnahme aus

Ich habe einige Zeit damit verbracht, mir das anzusehen, weil ich wirklich "Datum ist null" in Abfragen vergleichen möchte, und das ist das Ergebnis:

Wenn Sie „cast(foo.date as date) is null“ verwenden, ist null ", es funktioniert OK, wenn das Feld nicht null ist. Wenn das Feld null ist, wird diese Ausnahme ausgelöst:

org.postgresql.util.PSQLException: ERROR: cannot cast type bytea to date

Die Lösung ist coalesce:

coalesce(:date, null) is null

Es funktioniert gut, ob Daten im Feld getestet wurden oder nicht.

Mein Abfragebeispiel:

@Query("SELECT c "
        + " FROM Entity c "
        + " WHERE "
        + "       and ( (coalesce(:dateFrom, null) is null and coalesce(:dateUntil, null) is null) "
        + "             or ((coalesce(c.date, null) is not null) "
        + "                 and ( "
        + "                        ((coalesce(:dateFrom, null) is null and coalesce(:dateUntil, null) is not null) and c.date <= :dateUntil) "
        + "                     or ((coalesce(:dateUntil, null) is null and coalesce(:dateFrom, null) is not null) and c.date >= :dateFrom)"
        + "                     or (c.date between :dateFrom and :dateUntil)"
        + "                 )"
        + "             )"
        + "       ) "

Hoffe, es funktioniert für Sie!