RobertCraigie / prisma-client-py

Prisma Client Python is an auto-generated and fully type-safe database client designed for ease of use
https://prisma-client-py.readthedocs.io
Apache License 2.0
1.82k stars 77 forks source link

Add support for lazy connections #103

Open RobertCraigie opened 2 years ago

RobertCraigie commented 2 years ago

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 commented 2 years ago

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

AdeelK93 commented 1 month ago

could you do this with a global?

RobertCraigie commented 1 month ago

@AdeelK93 sorry what do you mean?

AdeelK93 commented 1 month ago

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
RobertCraigie commented 1 month ago

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