json.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745
  1. import json
  2. import warnings
  3. from django import forms
  4. from django.core import checks, exceptions
  5. from django.db import NotSupportedError, connections, router
  6. from django.db.models import expressions, lookups
  7. from django.db.models.constants import LOOKUP_SEP
  8. from django.db.models.fields import TextField
  9. from django.db.models.lookups import (
  10. FieldGetDbPrepValueMixin,
  11. PostgresOperatorLookup,
  12. Transform,
  13. )
  14. from django.utils.deprecation import RemovedInDjango70Warning, django_file_prefixes
  15. from django.utils.translation import gettext_lazy as _
  16. from . import Field
  17. from .mixins import CheckFieldDefaultMixin
  18. __all__ = ["JSONField"]
  19. class JSONField(CheckFieldDefaultMixin, Field):
  20. empty_strings_allowed = False
  21. description = _("A JSON object")
  22. default_error_messages = {
  23. "invalid": _("Value must be valid JSON."),
  24. }
  25. _default_hint = ("dict", "{}")
  26. def __init__(
  27. self,
  28. verbose_name=None,
  29. name=None,
  30. encoder=None,
  31. decoder=None,
  32. **kwargs,
  33. ):
  34. if encoder and not callable(encoder):
  35. raise ValueError("The encoder parameter must be a callable object.")
  36. if decoder and not callable(decoder):
  37. raise ValueError("The decoder parameter must be a callable object.")
  38. self.encoder = encoder
  39. self.decoder = decoder
  40. super().__init__(verbose_name, name, **kwargs)
  41. def check(self, **kwargs):
  42. errors = super().check(**kwargs)
  43. databases = kwargs.get("databases") or []
  44. errors.extend(self._check_supported(databases))
  45. return errors
  46. def _check_supported(self, databases):
  47. errors = []
  48. for db in databases:
  49. if not router.allow_migrate_model(db, self.model):
  50. continue
  51. connection = connections[db]
  52. if (
  53. self.model._meta.required_db_vendor
  54. and self.model._meta.required_db_vendor != connection.vendor
  55. ):
  56. continue
  57. if not (
  58. "supports_json_field" in self.model._meta.required_db_features
  59. or connection.features.supports_json_field
  60. ):
  61. errors.append(
  62. checks.Error(
  63. "%s does not support JSONFields." % connection.display_name,
  64. obj=self.model,
  65. id="fields.E180",
  66. )
  67. )
  68. return errors
  69. def deconstruct(self):
  70. name, path, args, kwargs = super().deconstruct()
  71. if self.encoder is not None:
  72. kwargs["encoder"] = self.encoder
  73. if self.decoder is not None:
  74. kwargs["decoder"] = self.decoder
  75. return name, path, args, kwargs
  76. def from_db_value(self, value, expression, connection):
  77. if value is None:
  78. return value
  79. # Some backends (SQLite at least) extract non-string values in their
  80. # SQL datatypes.
  81. if isinstance(expression, KeyTransform) and not isinstance(value, str):
  82. return value
  83. try:
  84. return json.loads(value, cls=self.decoder)
  85. except json.JSONDecodeError:
  86. return value
  87. def get_internal_type(self):
  88. return "JSONField"
  89. def get_db_prep_value(self, value, connection, prepared=False):
  90. if not prepared:
  91. value = self.get_prep_value(value)
  92. return connection.ops.adapt_json_value(value, self.encoder)
  93. def get_db_prep_save(self, value, connection):
  94. # This slightly involved logic is to allow for `None` to be used to
  95. # store SQL `NULL` while `Value(None, JSONField())` can be used to
  96. # store JSON `null` while preventing compilable `as_sql` values from
  97. # making their way to `get_db_prep_value`, which is what the `super()`
  98. # implementation does.
  99. if value is None:
  100. return value
  101. if (
  102. isinstance(value, expressions.Value)
  103. and value.value is None
  104. and isinstance(value.output_field, JSONField)
  105. ):
  106. value = None
  107. return super().get_db_prep_save(value, connection)
  108. def get_transform(self, name):
  109. transform = super().get_transform(name)
  110. if transform:
  111. return transform
  112. return KeyTransformFactory(name)
  113. def validate(self, value, model_instance):
  114. super().validate(value, model_instance)
  115. try:
  116. json.dumps(value, cls=self.encoder)
  117. except TypeError:
  118. raise exceptions.ValidationError(
  119. self.error_messages["invalid"],
  120. code="invalid",
  121. params={"value": value},
  122. )
  123. def value_to_string(self, obj):
  124. return self.value_from_object(obj)
  125. def formfield(self, **kwargs):
  126. return super().formfield(
  127. **{
  128. "form_class": forms.JSONField,
  129. "encoder": self.encoder,
  130. "decoder": self.decoder,
  131. **kwargs,
  132. }
  133. )
  134. class DataContains(FieldGetDbPrepValueMixin, PostgresOperatorLookup):
  135. lookup_name = "contains"
  136. postgres_operator = "@>"
  137. def as_sql(self, compiler, connection):
  138. if not connection.features.supports_json_field_contains:
  139. raise NotSupportedError(
  140. "contains lookup is not supported on this database backend."
  141. )
  142. lhs, lhs_params = self.process_lhs(compiler, connection)
  143. rhs, rhs_params = self.process_rhs(compiler, connection)
  144. params = tuple(lhs_params) + tuple(rhs_params)
  145. return "JSON_CONTAINS(%s, %s)" % (lhs, rhs), params
  146. class ContainedBy(FieldGetDbPrepValueMixin, PostgresOperatorLookup):
  147. lookup_name = "contained_by"
  148. postgres_operator = "<@"
  149. def as_sql(self, compiler, connection):
  150. if not connection.features.supports_json_field_contains:
  151. raise NotSupportedError(
  152. "contained_by lookup is not supported on this database backend."
  153. )
  154. lhs, lhs_params = self.process_lhs(compiler, connection)
  155. rhs, rhs_params = self.process_rhs(compiler, connection)
  156. params = tuple(rhs_params) + tuple(lhs_params)
  157. return "JSON_CONTAINS(%s, %s)" % (rhs, lhs), params
  158. class HasKeyLookup(PostgresOperatorLookup):
  159. logical_operator = None
  160. def compile_json_path_final_key(self, connection, key_transform):
  161. # Compile the final key without interpreting ints as array elements.
  162. return ".%s" % json.dumps(key_transform)
  163. def _as_sql_parts(self, compiler, connection):
  164. # Process JSON path from the left-hand side.
  165. if isinstance(self.lhs, KeyTransform):
  166. lhs_sql, lhs_params, lhs_key_transforms = self.lhs.preprocess_lhs(
  167. compiler, connection
  168. )
  169. lhs_json_path = connection.ops.compile_json_path(lhs_key_transforms)
  170. else:
  171. lhs_sql, lhs_params = self.process_lhs(compiler, connection)
  172. lhs_json_path = "$"
  173. # Process JSON path from the right-hand side.
  174. rhs = self.rhs
  175. if not isinstance(rhs, (list, tuple)):
  176. rhs = [rhs]
  177. for key in rhs:
  178. if isinstance(key, KeyTransform):
  179. *_, rhs_key_transforms = key.preprocess_lhs(compiler, connection)
  180. else:
  181. rhs_key_transforms = [key]
  182. *rhs_key_transforms, final_key = rhs_key_transforms
  183. rhs_json_path = connection.ops.compile_json_path(
  184. rhs_key_transforms, include_root=False
  185. )
  186. rhs_json_path += self.compile_json_path_final_key(connection, final_key)
  187. yield lhs_sql, lhs_params, lhs_json_path + rhs_json_path
  188. def _combine_sql_parts(self, parts):
  189. # Add condition for each key.
  190. if self.logical_operator:
  191. return "(%s)" % self.logical_operator.join(parts)
  192. return "".join(parts)
  193. def as_sql(self, compiler, connection, template=None):
  194. sql_parts = []
  195. params = []
  196. for lhs_sql, lhs_params, rhs_json_path in self._as_sql_parts(
  197. compiler, connection
  198. ):
  199. sql_parts.append(template % (lhs_sql, "%s"))
  200. params.extend([*lhs_params, rhs_json_path])
  201. return self._combine_sql_parts(sql_parts), tuple(params)
  202. def as_mysql(self, compiler, connection):
  203. return self.as_sql(
  204. compiler, connection, template="JSON_CONTAINS_PATH(%s, 'one', %s)"
  205. )
  206. def as_oracle(self, compiler, connection):
  207. # Use a custom delimiter to prevent the JSON path from escaping the SQL
  208. # literal. See comment in KeyTransform.
  209. template = "JSON_EXISTS(%s, q'\uffff%s\uffff')"
  210. sql_parts = []
  211. params = []
  212. for lhs_sql, lhs_params, rhs_json_path in self._as_sql_parts(
  213. compiler, connection
  214. ):
  215. # Add right-hand-side directly into SQL because it cannot be passed
  216. # as bind variables to JSON_EXISTS. It might result in invalid
  217. # queries but it is assumed that it cannot be evaded because the
  218. # path is JSON serialized.
  219. sql_parts.append(template % (lhs_sql, rhs_json_path))
  220. params.extend(lhs_params)
  221. return self._combine_sql_parts(sql_parts), tuple(params)
  222. def as_postgresql(self, compiler, connection):
  223. if isinstance(self.rhs, KeyTransform):
  224. *_, rhs_key_transforms = self.rhs.preprocess_lhs(compiler, connection)
  225. for key in rhs_key_transforms[:-1]:
  226. self.lhs = KeyTransform(key, self.lhs)
  227. self.rhs = rhs_key_transforms[-1]
  228. return super().as_postgresql(compiler, connection)
  229. def as_sqlite(self, compiler, connection):
  230. return self.as_sql(
  231. compiler, connection, template="JSON_TYPE(%s, %s) IS NOT NULL"
  232. )
  233. class HasKey(HasKeyLookup):
  234. lookup_name = "has_key"
  235. postgres_operator = "?"
  236. prepare_rhs = False
  237. class HasKeys(HasKeyLookup):
  238. lookup_name = "has_keys"
  239. postgres_operator = "?&"
  240. logical_operator = " AND "
  241. def get_prep_lookup(self):
  242. return [str(item) for item in self.rhs]
  243. class HasAnyKeys(HasKeys):
  244. lookup_name = "has_any_keys"
  245. postgres_operator = "?|"
  246. logical_operator = " OR "
  247. class HasKeyOrArrayIndex(HasKey):
  248. def compile_json_path_final_key(self, connection, key_transform):
  249. return connection.ops.compile_json_path([key_transform], include_root=False)
  250. class CaseInsensitiveMixin:
  251. """
  252. Mixin to allow case-insensitive comparison of JSON values on MySQL.
  253. MySQL handles strings used in JSON context using the utf8mb4_bin collation.
  254. Because utf8mb4_bin is a binary collation, comparison of JSON values is
  255. case-sensitive.
  256. """
  257. def process_lhs(self, compiler, connection):
  258. lhs, lhs_params = super().process_lhs(compiler, connection)
  259. if connection.vendor == "mysql":
  260. return "LOWER(%s)" % lhs, lhs_params
  261. return lhs, lhs_params
  262. def process_rhs(self, compiler, connection):
  263. rhs, rhs_params = super().process_rhs(compiler, connection)
  264. if connection.vendor == "mysql":
  265. return "LOWER(%s)" % rhs, rhs_params
  266. return rhs, rhs_params
  267. class JSONExact(lookups.Exact):
  268. # RemovedInDjango70Warning: When the deprecation period is over, remove
  269. # the following line.
  270. can_use_none_as_rhs = True
  271. def process_rhs(self, compiler, connection):
  272. if self.rhs is None and not isinstance(self.lhs, KeyTransform):
  273. warnings.warn(
  274. "Using None as the right-hand side of an exact lookup on JSONField to "
  275. "mean JSON scalar 'null' is deprecated. Use JSONNull() instead (or use "
  276. "the __isnull lookup if you meant SQL NULL).",
  277. RemovedInDjango70Warning,
  278. skip_file_prefixes=django_file_prefixes(),
  279. )
  280. rhs, rhs_params = super().process_rhs(compiler, connection)
  281. # RemovedInDjango70Warning: When the deprecation period is over, remove
  282. # The following if-block entirely.
  283. # Treat None lookup values as null.
  284. if rhs == "%s" and (*rhs_params,) == (None,):
  285. rhs_params = ("null",)
  286. if connection.vendor == "mysql" and not isinstance(
  287. self.rhs, expressions.JSONNull
  288. ):
  289. func = ["JSON_EXTRACT(%s, '$')"] * len(rhs_params)
  290. rhs %= tuple(func)
  291. return rhs, rhs_params
  292. def as_oracle(self, compiler, connection):
  293. lhs, lhs_params = self.process_lhs(compiler, connection)
  294. rhs, rhs_params = self.process_rhs(compiler, connection)
  295. if connection.features.supports_primitives_in_json_field:
  296. lhs = f"JSON({lhs})"
  297. rhs = f"JSON({rhs})"
  298. return f"JSON_EQUAL({lhs}, {rhs} ERROR ON ERROR)", (*lhs_params, *rhs_params)
  299. class JSONIContains(CaseInsensitiveMixin, lookups.IContains):
  300. pass
  301. class ProcessJSONLHSMixin:
  302. def _get_json_path(self, connection, key_transforms):
  303. if key_transforms is None:
  304. return "$"
  305. return connection.ops.compile_json_path(key_transforms)
  306. def _process_as_oracle(self, sql, params, connection, key_transforms=None):
  307. json_path = self._get_json_path(connection, key_transforms)
  308. if connection.features.supports_primitives_in_json_field:
  309. template = (
  310. "COALESCE("
  311. "JSON_VALUE(%s, q'\uffff%s\uffff'),"
  312. "JSON_QUERY(%s, q'\uffff%s\uffff' DISALLOW SCALARS)"
  313. ")"
  314. )
  315. else:
  316. template = (
  317. "COALESCE("
  318. "JSON_QUERY(%s, q'\uffff%s\uffff'),"
  319. "JSON_VALUE(%s, q'\uffff%s\uffff')"
  320. ")"
  321. )
  322. # Add paths directly into SQL because path expressions cannot be passed
  323. # as bind variables on Oracle. Use a custom delimiter to prevent the
  324. # JSON path from escaping the SQL literal. Each key in the JSON path is
  325. # passed through json.dumps() with ensure_ascii=True (the default),
  326. # which converts the delimiter into the escaped \uffff format. This
  327. # ensures that the delimiter is not present in the JSON path.
  328. sql = template % ((sql, json_path) * 2)
  329. return sql, params * 2
  330. def _process_as_sqlite(self, sql, params, connection, key_transforms=None):
  331. json_path = self._get_json_path(connection, key_transforms)
  332. datatype_values = ",".join(
  333. [repr(value) for value in connection.ops.jsonfield_datatype_values]
  334. )
  335. return (
  336. "(CASE WHEN JSON_TYPE(%s, %%s) IN (%s) "
  337. "THEN JSON_TYPE(%s, %%s) ELSE JSON_EXTRACT(%s, %%s) END)"
  338. ) % (sql, datatype_values, sql, sql), (*params, json_path) * 3
  339. def _process_as_mysql(self, sql, params, connection, key_transforms=None):
  340. json_path = self._get_json_path(connection, key_transforms)
  341. return "JSON_EXTRACT(%s, %%s)" % sql, (*params, json_path)
  342. class JSONIn(ProcessJSONLHSMixin, lookups.In):
  343. def resolve_expression_parameter(self, compiler, connection, sql, param):
  344. sql, params = super().resolve_expression_parameter(
  345. compiler,
  346. connection,
  347. sql,
  348. param,
  349. )
  350. if not connection.features.has_native_json_field and (
  351. not hasattr(param, "as_sql") or isinstance(param, expressions.Value)
  352. ):
  353. if connection.vendor == "oracle":
  354. value = param.value if hasattr(param, "value") else json.loads(param)
  355. sql = "%s(JSON_OBJECT('value' VALUE %%s FORMAT JSON), '$.value')"
  356. if isinstance(value, (list, dict)):
  357. sql %= "JSON_QUERY"
  358. else:
  359. sql %= "JSON_VALUE"
  360. elif connection.vendor == "mysql" or (
  361. connection.vendor == "sqlite"
  362. and params[0] not in connection.ops.jsonfield_datatype_values
  363. ):
  364. sql = "JSON_EXTRACT(%s, '$')"
  365. if connection.vendor == "mysql" and connection.mysql_is_mariadb:
  366. sql = "JSON_UNQUOTE(%s)" % sql
  367. return sql, params
  368. def process_lhs(self, compiler, connection):
  369. sql, params = super().process_lhs(compiler, connection)
  370. if isinstance(self.lhs, KeyTransform):
  371. return sql, params
  372. if connection.vendor == "mysql":
  373. return self._process_as_mysql(sql, params, connection)
  374. elif connection.vendor == "oracle":
  375. return self._process_as_oracle(sql, params, connection)
  376. elif connection.vendor == "sqlite":
  377. return self._process_as_sqlite(sql, params, connection)
  378. return sql, params
  379. def as_oracle(self, compiler, connection):
  380. if (
  381. connection.features.supports_primitives_in_json_field
  382. and isinstance(self.rhs, expressions.ExpressionList)
  383. and expressions.JSONNull() in self.rhs.get_source_expressions()
  384. ):
  385. # Break the lookup into multiple exact lookups combined with OR, as
  386. # Oracle does not support directly extracting JSON scalar null as a
  387. # value in the right-hand side of an IN clause.
  388. exact_lookup = self.lhs.get_lookup("exact")
  389. sql_parts = []
  390. all_params = ()
  391. for expr in self.rhs.get_source_expressions():
  392. lookup = exact_lookup(self.lhs, expr)
  393. sql, params = lookup.as_oracle(compiler, connection)
  394. sql_parts.append(f"({sql})")
  395. all_params = (*all_params, *params)
  396. sql = " OR ".join(sql_parts)
  397. return sql, all_params
  398. return self.as_sql(compiler, connection)
  399. JSONField.register_lookup(DataContains)
  400. JSONField.register_lookup(ContainedBy)
  401. JSONField.register_lookup(HasKey)
  402. JSONField.register_lookup(HasKeys)
  403. JSONField.register_lookup(HasAnyKeys)
  404. JSONField.register_lookup(JSONExact)
  405. JSONField.register_lookup(JSONIContains)
  406. JSONField.register_lookup(JSONIn)
  407. class KeyTransform(ProcessJSONLHSMixin, Transform):
  408. postgres_operator = "->"
  409. postgres_nested_operator = "#>"
  410. def __init__(self, key_name, *args, **kwargs):
  411. super().__init__(*args, **kwargs)
  412. self.key_name = str(key_name)
  413. def preprocess_lhs(self, compiler, connection):
  414. key_transforms = [self.key_name]
  415. previous = self.lhs
  416. while isinstance(previous, KeyTransform):
  417. key_transforms.insert(0, previous.key_name)
  418. previous = previous.lhs
  419. lhs, params = compiler.compile(previous)
  420. if connection.vendor == "oracle":
  421. # Escape string-formatting.
  422. key_transforms = [key.replace("%", "%%") for key in key_transforms]
  423. return lhs, params, key_transforms
  424. def as_mysql(self, compiler, connection):
  425. lhs, params, key_transforms = self.preprocess_lhs(compiler, connection)
  426. return self._process_as_mysql(lhs, params, connection, key_transforms)
  427. def as_oracle(self, compiler, connection):
  428. lhs, params, key_transforms = self.preprocess_lhs(compiler, connection)
  429. return self._process_as_oracle(lhs, params, connection, key_transforms)
  430. def as_postgresql(self, compiler, connection):
  431. lhs, params, key_transforms = self.preprocess_lhs(compiler, connection)
  432. if len(key_transforms) > 1:
  433. sql = "(%s %s %%s)" % (lhs, self.postgres_nested_operator)
  434. return sql, (*params, key_transforms)
  435. try:
  436. lookup = int(self.key_name)
  437. except ValueError:
  438. lookup = self.key_name
  439. return "(%s %s %%s)" % (lhs, self.postgres_operator), (*params, lookup)
  440. def as_sqlite(self, compiler, connection):
  441. lhs, params, key_transforms = self.preprocess_lhs(compiler, connection)
  442. return self._process_as_sqlite(lhs, params, connection, key_transforms)
  443. class KeyTextTransform(KeyTransform):
  444. postgres_operator = "->>"
  445. postgres_nested_operator = "#>>"
  446. output_field = TextField()
  447. def as_mysql(self, compiler, connection):
  448. # The ->> operator is not supported on MariaDB (see MDEV-13594) and
  449. # only supported against columns on MySQL.
  450. if (
  451. connection.mysql_is_mariadb
  452. or getattr(self.lhs.output_field, "model", None) is None
  453. ):
  454. sql, params = super().as_mysql(compiler, connection)
  455. return "JSON_UNQUOTE(%s)" % sql, params
  456. else:
  457. lhs, params, key_transforms = self.preprocess_lhs(compiler, connection)
  458. json_path = connection.ops.compile_json_path(key_transforms)
  459. return "(%s ->> %%s)" % lhs, (*params, json_path)
  460. @classmethod
  461. def from_lookup(cls, lookup):
  462. transform, *keys = lookup.split(LOOKUP_SEP)
  463. if not keys:
  464. raise ValueError("Lookup must contain key or index transforms.")
  465. for key in keys:
  466. transform = cls(key, transform)
  467. return transform
  468. KT = KeyTextTransform.from_lookup
  469. class KeyTransformTextLookupMixin:
  470. """
  471. Mixin for combining with a lookup expecting a text lhs from a JSONField
  472. key lookup. On PostgreSQL, make use of the ->> operator instead of casting
  473. key values to text and performing the lookup on the resulting
  474. representation.
  475. """
  476. def __init__(self, key_transform, *args, **kwargs):
  477. if not isinstance(key_transform, KeyTransform):
  478. raise TypeError(
  479. "Transform should be an instance of KeyTransform in order to "
  480. "use this lookup."
  481. )
  482. key_text_transform = KeyTextTransform(
  483. key_transform.key_name,
  484. *key_transform.source_expressions,
  485. **key_transform.extra,
  486. )
  487. super().__init__(key_text_transform, *args, **kwargs)
  488. class KeyTransformIsNull(lookups.IsNull):
  489. # key__isnull=False is the same as has_key='key'
  490. def as_oracle(self, compiler, connection):
  491. sql, params = HasKeyOrArrayIndex(
  492. self.lhs.lhs,
  493. self.lhs.key_name,
  494. ).as_oracle(compiler, connection)
  495. if not self.rhs:
  496. return sql, params
  497. # Column doesn't have a key or IS NULL.
  498. lhs, lhs_params, _ = self.lhs.preprocess_lhs(compiler, connection)
  499. return "(NOT %s OR %s IS NULL)" % (sql, lhs), tuple(params) + tuple(lhs_params)
  500. def as_sqlite(self, compiler, connection):
  501. template = "JSON_TYPE(%s, %s) IS NULL"
  502. if not self.rhs:
  503. template = "JSON_TYPE(%s, %s) IS NOT NULL"
  504. return HasKeyOrArrayIndex(self.lhs.lhs, self.lhs.key_name).as_sql(
  505. compiler,
  506. connection,
  507. template=template,
  508. )
  509. class KeyTransformIn(JSONIn):
  510. pass
  511. class KeyTransformExact(JSONExact):
  512. # RemovedInDjango70Warning: When deprecation period ends, uncomment the
  513. # flag below.
  514. # can_use_none_as_rhs = True
  515. def process_rhs(self, compiler, connection):
  516. if isinstance(self.rhs, KeyTransform):
  517. return super(lookups.Exact, self).process_rhs(compiler, connection)
  518. rhs, rhs_params = super().process_rhs(compiler, connection)
  519. if connection.vendor == "oracle":
  520. func = []
  521. sql = "%s(JSON_OBJECT('value' VALUE %%s FORMAT JSON), '$.value')"
  522. for value in rhs_params:
  523. value = json.loads(value)
  524. if isinstance(value, (list, dict)):
  525. func.append(sql % "JSON_QUERY")
  526. else:
  527. func.append(sql % "JSON_VALUE")
  528. rhs %= tuple(func)
  529. elif connection.vendor == "sqlite":
  530. func = []
  531. for value in rhs_params:
  532. if value in connection.ops.jsonfield_datatype_values:
  533. func.append("%s")
  534. else:
  535. func.append("JSON_EXTRACT(%s, '$')")
  536. rhs %= tuple(func)
  537. return rhs, rhs_params
  538. def as_oracle(self, compiler, connection):
  539. rhs, rhs_params = super().process_rhs(compiler, connection)
  540. if rhs_params and (*rhs_params,) == ("null",):
  541. # Field has key and it's NULL.
  542. has_key_expr = HasKeyOrArrayIndex(self.lhs.lhs, self.lhs.key_name)
  543. has_key_sql, has_key_params = has_key_expr.as_oracle(compiler, connection)
  544. is_null_expr = self.lhs.get_lookup("isnull")(self.lhs, True)
  545. is_null_sql, is_null_params = is_null_expr.as_sql(compiler, connection)
  546. return (
  547. "%s AND %s" % (has_key_sql, is_null_sql),
  548. tuple(has_key_params) + tuple(is_null_params),
  549. )
  550. return super().as_sql(compiler, connection)
  551. class KeyTransformIExact(
  552. CaseInsensitiveMixin, KeyTransformTextLookupMixin, lookups.IExact
  553. ):
  554. can_use_none_as_rhs = True
  555. def as_sql(self, compiler, connection):
  556. if self.rhs is None:
  557. # Interpret __iexact=None on KeyTextTransform as __exact=None on
  558. # KeyTransform.
  559. keytransform = KeyTransform(self.lhs.key_name, self.lhs.lhs)
  560. exact_lookup = keytransform.get_lookup("exact")(keytransform, self.rhs)
  561. # Delegate to the backend vendor method, if it exists.
  562. vendor = connection.vendor
  563. as_vendor = getattr(exact_lookup, f"as_{vendor}", exact_lookup.as_sql)
  564. return as_vendor(compiler, connection)
  565. return super().as_sql(compiler, connection)
  566. class KeyTransformIContains(
  567. CaseInsensitiveMixin, KeyTransformTextLookupMixin, lookups.IContains
  568. ):
  569. pass
  570. class KeyTransformStartsWith(KeyTransformTextLookupMixin, lookups.StartsWith):
  571. pass
  572. class KeyTransformIStartsWith(
  573. CaseInsensitiveMixin, KeyTransformTextLookupMixin, lookups.IStartsWith
  574. ):
  575. pass
  576. class KeyTransformEndsWith(KeyTransformTextLookupMixin, lookups.EndsWith):
  577. pass
  578. class KeyTransformIEndsWith(
  579. CaseInsensitiveMixin, KeyTransformTextLookupMixin, lookups.IEndsWith
  580. ):
  581. pass
  582. class KeyTransformRegex(KeyTransformTextLookupMixin, lookups.Regex):
  583. pass
  584. class KeyTransformIRegex(
  585. CaseInsensitiveMixin, KeyTransformTextLookupMixin, lookups.IRegex
  586. ):
  587. pass
  588. class KeyTransformNumericLookupMixin:
  589. def process_rhs(self, compiler, connection):
  590. rhs, rhs_params = super().process_rhs(compiler, connection)
  591. if not connection.features.has_native_json_field and self.rhs_is_direct_value():
  592. rhs_params = tuple(json.loads(value) for value in rhs_params)
  593. return rhs, rhs_params
  594. class KeyTransformLt(KeyTransformNumericLookupMixin, lookups.LessThan):
  595. pass
  596. class KeyTransformLte(KeyTransformNumericLookupMixin, lookups.LessThanOrEqual):
  597. pass
  598. class KeyTransformGt(KeyTransformNumericLookupMixin, lookups.GreaterThan):
  599. pass
  600. class KeyTransformGte(KeyTransformNumericLookupMixin, lookups.GreaterThanOrEqual):
  601. pass
  602. KeyTransform.register_lookup(KeyTransformIn)
  603. KeyTransform.register_lookup(KeyTransformExact)
  604. KeyTransform.register_lookup(KeyTransformIExact)
  605. KeyTransform.register_lookup(KeyTransformIsNull)
  606. KeyTransform.register_lookup(KeyTransformIContains)
  607. KeyTransform.register_lookup(KeyTransformStartsWith)
  608. KeyTransform.register_lookup(KeyTransformIStartsWith)
  609. KeyTransform.register_lookup(KeyTransformEndsWith)
  610. KeyTransform.register_lookup(KeyTransformIEndsWith)
  611. KeyTransform.register_lookup(KeyTransformRegex)
  612. KeyTransform.register_lookup(KeyTransformIRegex)
  613. KeyTransform.register_lookup(KeyTransformLt)
  614. KeyTransform.register_lookup(KeyTransformLte)
  615. KeyTransform.register_lookup(KeyTransformGt)
  616. KeyTransform.register_lookup(KeyTransformGte)
  617. class KeyTransformFactory:
  618. def __init__(self, key_name):
  619. self.key_name = key_name
  620. def __call__(self, *args, **kwargs):
  621. return KeyTransform(self.key_name, *args, **kwargs)