-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodule.py
More file actions
232 lines (206 loc) · 7.8 KB
/
module.py
File metadata and controls
232 lines (206 loc) · 7.8 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
import functools
import typing as t
import sqlalchemy as sa
from ellar.common import IHostContext, IModuleSetup, Module
from ellar.core import Config, DynamicModule, ModuleBase, ModuleSetup
from ellar.core.middleware import as_middleware
from ellar.core.modules import ModuleRefBase
from ellar.di import ProviderConfig, request_or_transient_scope
from ellar.utils.importer import get_main_directory_by_stack
from sqlalchemy.ext.asyncio import (
AsyncEngine,
AsyncSession,
)
from sqlalchemy.orm import Session
from ellar_sql.services import EllarSQLService
from .cli import DBCommands
from .schemas import MigrationOption, SQLAlchemyConfig
def _invalid_configuration(message: str) -> t.Callable:
def _raise_exception():
raise RuntimeError(message)
return _raise_exception
async def _session_cleanup(
db_service: EllarSQLService, session: t.Union[Session, AsyncSession]
) -> None:
res = db_service.session_factory.remove()
if isinstance(res, t.Coroutine):
await res
res = session.close()
if isinstance(res, t.Coroutine):
await res
@as_middleware
async def session_middleware(
context: IHostContext, call_next: t.Callable[..., t.Coroutine]
):
connection = context.switch_to_http_connection().get_client()
db_service = context.get_service_provider().get(EllarSQLService)
session = db_service.session_factory()
connection.state.session = session
try:
await call_next()
finally:
await _session_cleanup(db_service, session)
@Module(
commands=[DBCommands],
exports=[
EllarSQLService,
Session,
AsyncSession,
AsyncEngine,
sa.Engine,
MigrationOption,
],
providers=[EllarSQLService],
name="EllarSQL",
)
class EllarSQLModule(ModuleBase, IModuleSetup):
@classmethod
def post_build(cls, module_ref: "ModuleRefBase") -> None:
module_ref.config.MIDDLEWARE = list(module_ref.config.MIDDLEWARE) + [
session_middleware
]
@classmethod
def setup(
cls,
*,
databases: t.Union[str, t.Dict[str, t.Any]],
migration_options: t.Union[t.Dict[str, t.Any], MigrationOption],
session_options: t.Optional[t.Dict[str, t.Any]] = None,
engine_options: t.Optional[t.Dict[str, t.Any]] = None,
models: t.Optional[t.List[str]] = None,
echo: bool = False,
root_path: t.Optional[str] = None,
) -> "DynamicModule":
"""
Configures EllarSQLModule and setup required providers.
"""
root_path = root_path or get_main_directory_by_stack("__main__", stack_level=2)
if isinstance(migration_options, MigrationOption):
migration_options = migration_options.dict()
migration_options.setdefault("directory", "migrations")
schema = SQLAlchemyConfig.model_validate(
{
"databases": databases,
"engine_options": engine_options,
"echo": echo,
"models": models,
"session_options": session_options,
"migration_options": migration_options,
"root_path": root_path,
},
from_attributes=True,
)
return cls.__setup_module(schema)
@classmethod
def __setup_module(cls, sql_alchemy_config: SQLAlchemyConfig) -> DynamicModule:
db_service = EllarSQLService(
databases=sql_alchemy_config.databases,
common_engine_options=sql_alchemy_config.engine_options,
common_session_options=sql_alchemy_config.session_options,
echo=sql_alchemy_config.echo,
models=sql_alchemy_config.models,
root_path=sql_alchemy_config.root_path,
migration_options=sql_alchemy_config.migration_options,
)
providers: t.List[t.Any] = []
if db_service.has_async_engine_driver:
providers.append(ProviderConfig(AsyncEngine, use_value=db_service.engine))
providers.append(
ProviderConfig(
AsyncSession,
use_value=lambda: db_service.session_factory(),
scope=request_or_transient_scope,
)
)
providers.append(
ProviderConfig(
Session,
use_value=_invalid_configuration(
f"{Session} is not configured based on your database options. Please use {AsyncSession}"
),
scope=request_or_transient_scope,
)
)
providers.append(
ProviderConfig(
sa.Engine,
use_value=_invalid_configuration(
f"{sa.Engine} is not configured based on your database options. Please use {AsyncEngine}"
),
scope=request_or_transient_scope,
)
)
else:
providers.append(ProviderConfig(sa.Engine, use_value=db_service.engine))
providers.append(
ProviderConfig(
Session,
use_value=lambda: db_service.session_factory(),
scope=request_or_transient_scope,
)
)
providers.append(
ProviderConfig(
AsyncSession,
use_value=_invalid_configuration(
f"{AsyncSession} is not configured based on your database options. Please use {Session}"
),
scope=request_or_transient_scope,
)
)
providers.append(
ProviderConfig(
AsyncEngine,
use_value=_invalid_configuration(
f"{AsyncEngine} is not configured based on your database options. Please use {sa.Engine}"
),
scope=request_or_transient_scope,
)
)
providers.append(ProviderConfig(EllarSQLService, use_value=db_service))
providers.append(
ProviderConfig(
MigrationOption, use_value=lambda: db_service.migration_options
)
)
return DynamicModule(
cls,
providers=providers,
)
@classmethod
def register_setup(cls, **override_config: t.Any) -> ModuleSetup:
"""
Register Module to be configured through `SQLALCHEMY_CONFIG` variable in Application Config
"""
root_path = get_main_directory_by_stack("__main__", stack_level=2)
return ModuleSetup(
cls,
inject=[Config],
factory=functools.partial(
cls.__register_setup_factory,
root_path=root_path,
override_config=override_config,
),
)
@staticmethod
def __register_setup_factory(
module_ref: ModuleRefBase,
config: Config,
root_path: str,
override_config: t.Dict[str, t.Any],
) -> DynamicModule:
if config.get("ELLAR_SQL") and isinstance(config.ELLAR_SQL, dict):
defined_config = dict(config.ELLAR_SQL)
defined_config.update(override_config)
defined_config.setdefault("root_path", root_path)
schema = SQLAlchemyConfig.model_validate(
defined_config, from_attributes=True
)
schema.migration_options.directory = get_main_directory_by_stack(
schema.migration_options.directory,
stack_level=0,
from_dir=defined_config["root_path"],
)
module = t.cast(t.Type["EllarSQLModule"], module_ref.module)
return module.__setup_module(schema)
raise RuntimeError("Could not find `ELLAR_SQL` in application config.")