forked from absent1706/sqlalchemy-mixins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
inspection.py
62 lines (49 loc) · 1.78 KB
/
inspection.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
from sqlalchemy import inspect
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.hybrid import hybrid_property, hybrid_method
from sqlalchemy.orm import RelationshipProperty
from .utils import classproperty
Base = declarative_base()
class InspectionMixin(Base):
__abstract__ = True
@classproperty
def columns(cls):
return inspect(cls).columns.keys()
@classproperty
def primary_keys_full(cls):
"""Get primary key properties for a SQLAlchemy cls.
Taken from marshmallow_sqlalchemy
"""
mapper = cls.__mapper__
return [
mapper.get_property_by_column(column)
for column in mapper.primary_key
]
@classproperty
def primary_keys(cls):
return [pk.key for pk in cls.primary_keys_full]
@classproperty
def relations(cls):
"""Return a `list` of relationship names or the given model
"""
return [c.key for c in cls.__mapper__.iterate_properties
if isinstance(c, RelationshipProperty)]
@classproperty
def settable_relations(cls):
"""Return a `list` of relationship names or the given model
"""
return [r for r in cls.relations
if getattr(cls, r).property.viewonly is False]
@classproperty
def hybrid_properties(cls):
items = inspect(cls).all_orm_descriptors
return [item.__name__ for item in items
if isinstance(item, hybrid_property)]
@classproperty
def hybrid_methods_full(cls):
items = inspect(cls).all_orm_descriptors
return {item.func.__name__: item
for item in items if type(item) == hybrid_method}
@classproperty
def hybrid_methods(cls):
return list(cls.hybrid_methods_full.keys())