prisma-client-py icon indicating copy to clipboard operation
prisma-client-py copied to clipboard

Add support for lazy connections

Open RobertCraigie opened this issue 4 years ago • 5 comments

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.

RobertCraigie avatar Nov 06 '21 19:11 RobertCraigie

We need to take special care that concurrent queries do not create multiple connections.

RobertCraigie avatar Dec 04 '21 02:12 RobertCraigie

could you do this with a global?

AdeelK93 avatar Aug 07 '24 04:08 AdeelK93

@AdeelK93 sorry what do you mean?

RobertCraigie avatar Aug 07 '24 09:08 RobertCraigie

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

AdeelK93 avatar Aug 07 '24 17:08 AdeelK93

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

RobertCraigie avatar Aug 07 '24 17:08 RobertCraigie