|
1
|
|
|
from sqlalchemy import Table, MetaData |
|
|
|
|
|
|
2
|
|
|
from sqlalchemy.engine import Engine |
|
3
|
|
|
|
|
4
|
|
|
|
|
5
|
|
|
class CustomTable(Table): |
|
|
|
|
|
|
6
|
|
|
def __getattr__(self, attr): |
|
7
|
|
|
return getattr(self.c, attr) |
|
8
|
|
|
|
|
9
|
|
|
def __bool__(self) -> None: |
|
10
|
|
|
return self is not None |
|
11
|
|
|
|
|
12
|
|
|
|
|
13
|
|
|
class LazyDBProp(object): |
|
|
|
|
|
|
14
|
|
|
"""This descriptor returns sqlalchemy |
|
15
|
|
|
Table class which can be used to query |
|
16
|
|
|
table from the schema |
|
17
|
|
|
""" |
|
18
|
|
|
|
|
19
|
|
|
def __init__(self) -> None: |
|
20
|
|
|
self._table = None |
|
21
|
|
|
self._name = None |
|
22
|
|
|
|
|
23
|
|
|
def __set_name__(self, _, name): |
|
24
|
|
|
self._name = name |
|
25
|
|
|
|
|
26
|
|
|
def __set__(self, instance, value): |
|
27
|
|
|
if isinstance(value, (CustomTable, Table)): |
|
28
|
|
|
self._table = value |
|
29
|
|
|
|
|
30
|
|
|
def __get__(self, instance, _): |
|
31
|
|
|
if self._table is None: |
|
32
|
|
|
self._table = CustomTable( |
|
33
|
|
|
self._name, instance.metadata, autoload=True) |
|
34
|
|
|
return self._table |
|
35
|
|
|
|
|
36
|
|
|
|
|
37
|
|
|
def get_lazy_class(engine: Engine) -> object: |
|
38
|
|
|
""" |
|
39
|
|
|
Function to create Lazy class for pulling table object |
|
40
|
|
|
using SQLalchemy metadata |
|
41
|
|
|
""" |
|
42
|
|
|
|
|
43
|
|
|
def __init__(self, engine: Engine): |
|
44
|
|
|
self.metadata = MetaData(engine) |
|
45
|
|
|
self.engine = engine |
|
46
|
|
|
|
|
47
|
|
|
def __getattr__(self, attr): |
|
48
|
|
|
if attr not in self.__dict__: |
|
49
|
|
|
obj = self.__patch(attr) |
|
|
|
|
|
|
50
|
|
|
return obj.__get__(self, type(self)) |
|
|
|
|
|
|
51
|
|
|
|
|
52
|
|
|
def __patch(self, attribute): |
|
53
|
|
|
obj = LazyDBProp() |
|
54
|
|
|
obj.__set_name__(self, attribute) |
|
55
|
|
|
setattr(type(self), attribute, obj) |
|
56
|
|
|
return obj |
|
57
|
|
|
|
|
58
|
|
|
# naming classes uniquely for different schema's |
|
59
|
|
|
# to avoid cross referencing |
|
60
|
|
|
LazyClass = type(f"LazyClass_{engine.url.database}", (), {}) |
|
|
|
|
|
|
61
|
|
|
LazyClass.__init__ = __init__ |
|
62
|
|
|
LazyClass.__getattr__ = __getattr__ |
|
63
|
|
|
LazyClass.__patch = __patch |
|
|
|
|
|
|
64
|
|
|
return LazyClass(engine) |
|
65
|
|
|
|