Coverage for chatgpt_proxy / db / db.py: 92%

25 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-03-12 16:19 +0000

1# MIT License 

2# 

3# Copyright (c) 2025 Tuomo Kriikkula 

4# 

5# Permission is hereby granted, free of charge, to any person obtaining a copy 

6# of this software and associated documentation files (the "Software"), to deal 

7# in the Software without restriction, including without limitation the rights 

8# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 

9# copies of the Software, and to permit persons to whom the Software is 

10# furnished to do so, subject to the following conditions: 

11# 

12# The above copyright notice and this permission notice shall be included in all 

13# copies or substantial portions of the Software. 

14# 

15# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 

16# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 

17# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 

18# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 

19# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 

20# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 

21# SOFTWARE. 

22 

23"""Database connection and caching utilities.""" 

24 

25from contextlib import asynccontextmanager 

26from typing import AsyncGenerator 

27from typing import cast 

28 

29from asyncpg import Connection 

30from asyncpg import Pool 

31 

32from chatgpt_proxy.log import logger 

33 

34_default_acquire_timeout = 5.0 

35 

36 

37@asynccontextmanager 

38async def pool_acquire( 

39 pool: Pool, 

40 timeout: float = _default_acquire_timeout, 

41) -> AsyncGenerator[Connection]: 

42 async with pool.acquire(timeout=timeout) as conn: 

43 # TODO: what is the best way to handle type-juggling here? 

44 # noinspection PyProtectedMember 

45 _conn = conn._con # type: ignore[attr-defined] 

46 yield cast(Connection, _conn) 

47 

48 

49@asynccontextmanager 

50async def pool_acquire_many( 

51 pool: Pool, 

52 count: int, 

53 timeout: float = _default_acquire_timeout, 

54) -> AsyncGenerator[list[Connection]]: 

55 conns: list[Connection] = [] 

56 try: 

57 for _ in range(count): 

58 conn_proxy = await pool.acquire(timeout=timeout) 

59 # TODO: what is the best way to handle type-juggling here? 

60 # noinspection PyProtectedMember 

61 conns.append(conn_proxy._con) # type: ignore[attr-defined] 

62 yield conns 

63 finally: 

64 for conn in conns: 

65 try: 

66 await conn.close(timeout=timeout) 

67 except Exception as e: 

68 logger.debug( 

69 "error closing connection: {}: {}", 

70 type(e).__name__, e)