json.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. from django.db import NotSupportedError
  2. from django.db.models.expressions import Func, Value
  3. from django.db.models.fields import TextField
  4. from django.db.models.fields.json import JSONField
  5. from django.db.models.functions import Cast
  6. class JSONArray(Func):
  7. function = "JSON_ARRAY"
  8. output_field = JSONField()
  9. def as_sql(self, compiler, connection, **extra_context):
  10. if not connection.features.supports_json_field:
  11. raise NotSupportedError(
  12. "JSONFields are not supported on this database backend."
  13. )
  14. return super().as_sql(compiler, connection, **extra_context)
  15. def as_native(self, compiler, connection, *, returning, **extra_context):
  16. # PostgreSQL 16+ and Oracle remove SQL NULL values from the array by
  17. # default. Adds the NULL ON NULL clause to keep NULL values in the
  18. # array, mapping them to JSON null values, which matches the behavior
  19. # of SQLite.
  20. null_on_null = "NULL ON NULL" if len(self.get_source_expressions()) > 0 else ""
  21. return self.as_sql(
  22. compiler,
  23. connection,
  24. template=(
  25. f"%(function)s(%(expressions)s {null_on_null} RETURNING {returning})"
  26. ),
  27. **extra_context,
  28. )
  29. def as_postgresql(self, compiler, connection, **extra_context):
  30. # Casting source expressions is only required using JSONB_BUILD_ARRAY
  31. # or when using JSON_ARRAY on PostgreSQL 16+ with server-side bindings.
  32. # This is done in all cases for consistency.
  33. casted_obj = self.copy()
  34. casted_obj.set_source_expressions(
  35. [
  36. (
  37. # Conditional Cast to avoid unnecessary wrapping.
  38. expression
  39. if isinstance(expression, Cast)
  40. else Cast(expression, expression.output_field)
  41. )
  42. for expression in casted_obj.get_source_expressions()
  43. ]
  44. )
  45. if connection.features.is_postgresql_16:
  46. return casted_obj.as_native(
  47. compiler, connection, returning="JSONB", **extra_context
  48. )
  49. return casted_obj.as_sql(
  50. compiler,
  51. connection,
  52. function="JSONB_BUILD_ARRAY",
  53. **extra_context,
  54. )
  55. def as_oracle(self, compiler, connection, **extra_context):
  56. return self.as_native(compiler, connection, returning="CLOB", **extra_context)
  57. class JSONObject(Func):
  58. function = "JSON_OBJECT"
  59. output_field = JSONField()
  60. def __init__(self, **fields):
  61. expressions = []
  62. for key, value in fields.items():
  63. expressions.extend((Value(key), value))
  64. super().__init__(*expressions)
  65. def as_sql(self, compiler, connection, **extra_context):
  66. if not connection.features.has_json_object_function:
  67. raise NotSupportedError(
  68. "JSONObject() is not supported on this database backend."
  69. )
  70. return super().as_sql(compiler, connection, **extra_context)
  71. def join(self, args):
  72. pairs = zip(args[::2], args[1::2], strict=True)
  73. # Wrap 'key' in parentheses in case of postgres cast :: syntax.
  74. return ", ".join([f"({key}) VALUE {value}" for key, value in pairs])
  75. def as_native(self, compiler, connection, *, returning, **extra_context):
  76. return self.as_sql(
  77. compiler,
  78. connection,
  79. arg_joiner=self,
  80. template=f"%(function)s(%(expressions)s RETURNING {returning})",
  81. **extra_context,
  82. )
  83. def as_postgresql(self, compiler, connection, **extra_context):
  84. # Casting keys to text is only required when using JSONB_BUILD_OBJECT
  85. # or when using JSON_OBJECT on PostgreSQL 16+ with server-side
  86. # bindings. This is done in all cases for consistency.
  87. copy = self.copy()
  88. copy.set_source_expressions(
  89. [
  90. Cast(expression, TextField()) if index % 2 == 0 else expression
  91. for index, expression in enumerate(copy.get_source_expressions())
  92. ]
  93. )
  94. if connection.features.is_postgresql_16:
  95. return copy.as_native(
  96. compiler, connection, returning="JSONB", **extra_context
  97. )
  98. return super(JSONObject, copy).as_sql(
  99. compiler,
  100. connection,
  101. function="JSONB_BUILD_OBJECT",
  102. **extra_context,
  103. )
  104. def as_oracle(self, compiler, connection, **extra_context):
  105. return self.as_native(compiler, connection, returning="CLOB", **extra_context)