#37535 new Bug

Model._perform_unique_checks() uses the default connection's features instead of the routed database's

Reported by: nehmtech Owned by:
Component: Database layer (models, ORM) Version: dev
Severity: Normal Keywords: multi-db, validate_unique, router
Cc: nehmtech Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Model._perform_unique_checks() decides whether to skip a lookup for an empty string using connection.features.interprets_empty_strings_as_nulls, where connection is the default database connection.

However, the uniqueness query that follows is routed through DATABASE_ROUTERS (via model_class._default_manager.db). When reads are routed to a database whose backend differs from the default one (for example Oracle alongside PostgreSQL), the empty-string check uses the wrong backend's behavior, so validation can skip or run the uniqueness query incorrectly.

There was already a TODO: Handle multiple backends with different feature flags at that spot. Other code, such as UniqueConstraint.validate() and related managers, already resolves features from the routed database alias.

Steps to reproduce: configure two databases with different values of features.interprets_empty_strings_as_nulls, add a router whose db_for_read() returns the non-default alias, and call validate_unique() on an instance with an empty string in a unique CharField. Whether the query runs depends on the default database rather than the routed one.

Patch: ​https://github.com/nehmtech/django/tree/unique-checks-routed-db-features

Change History (0)

Note: See TracTickets for help on using tickets.
Back to Top