Skip to content

Commit af84cfb

Browse files
charettessarahboyce
authored andcommitted
Fixed #36612 -- Fixed a KeyTextTransform crash on MySQL against annotations.
MySQL only supports the ->> when used directly against columns, this can be inferred by the presence of lhs.output_field.model as model bounds fields are directly tied to columns. Purposely don't systematically switch to using JSON_QUOTE(JSON_EXTRACT(...)) as there might be functional indices out there that rely on the SQL remaining stable between versions. Thanks Jacob Tavener for the report.
1 parent a36df68 commit af84cfb

2 files changed

Lines changed: 12 additions & 2 deletions

File tree

django/db/models/fields/json.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -424,8 +424,12 @@ class KeyTextTransform(KeyTransform):
424424
output_field = TextField()
425425

426426
def as_mysql(self, compiler, connection):
427-
if connection.mysql_is_mariadb:
428-
# MariaDB doesn't support -> and ->> operators (see MDEV-13594).
427+
# The ->> operator is not supported on MariaDB (see MDEV-13594) and
428+
# only supported against columns on MySQL.
429+
if (
430+
connection.mysql_is_mariadb
431+
or getattr(self.lhs.output_field, "model", None) is None
432+
):
429433
sql, params = super().as_mysql(compiler, connection)
430434
return "JSON_UNQUOTE(%s)" % sql, params
431435
else:

tests/model_fields/test_jsonfield.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1160,6 +1160,12 @@ def test_lookups_with_key_transform(self):
11601160
True,
11611161
)
11621162

1163+
def test_cast_with_key_text_transform(self):
1164+
obj = NullableJSONModel.objects.annotate(
1165+
json_data=Cast(Value({"foo": "bar"}, JSONField()), JSONField())
1166+
).get(pk=self.objs[0].pk, json_data__foo__icontains="bar")
1167+
self.assertEqual(obj, self.objs[0])
1168+
11631169
@skipUnlessDBFeature("supports_json_field_contains")
11641170
def test_contains_contained_by_with_key_transform(self):
11651171
tests = [

0 commit comments

Comments
 (0)