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 collections.abc import Iterable
|
||||
from flask import current_app
|
||||
from typing import Any, Callable, Type, TypeVar, Generic, Optional, Protocol, runtime_checkable, cast
|
||||
from sqlalchemy import and_, func, inspect, or_, text
|
||||
from sqlalchemy.engine import Engine, Connection
|
||||
|
|
@ -133,24 +134,25 @@ class CRUDService(Generic[T]):
|
|||
self.polymorphic = polymorphic
|
||||
self.supports_soft_delete = hasattr(model, 'is_deleted')
|
||||
|
||||
# Derive engine WITHOUT leaking a session/connection
|
||||
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)
|
||||
self._backend: Optional[BackendInfo] = backend
|
||||
|
||||
@property
|
||||
def session(self) -> Session:
|
||||
return self._session_factory()
|
||||
"""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()
|
||||
|
||||
@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):
|
||||
if self.polymorphic:
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue