-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdb.py
More file actions
75 lines (60 loc) · 2.3 KB
/
db.py
File metadata and controls
75 lines (60 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
from asyncpg import create_pool, Pool, Connection
from contextlib import asynccontextmanager
from os import getenv
from typing import AsyncGenerator, Optional
_pool: Optional[Pool] = None # pylint: disable=invalid-name
async def create_tables(conn: Connection) -> None:
# Create tables if they do not exist
with open("sql/create_tables.sql", "r", encoding="utf-8") as f:
sql_commands = f.read()
await conn.execute(sql_commands)
# Create indexes if they do not exist
with open("sql/create_indexes.sql", "r", encoding="utf-8") as f:
sql_commands = f.read()
await conn.execute(sql_commands)
# Create triggers to ensure users exist
with open("sql/trigger_check_user_exists.sql", "r", encoding="utf-8") as f:
sql_commands = f.read()
await conn.execute(sql_commands)
# Create triggers to update summary table
with open("sql/trigger_update_summary.sql", "r", encoding="utf-8") as f:
sql_commands = f.read()
await conn.execute(sql_commands)
# Create chat tables
with open("sql/create_llm_tables.sql", "r", encoding="utf-8") as f:
sql_commands = f.read()
await conn.execute(sql_commands)
@asynccontextmanager
async def init_db() -> AsyncGenerator[Pool, None]:
global _pool # pylint: disable=global-statement
if _pool:
raise RuntimeError("Database pool is already initialized.")
dsn = getenv(
"POSTGRES_DB_URL",
"postgresql://billing:billing@localhost:5432/billing"
)
min_size = int(getenv("POSTGRES_POOL_MIN_SIZE", "5"))
max_size = int(getenv("POSTGRES_POOL_MAX_SIZE", "10"))
pool = await create_pool(
dsn=dsn,
min_size=min_size,
max_size=max_size,
)
try:
_pool = pool
async with pool.acquire() as conn:
await create_tables(conn) # type: ignore
yield pool
finally:
await pool.close()
_pool = None
@asynccontextmanager
async def get_db(transaction: bool = False) -> AsyncGenerator[Connection, None]:
if _pool is None:
raise RuntimeError("Database pool is not initialized.")
async with _pool.acquire() as conn:
if transaction:
async with conn.transaction():
yield conn # type: ignore
else:
yield conn # type: ignore