Skip to content

[MODEUS-219] Fix udp_report_releases to guarantee sorted array ordering#214

Merged
alb3rtino merged 1 commit into
masterfrom
MODEUS-219
Mar 11, 2026
Merged

[MODEUS-219] Fix udp_report_releases to guarantee sorted array ordering#214
alb3rtino merged 1 commit into
masterfrom
MODEUS-219

Conversation

@alb3rtino
Copy link
Copy Markdown
Contributor

@alb3rtino alb3rtino commented Mar 10, 2026

https://folio-org.atlassian.net/browse/MODEUS-219

Purpose

The udp_report_releases SQL function returns the reportReleases array in unspecified order. The function uses jsonb_agg(DISTINCT ...) with an ORDER BY clause at the query level, but since the query returns a single aggregated row, the ORDER BY has no effect on the array element ordering.

The PostgreSQL documentation states:

The aggregate functions array_agg, json_agg, jsonb_agg, [...] produce meaningfully different result values depending on the order of the input values. This ordering is unspecified by default, but can be controlled by writing an ORDER BY clause within the aggregate call.

The documentation on aggregate expressions further clarifies that DISTINCT alone does not guarantee ordering - it only ensures each distinct value is processed once. To control ordering, an ORDER BY clause must be placed within the aggregate call itself:

aggregate_name (DISTINCT expression [ , ... ] [ order_by_clause ] )

The existing tests in SQLTriggersIT assert sorted order and currently pass, but only by coincidence - PostgreSQL's DISTINCT implementation happens to use sort-based deduplication, which is not a documented guarantee.

Approach

Refactor udp_report_releases to use a subquery pattern, matching the approach already used by udp_report_types and udp_report_errors in the same file. This moves DISTINCT and ORDER BY into a subquery so that sorting occurs before aggregation, making the ordering explicit and reliable.

An alternative would be to use the inline ORDER BY within the aggregate call:

SELECT COALESCE(jsonb_agg(DISTINCT jsonb->>'release' ORDER BY jsonb->>'release'), '[]'::jsonb)

The subquery approach was chosen for consistency with the other functions in the same file.

Related

folio-org/ui-erm-usage#609

@alb3rtino alb3rtino requested a review from slaemmer March 10, 2026 19:14
@sonarqubecloud
Copy link
Copy Markdown

@alb3rtino alb3rtino merged commit e440285 into master Mar 11, 2026
28 checks passed
@alb3rtino alb3rtino deleted the MODEUS-219 branch March 11, 2026 18:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants