Skip to content

Commit

Permalink
fix(#25): handle attributes which are not accessible in ORM
Browse files Browse the repository at this point in the history
doing a check for property key before enabling active_history
to make sure it can be directly accessed by parent_cls
  • Loading branch information
indiVar0508 committed Feb 6, 2023
1 parent 3f0ae08 commit 7a2ebf9
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
5 changes: 4 additions & 1 deletion sqlalchemy_history/builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,10 @@ def enable_active_history(self, version_classes):
"""
for cls in version_classes:
for prop in sa.inspect(cls).iterate_properties:
getattr(cls, prop.key).impl.active_history = True
if hasattr(cls, prop.key):
# Mapper Arg `_sa_polymorphic_on` appear as columnproperty but is not attr of cls
# Giving AttrError
getattr(cls, prop.key).impl.active_history = True

def create_column_aliases(self, version_classes):
"""
Expand Down
46 changes: 46 additions & 0 deletions tests/reported_bugs/test_bug_25_polymorphic_on_attr.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import datetime
import sqlalchemy as sa
from copy import copy
from tests import TestCase


class TestBug25(TestCase):
# ref: https://github.com/corridor/sqlalchemy-history/issues/25
def create_models(self):
class Writer(self.Model):
__tablename__ = "writer"
__versioned__ = {}

id = sa.Column(sa.Integer, sa.Sequence(f"{__tablename__}_seq"), primary_key=True)
name = sa.Column(sa.String(255))
type = sa.Column(sa.String(255))

__mapper_args__ = {
"polymorphic_on": (
sa.case(
[(type.in_(["poet", "lyricist"]), "bard")],
else_=type,
)
),
"polymorphic_identity": "writer",
}

class Author(self.Model):
__tablename__ = "author"
__versioned__ = {}
id = sa.Column(sa.Integer, sa.Sequence(f"{__tablename__}_seq"), primary_key=True)
name = sa.Column(sa.String(255))

__mapper_args__ = {
"polymorphic_identity": "author",
}

self.Writer = Writer
self.Author = Author

def test_inserting_entries(self):
writer = self.Writer(name="Writer 1")
author = self.Author(name="Author 1")
self.session.add(writer)
self.session.add(author)
self.session.commit()

0 comments on commit 7a2ebf9

Please sign in to comment.