'Spring Boot R2DBC DatabaseClient: Parameter at position X is not set with UNION requests

I hope you would help me solve the issue I am facing with R2DBC DatabaseClient in Spring Boot 2.6.2.

I have a case where I need to generate SQL string with UNION depending on number of entity types in request. E. g.

SELECT SUM(money) as money, SUM(volume) as volume, SUM(sessions) as sessions, created_at as timestamp, 0 as type
FROM statistics
WHERE created_at >= :startDate AND created_at < :endDate
  AND type = 0 AND period = 1 AND statistical_type = 'First'
  AND statistical_id IN (:ids)
GROUP BY created_at
UNION
SELECT SUM(money) as money, SUM(volume) as volume, SUM(sessions) as sessions, created_at as timestamp, 1 as type
FROM statistics
WHERE created_at >= :startDate AND created_at < :endDate
  AND type = 1 AND period = 1 AND statistical_type = 'First'
  AND statistical_id IN (:ids)
GROUP BY created_at
ORDER BY timestamp

and I use it like so:

databaseClient.sql(generatedSqlString)
                        .bind("startDate", actualStartDate)
                        .bind("endDate", actualEndDate)
                        .bind("ids", ids)
                        .map(ReportDataBuilder.MAPPING_FUNCTION)
                        .all()

where ids is List<Integer> with at least 1 element.

Problem I encounter is:

  1. if there is only 1 type in request thus no UNION in SQL, everything works like charm
  2. if UNION appears in SQL thus 2 or more bindings of every parameter, I constantly get Parameter at position X is not set where for example X is 5 if ids has one element or X is 9 if ids has 5 elements etc.

I have a dirty workaround with embedding ids directly in the SQL string as comma separated string, but I assume there should be better solution.

Thank you all in advance!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source