Coverage for src/prisma/_registry.py: 79%
23 statements
« prev ^ index » next coverage.py v7.2.7, created at 2024-08-27 18:25 +0000
« prev ^ index » next coverage.py v7.2.7, created at 2024-08-27 18:25 +0000
1from __future__ import annotations
3from typing import TYPE_CHECKING, Union, Callable
5from .errors import ClientNotRegisteredError, ClientAlreadyRegisteredError
7if TYPE_CHECKING:
8 from .client import Prisma # noqa: TID251
11RegisteredClient = Union['Prisma', Callable[[], 'Prisma']]
12_registered_client: RegisteredClient | None = None
15def register(client: RegisteredClient) -> None:
16 """Register a client instance to be retrieved by `get_client()`
18 This function _must_ only be called once, preferrably as soon as possible
19 to avoid any potentially confusing errors with threads or processes.
20 """
21 from .client import Prisma # noqa: TID251
23 global _registered_client
25 if _registered_client is not None:
26 raise ClientAlreadyRegisteredError()
28 if not isinstance(client, Prisma) and not callable(client): 28 ↛ 29line 28 didn't jump to line 29, because the condition on line 28 was never true
29 raise TypeError(
30 f'Expected either a {Prisma} instance or a function that returns a {Prisma} but got {client} instead.'
31 )
33 _registered_client = client
36def get_client() -> Prisma:
37 """Get the registered client instance
39 Raises errors.ClientNotRegisteredError() if no client instance has been registered.
40 """
41 from .client import Prisma # noqa: TID251
43 registered = _registered_client
44 if registered is None:
45 raise ClientNotRegisteredError() from None
47 if isinstance(registered, Prisma):
48 return registered
50 client = registered()
51 if not isinstance(client, Prisma): # pyright: ignore[reportUnnecessaryIsInstance]
52 raise TypeError(f'Registered function returned {client} instead of a {Prisma} instance.')
54 return client