Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -429,19 +429,16 @@ def _prepare_filter_condition(self, expression: FilterExpression) -> _Document:
raise NotImplementedError(
"Use contains, contains_any, or contains_all for Azure DocumentDB list fields."
)
operands = [_prepare_filter_operand(field, item) for item in value]
# Portable membership, unlike eq/ne, never matches a null field, even when None is an operand.
operands = [_prepare_filter_operand(field, item) for item in value if item is not None]
operands = [item for item in operands if item is not _TYPE_MISMATCH]
if not operands:
if operator == "in":
return self._false_filter()
return {"$and": [{name: {"$exists": True}}, {name: {"$ne": None}}]}
condition = {name: {"$in" if operator == "in" else "$nin": operands}}
if operator == "not_in" or None in operands:
guards: list[_Document] = [{name: {"$exists": True}}]
if operator == "not_in":
guards.append({name: {"$ne": None}})
guards.append(condition)
return {"$and": guards}
if operator == "not_in":
return {"$and": [{name: {"$exists": True}}, {name: {"$ne": None}}, condition]}
return condition
if operator in {"contains", "contains_any", "contains_all"}:
if field.type_ != "list":
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,23 @@ def test_empty_membership_semantics(collection):
}


def test_membership_never_matches_null_operands(collection):
assert collection._prepare_filter(Filter("category", "in", [None, "database"])) == {
"category": {"$in": ["database"]}
}
assert collection._prepare_filter(Filter("category", "in", [None])) == {"_id": {"$exists": False}}
assert collection._prepare_filter(Filter("category", "not_in", [None, "database"])) == {
"$and": [
{"category": {"$exists": True}},
{"category": {"$ne": None}},
{"category": {"$nin": ["database"]}},
]
}
assert collection._prepare_filter(Filter("category", "not_in", [None])) == {
"$and": [{"category": {"$exists": True}}, {"category": {"$ne": None}}]
}


def test_filter_type_mismatches_preserve_bool_number_distinction(collection):
assert collection._prepare_filter(Filter("number", "eq", True)) == {"_id": {"$exists": False}}
assert collection._prepare_filter(Filter("flag", "eq", 1)) == {"_id": {"$exists": False}}
Expand Down
Loading