Open RobertCraigie opened 2 years ago
We need to take special care that concurrent queries do not create multiple connections.
could you do this with a global
?
@AdeelK93 sorry what do you mean?
something like this - creates a connection if one does not exist, tracking prior connection globally
from prisma import Prisma
_db = None
async def get_db() -> Prisma:
global _db
if not _db:
_db = Prisma(auto_register=True)
await _db.connect()
return _db
yeah that'd work but you'd also want to make sure you don't create multiple clients if a request comes in while you're connecting
e.g. something like this (untested)
import asyncio
from prisma import Prisma
from typing import Optional
_db: Optional[Prisma] = None
_lock = asyncio.Lock()
async def get_db() -> Prisma:
global _db
if _db is None:
async with _lock:
if _db is None:
db = Prisma(auto_register=True)
await db.connect()
_db = db
return _db
Problem
Currently, defining multiple event handlers using a framework that doesn't support a callback like
on_startup()
is annoying as you have to check if the client is connected or not before making a query.Suggested solution
Refactor the internal engine connection to be lazy, i.e. whenever a query is made, connect to the database before running the query.