1+ from sqlalchemy .orm .relationships import _RelationshipDeclared
2+
3+
4+ from typing import Any
5+
6+
17import datetime
28import sqlalchemy as sa
9+ from sqlalchemy .orm import relationship
310from sqlalchemy_history .utils import version_class
411
512from tests import TestCase
613
714
815class TestHybridProperty (TestCase ):
916 def create_models (self ):
17+
1018 class Article (self .Model ):
1119 __tablename__ = "article"
1220 __versioned__ = {}
@@ -17,11 +25,35 @@ class Article(self.Model):
1725 description = sa .Column (sa .UnicodeText )
1826 publish = sa .Column (sa .DateTime , default = lambda : datetime .datetime .now (datetime .timezone .utc ))
1927
28+ author_id = sa .Column (sa .Integer , sa .ForeignKey ("article_author.id" ), nullable = False )
29+
30+
2031 @sa .ext .hybrid .hybrid_property
2132 def time_from_publish (self ):
2233 return datetime .datetime .today () - self .publish
2334
35+ @sa .ext .hybrid .hybrid_property
36+ def author_name (self ):
37+ return self .author .name
38+
39+ @author_name .expression
40+ def author_name (cls ):
41+ return sa .select (ArticleAuthor .name ).where (ArticleAuthor .id == cls .author_id ).scalar_subquery ()
42+
43+ class ArticleAuthor (self .Model ):
44+ __tablename__ = "article_author"
45+ __versioned__ = {}
46+
47+ id = sa .Column (sa .Integer , autoincrement = True , primary_key = True )
48+ name = sa .Column (sa .Unicode (255 ), nullable = False )
49+ articles = relationship ("Article" , backref = "author" )
50+
51+
2452 self .Article = Article
2553
2654 def test_hybrid_property_mapping_for_versioned_class (self ):
2755 version_class (self .Article ).time_from_publish
56+
57+
58+ def test_version_class_hybrid_property_in_sql_expression (self ):
59+ sa .select (version_class (self .Article ).author_name )
0 commit comments