Minor change to service.
This commit is contained in:
parent
085905557d
commit
7a3b11dc32
1 changed files with 17 additions and 15 deletions
|
|
@ -1,6 +1,7 @@
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from collections.abc import Iterable
|
from collections.abc import Iterable
|
||||||
|
from flask import current_app
|
||||||
from typing import Any, Callable, Type, TypeVar, Generic, Optional, Protocol, runtime_checkable, cast
|
from typing import Any, Callable, Type, TypeVar, Generic, Optional, Protocol, runtime_checkable, cast
|
||||||
from sqlalchemy import and_, func, inspect, or_, text
|
from sqlalchemy import and_, func, inspect, or_, text
|
||||||
from sqlalchemy.engine import Engine, Connection
|
from sqlalchemy.engine import Engine, Connection
|
||||||
|
|
@ -133,25 +134,26 @@ class CRUDService(Generic[T]):
|
||||||
self.polymorphic = polymorphic
|
self.polymorphic = polymorphic
|
||||||
self.supports_soft_delete = hasattr(model, 'is_deleted')
|
self.supports_soft_delete = hasattr(model, 'is_deleted')
|
||||||
|
|
||||||
# Derive engine WITHOUT leaking a session/connection
|
self._backend: Optional[BackendInfo] = backend
|
||||||
bind = getattr(session_factory, "bind", None)
|
|
||||||
if bind is None:
|
|
||||||
tmp_sess = session_factory()
|
|
||||||
try:
|
|
||||||
bind = tmp_sess.get_bind()
|
|
||||||
finally:
|
|
||||||
try:
|
|
||||||
tmp_sess.close()
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
eng: Engine = bind.engine if isinstance(bind, Connection) else cast(Engine, bind)
|
|
||||||
self.backend = backend or make_backend_info(eng)
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def session(self) -> Session:
|
def session(self) -> Session:
|
||||||
|
"""Always return the Flask-scoped Session if available; otherwise the provided factory."""
|
||||||
|
try:
|
||||||
|
sess = current_app.extensions["crudkit"]["Session"]
|
||||||
|
return sess
|
||||||
|
except Exception:
|
||||||
return self._session_factory()
|
return self._session_factory()
|
||||||
|
|
||||||
|
@property
|
||||||
|
def backend(self) -> BackendInfo:
|
||||||
|
"""Resolve backend info lazily against the active session's engine."""
|
||||||
|
if self._backend is None:
|
||||||
|
bind = self.session.get_bind()
|
||||||
|
eng: Engine = bind.engine if isinstance(bind, Connection) else cast(Engine, bind)
|
||||||
|
self._backend = make_backend_info(eng)
|
||||||
|
return self._backend
|
||||||
|
|
||||||
def get_query(self):
|
def get_query(self):
|
||||||
if self.polymorphic:
|
if self.polymorphic:
|
||||||
poly = with_polymorphic(self.model, "*")
|
poly = with_polymorphic(self.model, "*")
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue