Opened 2 months ago

Closed 2 months ago

#31396 closed New feature (fixed)

Add support for bitwise XOR to expressions.

Reported by: Hannes Ljungberg Owned by: Hannes Ljungberg
Component: Database layer (models, ORM) Version: master
Severity: Normal Keywords: bitwise xor
Cc: Triage Stage: Ready for checkin
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

It would be nice to get support for performing bitwise XOR on expressions. I'm aware of #29865 but from my understanding this ticket is about logical XOR and not bitwise XOR. Let me know if that ticket should be used instead.

My proposal is to implement this just like the other bitwise-functions, i.e Combinable.bitxor(other).

The connector defined by Combinable could be # , this is what PostgresSQL use, see https://www.postgresql.org/docs/current/functions-bitstring.html. I guess a more natural choice would’ve been ^ but this connector is already in use by Combinable.POW:
https://github.com/django/django/blob/291539a85c8461456ab728fe6820a86de54294b6/django/db/models/expressions.py#L42

Bitwise XOR is supported by all backends except sqlite. It could be implemented on sqlite as something like ((%(lhs)s | %(rhs)s) - (%(lhs)s & %(rhs)s)) but the way CombinedExpression.as_sql is implemented makes it a bit tricky to repeat the right-hand side binding:
((“left_hand_side_expr" | %s) - ("left_hand_side_expr" & %s)) % (rhs,) .

Maybe it could be OK to set django.db.backends.sqlite3.features.DatabaseFeatures.supports_bitwise_xor = False

I have a proof-of-concept ready if this would be accepted.

Change History (4)

comment:1 in reply to:  description Changed 2 months ago by felixxm

Summary: Add support for bitwise XORAdd support for bitwise XOR to expressions.
Triage Stage: UnreviewedAccepted

Replying to Hannes Ljungberg:

Bitwise XOR is supported by all backends except sqlite. It could be implemented on sqlite as something like ((%(lhs)s | %(rhs)s) - (%(lhs)s & %(rhs)s)) but the way CombinedExpression.as_sql is implemented makes it a bit tricky to repeat the right-hand side binding:
((“left_hand_side_expr" | %s) - ("left_hand_side_expr" & %s)) % (rhs,) .

You can override a bitxor operator (e.g. #) in DatabaseOperations.combine_expression() for each backend.

comment:2 Changed 2 months ago by Hannes Ljungberg

Has patch: set

comment:3 Changed 2 months ago by felixxm

Triage Stage: AcceptedReady for checkin

comment:4 Changed 2 months ago by Mariusz Felisiak <felisiak.mariusz@…>

Resolution: fixed
Status: assignedclosed

In f3da09df:

Fixed #31396 -- Added binary XOR operator to F expressions.

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