9
9
from debug_toolbar .utils import get_stack_trace , get_template_info
10
10
11
11
try :
12
- from psycopg2 ._json import Json as PostgresJson
13
- from psycopg2 .extensions import STATUS_IN_TRANSACTION
12
+ import psycopg
13
+
14
+ PostgresJson = psycopg .types .json .Jsonb
15
+ STATUS_IN_TRANSACTION = psycopg .pq .TransactionStatus .INTRANS
14
16
except ImportError :
15
- PostgresJson = None
16
- STATUS_IN_TRANSACTION = None
17
+ try :
18
+ from psycopg2 ._json import Json as PostgresJson
19
+ from psycopg2 .extensions import STATUS_IN_TRANSACTION
20
+ except ImportError :
21
+ PostgresJson = None
22
+ STATUS_IN_TRANSACTION = None
17
23
18
24
# Prevents SQL queries from being sent to the DB. It's used
19
25
# by the TemplatePanel to prevent the toolbar from issuing
@@ -126,7 +132,13 @@ def _quote_params(self, params):
126
132
127
133
def _decode (self , param ):
128
134
if PostgresJson and isinstance (param , PostgresJson ):
129
- return param .dumps (param .adapted )
135
+ # psycopg3
136
+ if hasattr (param , "obj" ):
137
+ return param .dumps (param .obj )
138
+ # psycopg2
139
+ if hasattr (param , "adapted" ):
140
+ return param .dumps (param .adapted )
141
+
130
142
# If a sequence type, decode each element separately
131
143
if isinstance (param , (tuple , list )):
132
144
return [self ._decode (element ) for element in param ]
@@ -149,7 +161,7 @@ def _record(self, method, sql, params):
149
161
if vendor == "postgresql" :
150
162
# The underlying DB connection (as opposed to Django's wrapper)
151
163
conn = self .db .connection
152
- initial_conn_status = conn .status
164
+ initial_conn_status = conn .info . transaction_status
153
165
154
166
start_time = time ()
155
167
try :
@@ -166,7 +178,10 @@ def _record(self, method, sql, params):
166
178
167
179
# Sql might be an object (such as psycopg Composed).
168
180
# For logging purposes, make sure it's str.
169
- sql = str (sql )
181
+ if vendor == "postgresql" and not isinstance (sql , str ):
182
+ sql = sql .as_string (conn )
183
+ else :
184
+ sql = str (sql )
170
185
171
186
params = {
172
187
"vendor" : vendor ,
@@ -205,7 +220,7 @@ def _record(self, method, sql, params):
205
220
# case where Django can start a transaction before the first query
206
221
# executes, so in that case logger.current_transaction_id() will
207
222
# generate a new transaction ID since one does not already exist.
208
- final_conn_status = conn .status
223
+ final_conn_status = conn .info . transaction_status
209
224
if final_conn_status == STATUS_IN_TRANSACTION :
210
225
if initial_conn_status == STATUS_IN_TRANSACTION :
211
226
trans_id = self .logger .current_transaction_id (alias )
@@ -217,7 +232,7 @@ def _record(self, method, sql, params):
217
232
params .update (
218
233
{
219
234
"trans_id" : trans_id ,
220
- "trans_status" : conn .get_transaction_status () ,
235
+ "trans_status" : conn .info . transaction_status ,
221
236
"iso_level" : iso_level ,
222
237
}
223
238
)
0 commit comments