-
Notifications
You must be signed in to change notification settings - Fork 67
/
inspection.py
57 lines (46 loc) · 1.67 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
from sqlalchemy import inspect
from sqlalchemy.ext.hybrid import hybrid_property, hybrid_method
from sqlalchemy.orm import RelationshipProperty, DeclarativeBase
from .utils import classproperty
class InspectionMixin:
@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__.attrs
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())