Skip to content

Commit

Permalink
Used JSON_OBJECT database function on PostgreSQL 16+.
Browse files Browse the repository at this point in the history
  • Loading branch information
ngnpope authored Dec 31, 2023
1 parent 9d52e07 commit 81ccf92
Showing 1 changed file with 24 additions and 19 deletions.
43 changes: 24 additions & 19 deletions django/db/models/functions/comparison.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,35 +159,40 @@ def as_sql(self, compiler, connection, **extra_context):
)
return super().as_sql(compiler, connection, **extra_context)

def as_postgresql(self, compiler, connection, **extra_context):
copy = self.copy()
copy.set_source_expressions(
[
Cast(expression, TextField()) if index % 2 == 0 else expression
for index, expression in enumerate(copy.get_source_expressions())
]
)
return super(JSONObject, copy).as_sql(
compiler,
connection,
function="JSONB_BUILD_OBJECT",
**extra_context,
)

def as_oracle(self, compiler, connection, **extra_context):
def as_native(self, compiler, connection, *, returning, **extra_context):
class ArgJoiner:
def join(self, args):
args = [" VALUE ".join(arg) for arg in zip(args[::2], args[1::2])]
return ", ".join(args)
pairs = zip(args[::2], args[1::2], strict=True)
return ", ".join([" VALUE ".join(pair) for pair in pairs])

return self.as_sql(
compiler,
connection,
arg_joiner=ArgJoiner(),
template="%(function)s(%(expressions)s RETURNING CLOB)",
template=f"%(function)s(%(expressions)s RETURNING {returning})",
**extra_context,
)

def as_postgresql(self, compiler, connection, **extra_context):
if not connection.features.is_postgresql_16:
copy = self.copy()
copy.set_source_expressions(
[
Cast(expression, TextField()) if index % 2 == 0 else expression
for index, expression in enumerate(copy.get_source_expressions())
]
)
return super(JSONObject, copy).as_sql(
compiler,
connection,
function="JSONB_BUILD_OBJECT",
**extra_context,
)
return self.as_native(compiler, connection, returning="JSONB", **extra_context)

def as_oracle(self, compiler, connection, **extra_context):
return self.as_native(compiler, connection, returning="CLOB", **extra_context)


class Least(Func):
"""
Expand Down

0 comments on commit 81ccf92

Please sign in to comment.