0
# Exception Handling
1
2
Complete exception hierarchy for proper error handling following DB-API 2.0 standards with PostgreSQL-specific error categories and detailed error information.
3
4
## Capabilities
5
6
### Base Exception Classes
7
8
Foundation exception classes providing the base for all pg8000 error conditions.
9
10
```python { .api }
11
class Error(Exception):
12
"""
13
Base exception class for all pg8000 errors.
14
15
This is the root of the pg8000 exception hierarchy and catches
16
all database-related errors from pg8000.
17
"""
18
19
class InterfaceError(Error):
20
"""
21
Exception for database interface related errors.
22
23
Raised for errors related to the database interface rather than
24
the database itself. Includes connection parameter errors,
25
invalid API usage, and interface-level problems.
26
"""
27
28
class DatabaseError(Error):
29
"""
30
Exception for database related errors.
31
32
Base class for errors that occur during database operations.
33
This includes all errors that originate from PostgreSQL server
34
responses or database communication issues.
35
"""
36
```
37
38
### Operational Exception Classes
39
40
Exceptions for database operation and runtime errors.
41
42
```python { .api }
43
class OperationalError(DatabaseError):
44
"""
45
Exception for database operational errors.
46
47
Raised for errors related to database operations that are not
48
under the control of the programmer. Includes connection failures,
49
server shutdowns, network errors, and similar operational issues.
50
51
Common causes:
52
- Connection timeout or loss
53
- Server unavailable or shutdown
54
- Network connectivity issues
55
- Authentication failures
56
- Permission denied errors
57
"""
58
59
class InternalError(DatabaseError):
60
"""
61
Exception for internal database errors.
62
63
Raised when PostgreSQL encounters an internal error condition.
64
These errors indicate problems within the database system itself
65
rather than with the application code or data.
66
67
Common causes:
68
- PostgreSQL internal errors
69
- System resource exhaustion
70
- Corrupted database structures
71
- PostgreSQL bugs or crashes
72
"""
73
```
74
75
### Data and Programming Exception Classes
76
77
Exceptions for data validation and programming errors.
78
79
```python { .api }
80
class DataError(DatabaseError):
81
"""
82
Exception for data processing errors.
83
84
Raised for errors due to problems with the processed data.
85
This includes data type mismatches, constraint violations,
86
and data format errors.
87
88
Common causes:
89
- Invalid data type conversion
90
- Data value out of range
91
- Invalid data format
92
- Constraint check violations
93
"""
94
95
class ProgrammingError(DatabaseError):
96
"""
97
Exception for programming errors.
98
99
Raised for errors in SQL syntax, invalid object names,
100
and other programming mistakes. These errors indicate
101
problems with the application code rather than runtime conditions.
102
103
Common causes:
104
- SQL syntax errors
105
- Invalid table or column names
106
- Missing required parameters
107
- Invalid SQL operations
108
- Prepared statement errors
109
"""
110
```
111
112
### Integrity and Support Exception Classes
113
114
Exceptions for data integrity and feature support issues.
115
116
```python { .api }
117
class IntegrityError(DatabaseError):
118
"""
119
Exception for relational integrity errors.
120
121
Raised when database relational integrity is affected.
122
This includes foreign key constraint violations, unique
123
constraint violations, and other referential integrity issues.
124
125
Common causes:
126
- Foreign key constraint violations
127
- Unique constraint violations
128
- Primary key violations
129
- Check constraint failures
130
- NOT NULL violations
131
"""
132
133
class NotSupportedError(DatabaseError):
134
"""
135
Exception for unsupported operation errors.
136
137
Raised when an unsupported database operation is attempted.
138
This includes operations not supported by PostgreSQL or
139
by the pg8000 driver itself.
140
141
Common causes:
142
- Unsupported SQL features
143
- Unsupported data types
144
- Unsupported connection parameters
145
- Missing PostgreSQL extensions
146
"""
147
148
class ArrayContentNotSupportedError(NotSupportedError):
149
"""
150
Exception for unsupported array content errors.
151
152
Raised when attempting to use array data types with
153
content that is not supported by pg8000's array handling.
154
155
Common causes:
156
- Nested arrays beyond supported depth
157
- Array elements of unsupported types
158
- Mixed-type arrays
159
- Invalid array structure
160
"""
161
```
162
163
### DB-API 2.0 Warning Class
164
165
Warning class for non-error conditions that may require attention.
166
167
```python { .api }
168
class Warning(Exception):
169
"""
170
Exception for important warnings.
171
172
Raised for important warnings like data truncation while
173
inserting, etc. This exception is part of the DB-API 2.0
174
specification but is not currently used by pg8000.
175
176
Note: This class exists for DB-API 2.0 compliance but
177
pg8000 does not currently raise Warning exceptions.
178
"""
179
```
180
181
### DB-API 2.0 Constructor Functions
182
183
Standard DB-API 2.0 constructor functions for date/time and binary objects.
184
185
```python { .api }
186
def Date(year: int, month: int, day: int) -> datetime.date:
187
"""
188
Construct date object from year, month, day.
189
190
Parameters:
191
- year: Year value
192
- month: Month value (1-12)
193
- day: Day value (1-31)
194
195
Returns:
196
Python date object
197
198
Raises:
199
ValueError: If date values are invalid
200
"""
201
202
def Time(hour: int, minute: int, second: int) -> datetime.time:
203
"""
204
Construct time object from hour, minute, second.
205
206
Parameters:
207
- hour: Hour value (0-23)
208
- minute: Minute value (0-59)
209
- second: Second value (0-59)
210
211
Returns:
212
Python time object
213
214
Raises:
215
ValueError: If time values are invalid
216
"""
217
218
def Timestamp(year: int, month: int, day: int, hour: int, minute: int, second: int) -> datetime.datetime:
219
"""
220
Construct timestamp object from date and time components.
221
222
Parameters:
223
- year: Year value
224
- month: Month value (1-12)
225
- day: Day value (1-31)
226
- hour: Hour value (0-23)
227
- minute: Minute value (0-59)
228
- second: Second value (0-59)
229
230
Returns:
231
Python datetime object
232
233
Raises:
234
ValueError: If date/time values are invalid
235
"""
236
237
def DateFromTicks(ticks: float) -> datetime.date:
238
"""
239
Construct date object from Unix timestamp.
240
241
Parameters:
242
- ticks: Unix timestamp (seconds since epoch)
243
244
Returns:
245
Python date object
246
"""
247
248
def TimeFromTicks(ticks: float) -> datetime.time:
249
"""
250
Construct time object from Unix timestamp.
251
252
Parameters:
253
- ticks: Unix timestamp (seconds since epoch)
254
255
Returns:
256
Python time object
257
"""
258
259
def TimestampFromTicks(ticks: float) -> datetime.datetime:
260
"""
261
Construct timestamp object from Unix timestamp.
262
263
Parameters:
264
- ticks: Unix timestamp (seconds since epoch)
265
266
Returns:
267
Python datetime object
268
"""
269
270
def Binary(value: bytes) -> bytes:
271
"""
272
Construct binary object for database storage.
273
274
Parameters:
275
- value: Binary data as bytes
276
277
Returns:
278
Binary data object for database insertion
279
"""
280
```
281
282
### Usage Examples
283
284
#### Basic Exception Handling
285
286
```python
287
import pg8000
288
289
try:
290
conn = pg8000.connect(
291
user="invalid_user",
292
password="wrong_password",
293
database="nonexistent_db"
294
)
295
except pg8000.OperationalError as e:
296
print(f"Connection failed: {e}")
297
# Handle connection errors (retry, fallback, etc.)
298
except pg8000.InterfaceError as e:
299
print(f"Interface error: {e}")
300
# Handle parameter or interface errors
301
except pg8000.Error as e:
302
print(f"Database error: {e}")
303
# Handle any other pg8000 errors
304
```
305
306
#### Comprehensive Error Handling
307
308
```python
309
import pg8000
310
311
conn = pg8000.connect(user="myuser", password="mypass", database="mydb")
312
cursor = conn.cursor()
313
314
try:
315
# Attempt potentially problematic operations
316
cursor.execute("""
317
INSERT INTO users (id, email, age)
318
VALUES (%s, %s, %s)
319
""", (1, "user@example.com", 25))
320
321
conn.commit()
322
print("User inserted successfully")
323
324
except pg8000.IntegrityError as e:
325
print(f"Integrity constraint violated: {e}")
326
# Handle unique constraint, foreign key violations, etc.
327
conn.rollback()
328
329
except pg8000.DataError as e:
330
print(f"Data error: {e}")
331
# Handle data type errors, value out of range, etc.
332
conn.rollback()
333
334
except pg8000.ProgrammingError as e:
335
print(f"Programming error: {e}")
336
# Handle SQL syntax errors, invalid table names, etc.
337
conn.rollback()
338
339
except pg8000.OperationalError as e:
340
print(f"Operational error: {e}")
341
# Handle connection lost, server shutdown, etc.
342
conn.rollback()
343
344
except pg8000.DatabaseError as e:
345
print(f"Database error: {e}")
346
# Handle any other database-related errors
347
conn.rollback()
348
349
finally:
350
cursor.close()
351
conn.close()
352
```
353
354
#### Specific Error Scenarios
355
356
```python
357
import pg8000
358
359
conn = pg8000.connect(user="myuser", password="mypass", database="mydb")
360
cursor = conn.cursor()
361
362
# Scenario 1: SQL Syntax Error
363
try:
364
cursor.execute("SELCT * FROM users") # Typo in SELECT
365
except pg8000.ProgrammingError as e:
366
print(f"SQL syntax error: {e}")
367
368
# Scenario 2: Constraint Violation
369
try:
370
cursor.execute("INSERT INTO users (id, email) VALUES (%s, %s)", (1, "duplicate@example.com"))
371
cursor.execute("INSERT INTO users (id, email) VALUES (%s, %s)", (2, "duplicate@example.com")) # Unique constraint
372
conn.commit()
373
except pg8000.IntegrityError as e:
374
print(f"Constraint violation: {e}")
375
conn.rollback()
376
377
# Scenario 3: Data Type Error
378
try:
379
cursor.execute("INSERT INTO users (age) VALUES (%s)", ("not_a_number",))
380
conn.commit()
381
except pg8000.DataError as e:
382
print(f"Data type error: {e}")
383
conn.rollback()
384
385
# Scenario 4: Unsupported Operation
386
try:
387
cursor.execute("SELECT * FROM users FOR JSON AUTO") # SQL Server syntax
388
except pg8000.NotSupportedError as e:
389
print(f"Unsupported operation: {e}")
390
391
cursor.close()
392
conn.close()
393
```
394
395
#### Using DB-API 2.0 Constructor Functions
396
397
```python
398
import pg8000
399
import time
400
401
# Using DB-API 2.0 constructors
402
date_obj = pg8000.Date(2023, 12, 25)
403
time_obj = pg8000.Time(14, 30, 0)
404
timestamp_obj = pg8000.Timestamp(2023, 12, 25, 14, 30, 0)
405
406
# From Unix timestamps
407
current_time = time.time()
408
date_from_ticks = pg8000.DateFromTicks(current_time)
409
time_from_ticks = pg8000.TimeFromTicks(current_time)
410
timestamp_from_ticks = pg8000.TimestampFromTicks(current_time)
411
412
# Binary data
413
binary_data = pg8000.Binary(b"binary content")
414
415
# Use in database operations
416
conn = pg8000.connect(user="myuser", password="mypass", database="mydb")
417
cursor = conn.cursor()
418
419
try:
420
cursor.execute("""
421
INSERT INTO events (event_date, event_time, created_at, data)
422
VALUES (%s, %s, %s, %s)
423
""", (date_obj, time_obj, timestamp_obj, binary_data))
424
425
conn.commit()
426
print("Event data inserted successfully")
427
428
except pg8000.Error as e:
429
print(f"Error inserting event data: {e}")
430
conn.rollback()
431
432
finally:
433
cursor.close()
434
conn.close()
435
```