Skip to content

Commit ae751bd

Browse files
committed
perf: Ensure that the engine url corresponds to a database instance.
1 parent cff3f46 commit ae751bd

1 file changed

Lines changed: 10 additions & 1 deletion

File tree

sqlalchemy_database/_abc_async_database.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,16 @@ async def to_thread(func: Callable[_P, _R], *args: _P.args, **kwargs: _P.kwargs)
2323

2424

2525
class AbcAsyncDatabase(metaclass=abc.ABCMeta): # noqa: B024
26+
def __new__(cls, engine, *args, **kwargs):
27+
"""Create a new instance of the database class.Each engine url corresponds to a database instance,
28+
and if it already exists, it is directly returned, otherwise a new instance is created.
29+
"""
30+
if not hasattr(cls, "_instances"):
31+
cls._instances = {}
32+
if engine.url not in cls._instances:
33+
cls._instances[engine.url] = super().__new__(cls)
34+
return cls._instances[engine.url]
35+
2636
def __init__(self) -> None:
2737
for func_name in {
2838
"run_sync",
@@ -82,7 +92,6 @@ async def asgi_dispatch(self, request, call_next):
8292
app.add_middleware(BaseHTTPMiddleware, dispatch=db.asgi_dispatch)
8393
```
8494
"""
85-
print("asgi_dispatch", id(request.scope))
8695
# bind session to request
8796
async with self.__call__(scope=id(request.scope)):
8897
return await call_next(request)

0 commit comments

Comments
 (0)