|
1 |
| -from collections.abc import Sequence |
2 |
| -from typing import Union |
| 1 | +from collections.abc import AsyncGenerator, Generator, Sequence |
| 2 | +from contextlib import asynccontextmanager, contextmanager |
| 3 | +from typing import Any, Callable, Optional, Union, cast |
3 | 4 |
|
4 | 5 | from litestar.config.app import AppConfig
|
5 | 6 | from litestar.plugins import InitPluginProtocol
|
| 7 | +from sqlalchemy import Engine |
| 8 | +from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession |
| 9 | +from sqlalchemy.orm import Session |
6 | 10 |
|
7 | 11 | from advanced_alchemy.extensions.litestar.plugins import _slots_base
|
8 | 12 | from advanced_alchemy.extensions.litestar.plugins.init import (
|
@@ -41,10 +45,99 @@ def on_app_init(self, app_config: AppConfig) -> AppConfig:
|
41 | 45 |
|
42 | 46 | Args:
|
43 | 47 | app_config: The :class:`AppConfig <.config.app.AppConfig>` instance.
|
| 48 | +
|
| 49 | + Returns: |
| 50 | + The :class:`AppConfig <.config.app.AppConfig>` instance. |
44 | 51 | """
|
45 | 52 | app_config.plugins.extend([SQLAlchemyInitPlugin(config=self._config), SQLAlchemySerializationPlugin()])
|
46 | 53 | return app_config
|
47 | 54 |
|
| 55 | + def _get_config(self, key: Optional[str] = None) -> Union[SQLAlchemyAsyncConfig, SQLAlchemySyncConfig]: |
| 56 | + """Get a configuration by key. |
| 57 | +
|
| 58 | + Args: |
| 59 | + key: Optional key to identify the configuration. If not provided, uses the first config. |
| 60 | +
|
| 61 | + Raises: |
| 62 | + ValueError: If no configuration is found. |
| 63 | +
|
| 64 | + Returns: |
| 65 | + The SQLAlchemy configuration. |
| 66 | + """ |
| 67 | + if key is None: |
| 68 | + return self._config[0] |
| 69 | + for config in self._config: |
| 70 | + if getattr(config, "key", None) == key: |
| 71 | + return config |
| 72 | + msg = f"No configuration found with key {key}" |
| 73 | + raise ValueError(msg) |
| 74 | + |
| 75 | + def get_session( |
| 76 | + self, |
| 77 | + key: Optional[str] = None, |
| 78 | + ) -> Union[AsyncGenerator[AsyncSession, None], Generator[Session, None, None]]: |
| 79 | + """Get a SQLAlchemy session. |
| 80 | +
|
| 81 | + Args: |
| 82 | + key: Optional key to identify the configuration. If not provided, uses the first config. |
| 83 | +
|
| 84 | + Returns: |
| 85 | + A SQLAlchemy session. |
| 86 | + """ |
| 87 | + config = self._get_config(key) |
| 88 | + |
| 89 | + if isinstance(config, SQLAlchemyAsyncConfig): |
| 90 | + |
| 91 | + @asynccontextmanager |
| 92 | + async def async_gen() -> AsyncGenerator[AsyncSession, None]: |
| 93 | + async with config.get_session() as session: |
| 94 | + yield session |
| 95 | + |
| 96 | + return cast("AsyncGenerator[AsyncSession, None]", async_gen()) |
| 97 | + |
| 98 | + @contextmanager |
| 99 | + def sync_gen() -> Generator[Session, None, None]: |
| 100 | + with config.get_session() as session: |
| 101 | + yield session |
| 102 | + |
| 103 | + return cast("Generator[Session, None, None]", sync_gen()) |
| 104 | + |
| 105 | + def provide_session( |
| 106 | + self, |
| 107 | + key: Optional[str] = None, |
| 108 | + ) -> Callable[..., Union[AsyncGenerator[AsyncSession, None], Generator[Session, None, None]]]: |
| 109 | + """Get a session provider for dependency injection. |
| 110 | +
|
| 111 | + Args: |
| 112 | + key: Optional key to identify the configuration. If not provided, uses the first config. |
| 113 | +
|
| 114 | + Returns: |
| 115 | + A callable that returns a session provider. |
| 116 | + """ |
| 117 | + |
| 118 | + def provider( |
| 119 | + *args: Any, # noqa: ARG001 |
| 120 | + **kwargs: Any, # noqa: ARG001 |
| 121 | + ) -> Union[AsyncGenerator[AsyncSession, None], Generator[Session, None, None]]: |
| 122 | + return self.get_session(key) |
| 123 | + |
| 124 | + return provider |
| 125 | + |
| 126 | + def get_engine( |
| 127 | + self, |
| 128 | + key: Optional[str] = None, |
| 129 | + ) -> Union[AsyncEngine, Engine]: |
| 130 | + """Get the SQLAlchemy engine. |
| 131 | +
|
| 132 | + Args: |
| 133 | + key: Optional key to identify the configuration. If not provided, uses the first config. |
| 134 | +
|
| 135 | + Returns: |
| 136 | + The SQLAlchemy engine. |
| 137 | + """ |
| 138 | + config = self._get_config(key) |
| 139 | + return config.get_engine() |
| 140 | + |
48 | 141 |
|
49 | 142 | __all__ = (
|
50 | 143 | "EngineConfig",
|
|
0 commit comments