Update db.py
Browse files
db.py
CHANGED
@@ -1,11 +1,20 @@
|
|
1 |
from tortoise import Tortoise
|
2 |
import os
|
3 |
import ssl
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
4 |
|
5 |
# It's a good practice to create the SSL context outside the dict
|
6 |
-
# This context tells asyncpg to verify the server certificate
|
7 |
ssl_context = ssl.create_default_context()
|
8 |
|
|
|
9 |
TORTOISE_ORM = {
|
10 |
"connections": {
|
11 |
"default": {
|
@@ -17,9 +26,10 @@ TORTOISE_ORM = {
|
|
17 |
"password": os.getenv("DB_PASSWORD"),
|
18 |
"database": "postgres",
|
19 |
},
|
20 |
-
#
|
21 |
"connect_args": {
|
22 |
"statement_cache_size": 0,
|
|
|
23 |
"ssl": ssl_context
|
24 |
}
|
25 |
}
|
@@ -40,7 +50,6 @@ TORTOISE_ORM = {
|
|
40 |
},
|
41 |
}
|
42 |
|
43 |
-
|
44 |
async def init_db():
|
45 |
await Tortoise.init(
|
46 |
TORTOISE_ORM # db_url=DATABASE_URL,
|
|
|
1 |
from tortoise import Tortoise
|
2 |
import os
|
3 |
import ssl
|
4 |
+
import uuid
|
5 |
+
from asyncpg import Connection
|
6 |
+
|
7 |
+
# 1. Create a custom connection class to generate unique IDs for every statement
|
8 |
+
class UniquePreparedStatementConnection(Connection):
|
9 |
+
def _get_unique_id(self, prefix: str) -> str:
|
10 |
+
# This forces every prepared statement to have a new, unique name,
|
11 |
+
# preventing any possible collisions when using a connection pooler.
|
12 |
+
return f"__asyncpg_{prefix}_{uuid.uuid4()}__"
|
13 |
|
14 |
# It's a good practice to create the SSL context outside the dict
|
|
|
15 |
ssl_context = ssl.create_default_context()
|
16 |
|
17 |
+
# 2. Update your TORTOISE_ORM configuration
|
18 |
TORTOISE_ORM = {
|
19 |
"connections": {
|
20 |
"default": {
|
|
|
26 |
"password": os.getenv("DB_PASSWORD"),
|
27 |
"database": "postgres",
|
28 |
},
|
29 |
+
# Pass the custom connection class and disable the cache
|
30 |
"connect_args": {
|
31 |
"statement_cache_size": 0,
|
32 |
+
"connection_class": UniquePreparedStatementConnection,
|
33 |
"ssl": ssl_context
|
34 |
}
|
35 |
}
|
|
|
50 |
},
|
51 |
}
|
52 |
|
|
|
53 |
async def init_db():
|
54 |
await Tortoise.init(
|
55 |
TORTOISE_ORM # db_url=DATABASE_URL,
|