Opened 8 minutes ago
#37556 new Bug
Combined querysets with default ordering raise ORA-00907 on Oracle
| Reported by: | Dmitri | Owned by: | |
|---|---|---|---|
| Component: | Database layer (models, ORM) | Version: | 6.0 |
| Severity: | Normal | Keywords: | oracle, union, order_by |
| Cc: | Triage Stage: | Unreviewed | |
| Has patch: | no | Needs documentation: | no |
| Needs tests: | no | Patch needs improvement: | no |
| Easy pickings: | no | UI/UX: | no |
Description
On Oracle, combining unsliced querysets for a model with Meta.ordering
generates a bare ORDER BY inside parenthesized components of a compound
query. Oracle rejects this SQL with:
oracledb.exceptions.DatabaseError: ORA-00907: missing right parenthesis
This isn't specific to ordering by related fields. For example, the
following test using the existing Note model in
tests/queries/test_qs_combinators.py fails on Oracle:
def test_union_default_ordering(self): note_b = Note.objects.create(note="n2", misc="m2") note_a = Note.objects.create(note="n1", misc="m1") qs = Note.objects.all() self.assertSequenceEqual(qs.union(qs), [note_a, note_b])
The behavior is the same on stable/6.0.x and main, so this isn't a
regression in Django 6.1.
For unsliced combined queries, the ordering of individual components
doesn't affect the selected rows; the outer query applies the resulting
ordering. Keeping it also creates backend deviations: some databases
accept and ignore it, while Oracle rejects it.
Simon previously suggested clearing ordering when it isn't meaningful:
when ordering in combined queries is not meaningful
(not (self.is_sliced or self.distinct_fields or self.select_for_update))
I think we should always elide it
The proposed direction is therefore to clear meaningless ordering while
preserving it for sliced queries, DISTINCT ON, and SELECT FOR UPDATE.
When meaningful ordering is preserved but unsupported by the target
backend, compilation could raise a clear error based on the backend
feature flags.
References:
- #36938 and #37097: previous fixes for ordering in combined queries.
- Simon's proposed approach.
- PR #22337: discussion and a proof of concept with tests, tested on Oracle 26ai and SQLite.
- Jacob's follow-up supporting investigation of this approach through the regular development process.
- PR #22372: temporarily skips the related test on Oracle.