Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Used JSON_OBJECT database function on PostgreSQL 16+. #17664

Merged
merged 1 commit into from
Dec 31, 2023

Conversation

ngnpope
Copy link
Member

@ngnpope ngnpope commented Dec 30, 2023

Updates JSONObject() to use the standard SQL function JSON_OBJECT on PostgreSQL 16+.

This makes Oracle and PostgreSQL 16+ share the same implementation.

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)
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Adding the strict flag here avoids silently dropping the last argument if an odd number of arguments are provided to JSONObject().

@felixxm
Copy link
Member

felixxm commented Dec 31, 2023

@ngnpope Thanks 👍

@felixxm felixxm merged commit 81ccf92 into django:main Dec 31, 2023
34 checks passed
@felixxm felixxm changed the title Used standard JSON_OBJECT function on PostgreSQL 16+. Used JSON_OBJECT database function on PostgreSQL 16+. Dec 31, 2023
@ngnpope ngnpope deleted the pg16-json-object branch December 31, 2023 08:57
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])
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm late to the party, but something that I usually recommend is to avoid creating a whole list in memory before calling join, since it handles generators very nicely and it uses less memory:

Suggested change
return ", ".join([" VALUE ".join(pair) for pair in pairs])
return ", ".join(" VALUE ".join(pair) for pair in pairs)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A list comprehension is preferable here as str.join() converts to list internally anyway. It is better performance to provide a list up front.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you! Now that you mention it, I recall this was already discussed in another Django PR. I need to re-learn this! 📚

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
3 participants