Skip to content

Add default order by id to one_to_many and many_to_many associations#4996

Draft
philippthun wants to merge 1 commit intocloudfoundry:mainfrom
sap-contributions:default-order-by-id-associations
Draft

Add default order by id to one_to_many and many_to_many associations#4996
philippthun wants to merge 1 commit intocloudfoundry:mainfrom
sap-contributions:default-order-by-id-associations

Conversation

@philippthun
Copy link
Copy Markdown
Member

@philippthun philippthun commented Apr 7, 2026

Ensures deterministic ordering for all association queries by adding a default order: :id to the vcap_relations plugin. This fixes sporadic test failures in parallel test runs where database query order was non-deterministic.

Explicit order options still override this default, and callers can use .order(:field) on the dataset to override as needed.

Associations with a block (custom dataset transformation) do not get the default order, as the transformation may not be compatible with ordering by id.

Also removes now-redundant explicit order: :id from two models and fixes orgs_visibility to order by service_plan_id (the only column in its select list).

  • I have reviewed the contributing guide

  • I have viewed, signed, and submitted the Contributor License Agreement

  • I have made this pull request to the main branch

  • I have run all the unit tests using bundle exec rake

  • I have run CF Acceptance Tests

@Gerg
Copy link
Copy Markdown
Member

Gerg commented Apr 7, 2026

Not sure if this will affect anything other than the public APIs, but I know some users previously run into some issues with service binding ordering changes in app environments: #4665

cc @Samze @sethboyles

@philippthun philippthun force-pushed the default-order-by-id-associations branch 6 times, most recently from 9ac94f6 to 69a4432 Compare April 8, 2026 13:56
Adds a Sequel extension that automatically appends ORDER BY id to
model queries, ensuring deterministic results for consistent API
responses and reliable test behavior in parallel runs.

Skips adding the default order when:
- Query already has an explicit ORDER BY clause
- Query has GROUP BY (aggregated results don't have individual ids)
- Query is schema introspection (LIMIT 0)
- Query has UNION/INTERSECT/EXCEPT (ORDER BY before UNION is a syntax
  error)
- Query has DISTINCT ON (requires matching ORDER BY)
- Query is a subquery (outer query handles ordering)
- Model doesn't have id as primary key
- id is not in the select list

For JOIN queries (including many_to_many associations), it uses a
qualified column (table.id) to avoid ambiguity.
@philippthun philippthun force-pushed the default-order-by-id-associations branch from 69a4432 to e5b44d3 Compare April 9, 2026 15:01
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