Skip to content

fixed deprecated reference due to ellar 0.8.1 #43

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions docs/migrations/env.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ but it also introduces a certain level of complexity.
from logging.config import fileConfig

from alembic import context
from ellar.app import current_injector
from ellar.threading import run_as_async
from ellar.core import current_injector
from ellar.threading import run_as_sync

from ellar_sql.migrations import SingleDatabaseAlembicEnvMigration
from ellar_sql.services import EllarSQLService
Expand All @@ -28,7 +28,7 @@ fileConfig(config.config_file_name) # type:ignore[arg-type]
# my_important_option = config.get_main_option("my_important_option")
# ... etc.

@run_as_async
@run_as_sync
async def main() -> None:
db_service: EllarSQLService = current_injector.get(EllarSQLService)

Expand Down Expand Up @@ -91,8 +91,8 @@ from logging.config import fileConfig
from alembic import context
from ellar_sql.migrations import AlembicEnvMigrationBase
from ellar_sql.model.database_binds import get_metadata
from ellar.app import current_injector
from ellar.threading import run_as_async
from ellar.core import current_injector
from ellar.threading import run_as_sync
from ellar_sql.services import EllarSQLService

# This is the Alembic Config object, which provides
Expand Down Expand Up @@ -156,7 +156,7 @@ class MyCustomMigrationEnv(AlembicEnvMigrationBase):
context.run_migrations()


@run_as_async
@run_as_sync
async def main() -> None:
db_service: EllarSQLService = current_injector.get(EllarSQLService)

Expand Down
8 changes: 4 additions & 4 deletions docs/models/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ class User(model.Model):
We have created a `User` model but the data does not exist. Let's fix that

```python
from ellar.app import current_injector
from ellar.core import current_injector
from ellar_sql import EllarSQLService

db_service = current_injector.get(EllarSQLService)
Expand Down Expand Up @@ -285,7 +285,7 @@ Although with `EllarSQLService` you can get the `engine` and `session`. It's the
```python
import sqlalchemy as sa
import sqlalchemy.orm as sa_orm
from ellar.app import current_injector
from ellar.core import current_injector
from ellar_sql import EllarSQLService

db_service = current_injector.get(EllarSQLService)
Expand All @@ -303,7 +303,7 @@ assert isinstance(db_service.session_factory(), sa_orm.Session)
```python
import sqlalchemy as sa
import sqlalchemy.orm as sa_orm
from ellar.app import current_injector
from ellar.core import current_injector

# get engine from DI
default_engine = current_injector.get(sa.Engine)
Expand All @@ -317,7 +317,7 @@ assert isinstance(session, sa_orm.Session)
For Async Database options
```python
from sqlalchemy.ext.asyncio import AsyncSession, AsyncEngine
from ellar.app import current_injector
from ellar.core import current_injector

# get engine from DI
default_engine = current_injector.get(AsyncEngine)
Expand Down
2 changes: 1 addition & 1 deletion docs/multiple/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ It also requires the `database` argument to target a specific database.

```python
# Create tables for all binds
from ellar.app import current_injector
from ellar.core import current_injector
from ellar_sql import EllarSQLService

db_service = current_injector.get(EllarSQLService)
Expand Down
2 changes: 1 addition & 1 deletion ellar_sql/cli/commands.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import ellar_cli.click as click
from ellar.app import current_injector
from ellar.core import current_injector

from ellar_sql.services import EllarSQLService

Expand Down
4 changes: 2 additions & 2 deletions ellar_sql/factory/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import sqlalchemy as sa
import sqlalchemy.orm as sa_orm
from ellar.threading import run_as_async
from ellar.threading import run_as_sync
from factory.alchemy import (
SESSION_PERSISTENCE_COMMIT,
SESSION_PERSISTENCE_FLUSH,
Expand Down Expand Up @@ -36,7 +36,7 @@ class Meta:
abstract = True

@classmethod
@run_as_async
@run_as_sync
async def _session_execute(
cls, session_func: t.Callable, *args: t.Any, **kwargs: t.Any
) -> t.Union[sa.Result, sa.CursorResult, t.Any]:
Expand Down
2 changes: 1 addition & 1 deletion ellar_sql/model/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

import sqlalchemy as sa
import sqlalchemy.orm as sa_orm
from ellar.app import current_injector
from ellar.core import current_injector
from sqlalchemy.ext.asyncio import AsyncSession

from ellar_sql.constant import DATABASE_BIND_KEY, DATABASE_KEY, DEFAULT_KEY
Expand Down
13 changes: 4 additions & 9 deletions ellar_sql/model/typeDecorator/file/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,14 @@
from sqlalchemy_file.exceptions import ValidationError

from ellar.common import IExecutionContext
from ellar.common.exceptions import CallableExceptionHandler
from ellar.core.exceptions import as_exception_handler


def _exception_handlers(ctx: IExecutionContext, exc: ValidationError):
# Register to application config.EXCEPTION_HANDLERS to add exception handler for sqlalchemy-file
@as_exception_handler(ValidationError)
async def FileExceptionHandler(ctx: IExecutionContext, exc: ValidationError):
app_config = ctx.get_app().config
return app_config.DEFAULT_JSON_CLASS(
{"message": exc.msg, "key": exc.key},
status_code=400,
)


# Register to application config.EXCEPTION_HANDLERS to add exception handler for sqlalchemy-file
FileExceptionHandler = CallableExceptionHandler(
exc_class_or_status_code=ValidationError,
callable_exception_handler=_exception_handlers,
)
2 changes: 1 addition & 1 deletion ellar_sql/model/typeDecorator/file/file.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
import warnings
from datetime import datetime

from ellar.app import current_injector
from ellar.common.compatible import AttributeDictAccessMixin
from ellar.core import current_injector
from ellar_storage import StorageService, StoredFile
from sqlalchemy_file.file import File as BaseFile
from starlette.datastructures import UploadFile
Expand Down
2 changes: 1 addition & 1 deletion ellar_sql/model/typeDecorator/file/file_tracker.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import typing as t

from ellar.app import current_injector
from ellar.core import current_injector
from ellar_storage import StorageService
from sqlalchemy import event, orm
from sqlalchemy_file.types import FileFieldSessionTracker
Expand Down
73 changes: 47 additions & 26 deletions ellar_sql/module.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@
import typing as t

import sqlalchemy as sa
from ellar.common import IExecutionContext, IModuleSetup, Module, middleware
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.events import app_context_teardown
from ellar.utils.importer import get_main_directory_by_stack
from sqlalchemy.ext.asyncio import (
AsyncEngine,
Expand All @@ -26,32 +27,49 @@ def _raise_exception():
return _raise_exception


@Module(commands=[DBCommands])
class EllarSQLModule(ModuleBase, IModuleSetup):
@middleware()
async def session_middleware(
cls, context: IExecutionContext, call_next: t.Callable[..., t.Coroutine]
):
connection = context.switch_to_http_connection().get_client()

db_session = connection.service_provider.get(EllarSQLService)
session = db_session.session_factory()
@as_middleware
async def session_middleware(
context: IHostContext, call_next: t.Callable[..., t.Coroutine]
):
connection = context.switch_to_http_connection().get_client()

connection.state.session = session
db_service = context.get_service_provider().get(EllarSQLService)
session = db_service.session_factory()

try:
await call_next()
except Exception as ex:
res = session.rollback()
if isinstance(res, t.Coroutine):
await res
raise ex
connection.state.session = session

@classmethod
async def _on_application_tear_down(cls, db_service: EllarSQLService) -> None:
res = db_service.session_factory.remove()
try:
await call_next()
except Exception as ex:
res = session.rollback()
if isinstance(res, t.Coroutine):
await res
raise ex

res = db_service.session_factory.remove()
if isinstance(res, t.Coroutine):
await res


@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(
Expand Down Expand Up @@ -155,8 +173,10 @@ def __setup_module(cls, sql_alchemy_config: SQLAlchemyConfig) -> DynamicModule:
)

providers.append(ProviderConfig(EllarSQLService, use_value=db_service))
app_context_teardown.connect(
functools.partial(cls._on_application_tear_down, db_service=db_service)
providers.append(
ProviderConfig(
MigrationOption, use_value=lambda: db_service.migration_options
)
)

return DynamicModule(
Expand All @@ -182,7 +202,7 @@ def register_setup(cls, **override_config: t.Any) -> ModuleSetup:

@staticmethod
def __register_setup_factory(
module: t.Type["EllarSQLModule"],
module_ref: ModuleRefBase,
config: Config,
root_path: str,
override_config: t.Dict[str, t.Any],
Expand All @@ -201,6 +221,7 @@ def __register_setup_factory(
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.")
10 changes: 5 additions & 5 deletions ellar_sql/pagination/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
import ellar.common as ecm
import sqlalchemy as sa
import sqlalchemy.orm as sa_orm
from ellar.app import current_injector
from ellar.threading import run_as_async
from ellar.core import current_injector
from ellar.threading import run_as_sync
from sqlalchemy.ext.asyncio import AsyncSession

from ellar_sql.model.base import ModelBase
Expand Down Expand Up @@ -277,7 +277,7 @@ def __init__(
if self._created_session:
self._close_session() # session usage is done but only if Paginator created the session

@run_as_async
@run_as_sync
async def _close_session(self) -> None:
res = self._session.close()
if isinstance(res, t.Coroutine):
Expand All @@ -298,7 +298,7 @@ def _query_items_sync(self) -> t.List[t.Any]:
select = self._select.limit(self.per_page).offset(self._query_offset)
return list(self._session.execute(select).unique().scalars())

@run_as_async
@run_as_sync
async def _query_items_async(self) -> t.List[t.Any]:
session = t.cast(AsyncSession, self._session)

Expand All @@ -320,7 +320,7 @@ def _query_count_sync(self) -> int:
).scalar()
return out # type:ignore[return-value]

@run_as_async
@run_as_sync
async def _query_count_async(self) -> int:
session = t.cast(AsyncSession, self._session)

Expand Down
2 changes: 1 addition & 1 deletion ellar_sql/query/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import ellar.common as ecm
import sqlalchemy as sa
import sqlalchemy.exc as sa_exc
from ellar.app import current_injector
from ellar.core import current_injector

from ellar_sql.services import EllarSQLService

Expand Down
6 changes: 3 additions & 3 deletions ellar_sql/templates/multiple/env.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
from logging.config import fileConfig

from alembic import context
from ellar.app import current_injector
from ellar.threading import run_as_async
from ellar.core import current_injector
from ellar.threading import run_as_sync

from ellar_sql.migrations import MultipleDatabaseAlembicEnvMigration
from ellar_sql.services import EllarSQLService
Expand All @@ -22,7 +22,7 @@
# ... etc.


@run_as_async
@run_as_sync
async def main() -> None:
db_service: EllarSQLService = current_injector.get(EllarSQLService)

Expand Down
2 changes: 1 addition & 1 deletion ellar_sql/templates/multiple/script.py.mako
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}

<%!
from ellar.app import current_injector
from ellar.core import current_injector
from ellar_sql.services import EllarSQLService

db_service = current_injector.get(EllarSQLService)
Expand Down
6 changes: 3 additions & 3 deletions ellar_sql/templates/single/env.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
from logging.config import fileConfig

from alembic import context
from ellar.app import current_injector
from ellar.threading import run_as_async
from ellar.core import current_injector
from ellar.threading import run_as_sync

from ellar_sql.migrations import SingleDatabaseAlembicEnvMigration
from ellar_sql.services import EllarSQLService
Expand All @@ -22,7 +22,7 @@
# ... etc.


@run_as_async
@run_as_sync
async def main() -> None:
db_service: EllarSQLService = current_injector.get(EllarSQLService)

Expand Down
4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,10 @@ classifiers = [
]

dependencies = [
"ellar-cli >= 0.3.7",
"ellar-cli >= 0.4.3",
"sqlalchemy >= 2.0.23",
"alembic >= 1.10.0",
"ellar-storage >= 0.1.4",
"ellar-storage >= 0.1.7",
"sqlalchemy-file >= 0.6.0",
]

Expand Down
2 changes: 1 addition & 1 deletion samples/db-learning/db_learning/command.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@


@click.command("seed")
@click.with_app_context
@click.with_injector_context
def seed_user():
db_service = current_injector.get(EllarSQLService)
session = db_service.session_factory()
Expand Down
Loading
Loading
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy