-
Notifications
You must be signed in to change notification settings - Fork 27
POC add expression support to QuerySet.update() #111
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
Closed
Closed
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -3,9 +3,9 @@ | |
from collections import defaultdict | ||
|
||
from bson import SON | ||
from django.core.exceptions import EmptyResultSet, FullResultSet | ||
from django.db import DatabaseError, IntegrityError, NotSupportedError | ||
from django.db.models import Count, Expression | ||
from django.core.exceptions import EmptyResultSet, FieldError, FullResultSet | ||
from django.db import IntegrityError, NotSupportedError | ||
from django.db.models import Count | ||
from django.db.models.aggregates import Aggregate, Variance | ||
from django.db.models.expressions import Case, Col, Ref, Value, When | ||
from django.db.models.functions.comparison import Coalesce | ||
|
@@ -581,7 +581,19 @@ def execute_sql(self, result_type): | |
self.pre_sql_setup() | ||
values = [] | ||
for field, _, value in self.query.values: | ||
if hasattr(value, "prepare_database_save"): | ||
if hasattr(value, "resolve_expression"): | ||
value = value.resolve_expression(self.query, allow_joins=False, for_save=True) | ||
if value.contains_aggregate: | ||
raise FieldError( | ||
"Aggregate functions are not allowed in this query " | ||
f"({field.name}={value})." | ||
) | ||
if value.contains_over_clause: | ||
raise FieldError( | ||
"Window expressions are not allowed in this query " | ||
f"({field.name}={value})." | ||
) | ||
elif hasattr(value, "prepare_database_save"): | ||
if field.remote_field: | ||
value = value.prepare_database_save(field) | ||
else: | ||
|
@@ -591,42 +603,44 @@ def execute_sql(self, result_type): | |
f"{field.__class__.__name__}." | ||
) | ||
prepared = field.get_db_prep_save(value, connection=self.connection) | ||
values.append((field, prepared)) | ||
if hasattr(value, "as_mql"): | ||
prepared = prepared.as_mql(self, self.connection) | ||
values.append((field.column, prepared)) | ||
try: | ||
criteria = self.build_query().mongo_query | ||
except EmptyResultSet: | ||
return 0 | ||
is_empty = not bool(values) | ||
rows = 0 if is_empty else self.update(values) | ||
if is_empty: | ||
rows = 0 | ||
else: | ||
base_pipeline = [ | ||
{"$match": criteria}, | ||
{"$set": dict(values)}, | ||
] | ||
count_pipeline = [*base_pipeline, {"$count": "count"}] | ||
pipeline = [ | ||
*base_pipeline, | ||
{ | ||
"$merge": { | ||
"into": self.collection_name, | ||
"whenMatched": "replace", | ||
"whenNotMatched": "discard", | ||
} | ||
}, | ||
] | ||
with self.connection.connection.start_session() as session, session.start_transaction(): | ||
result = next(self.collection.aggregate(count_pipeline), {"count": 0}) | ||
self.collection.aggregate(pipeline) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. what has been the output when you merge: |
||
rows = result["count"] | ||
# rows = 0 if is_empty else self.update(values) | ||
for query in self.query.get_related_updates(): | ||
aux_rows = query.get_compiler(self.using).execute_sql(result_type) | ||
if is_empty and aux_rows: | ||
rows = aux_rows | ||
is_empty = False | ||
return rows | ||
|
||
def update(self, values): | ||
spec = {} | ||
for field, value in values: | ||
if field.primary_key: | ||
raise DatabaseError("Cannot modify _id.") | ||
if isinstance(value, Expression): | ||
raise NotSupportedError("QuerySet.update() with expression not supported.") | ||
# .update(foo=123) --> {'$set': {'foo': 123}} | ||
spec.setdefault("$set", {})[field.column] = value | ||
return self.execute_update(spec) | ||
|
||
@wrap_database_errors | ||
def execute_update(self, update_spec): | ||
try: | ||
criteria = self.build_query().mongo_query | ||
except EmptyResultSet: | ||
return 0 | ||
return self.collection.update_many(criteria, update_spec).matched_count | ||
|
||
def check_query(self): | ||
super().check_query() | ||
if len([a for a in self.query.alias_map if self.query.alias_refcount[a]]) > 1: | ||
raise NotSupportedError( | ||
"Cannot use QuerySet.update() when querying across multiple collections on MongoDB." | ||
) | ||
|
||
def get_where(self): | ||
return self.query.where | ||
|
||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This part is the only thing that need focus. Here I just create the $merge pipeline and the affected rows pipeline with a single transaction. I really don't know if this is the way to go.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is the right way to go about it. having a transaction ensures that state isn't changed between the lookup and the update.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think we can use update many directly as Shane mentioned. I've re-read the docs and what the docs support are this three stages.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yeap, It works 🚀. So we are able to do the update without making two queries (one for count and the other for the update)