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
7 changes: 6 additions & 1 deletion sqlalchemy_history/relationship_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,12 @@ def criteria(self, obj):
return self.many_to_one_criteria(obj)
else:
reflector = VersionExpressionReflector(obj, self.property)
return reflector(self.property.primaryjoin)
criteria = reflector(self.property.primaryjoin)

# For many-to-many relationships, we also need to include the secondary join
if direction.name == "MANYTOMANY" and self.property.secondaryjoin is not None:
criteria = sa.and_(criteria, reflector(self.property.secondaryjoin))
return criteria
Copy link
Collaborator

Choose a reason for hiding this comment

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

you can have this unit test in tests/relationships/test_non_versioned_classes.py

def test_no_cartesian_product_with_multiple_unrelated_tags(self):
    # Create an article with one tag
    article = self.Article(name="Some article")
    tag1 = self.Tag(name="tag1")
    article.tags.append(tag1)
    self.session.add(article)
    self.session.commit()

    # Create another article with a different tag
    article2 = self.Article(name="Another article")
    tag2 = self.Tag(name="tag2")
    article2.tags.append(tag2)
    self.session.add(article2)
    self.session.commit()

    # Ensure the first article's version only has its own tag, not all tags
    assert len(article.versions[0].tags) == 1
    assert article.versions[0].tags[0] == tag1


def many_to_many_criteria(self, obj):
"""Returns the many-to-many query.
Expand Down
19 changes: 19 additions & 0 deletions tests/relationships/test_non_versioned_classes.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,3 +101,22 @@ def test_single_insert(self):
self.session.commit()
assert len(article.versions[0].tags) == 1
assert isinstance(article.versions[0].tags[0], self.Tag)

def test_no_cartesian_product_with_multiple_unrelated_tags(self):
# Create an article with one tag
article = self.Article(name="Some article")
tag1 = self.Tag(name="tag1")
article.tags.append(tag1)
self.session.add(article)
self.session.commit()

# Create another article with a different tag
article2 = self.Article(name="Another article")
tag2 = self.Tag(name="tag2")
article2.tags.append(tag2)
self.session.add(article2)
self.session.commit()

# Ensure the first article's version only has its own tag, not all tags
assert len(article.versions[0].tags) == 1
assert article.versions[0].tags[0] == tag1