Pure-Python PostgreSQL driver providing DB-API 2.0 compliant database connectivity with native pg8000 API and comprehensive PostgreSQL data type support.
—
Complete exception hierarchy for proper error handling following DB-API 2.0 standards with PostgreSQL-specific error categories and detailed error information.
Foundation exception classes providing the base for all pg8000 error conditions.
class Error(Exception):
"""
Base exception class for all pg8000 errors.
This is the root of the pg8000 exception hierarchy and catches
all database-related errors from pg8000.
"""
class InterfaceError(Error):
"""
Exception for database interface related errors.
Raised for errors related to the database interface rather than
the database itself. Includes connection parameter errors,
invalid API usage, and interface-level problems.
"""
class DatabaseError(Error):
"""
Exception for database related errors.
Base class for errors that occur during database operations.
This includes all errors that originate from PostgreSQL server
responses or database communication issues.
"""Exceptions for database operation and runtime errors.
class OperationalError(DatabaseError):
"""
Exception for database operational errors.
Raised for errors related to database operations that are not
under the control of the programmer. Includes connection failures,
server shutdowns, network errors, and similar operational issues.
Common causes:
- Connection timeout or loss
- Server unavailable or shutdown
- Network connectivity issues
- Authentication failures
- Permission denied errors
"""
class InternalError(DatabaseError):
"""
Exception for internal database errors.
Raised when PostgreSQL encounters an internal error condition.
These errors indicate problems within the database system itself
rather than with the application code or data.
Common causes:
- PostgreSQL internal errors
- System resource exhaustion
- Corrupted database structures
- PostgreSQL bugs or crashes
"""Exceptions for data validation and programming errors.
class DataError(DatabaseError):
"""
Exception for data processing errors.
Raised for errors due to problems with the processed data.
This includes data type mismatches, constraint violations,
and data format errors.
Common causes:
- Invalid data type conversion
- Data value out of range
- Invalid data format
- Constraint check violations
"""
class ProgrammingError(DatabaseError):
"""
Exception for programming errors.
Raised for errors in SQL syntax, invalid object names,
and other programming mistakes. These errors indicate
problems with the application code rather than runtime conditions.
Common causes:
- SQL syntax errors
- Invalid table or column names
- Missing required parameters
- Invalid SQL operations
- Prepared statement errors
"""Exceptions for data integrity and feature support issues.
class IntegrityError(DatabaseError):
"""
Exception for relational integrity errors.
Raised when database relational integrity is affected.
This includes foreign key constraint violations, unique
constraint violations, and other referential integrity issues.
Common causes:
- Foreign key constraint violations
- Unique constraint violations
- Primary key violations
- Check constraint failures
- NOT NULL violations
"""
class NotSupportedError(DatabaseError):
"""
Exception for unsupported operation errors.
Raised when an unsupported database operation is attempted.
This includes operations not supported by PostgreSQL or
by the pg8000 driver itself.
Common causes:
- Unsupported SQL features
- Unsupported data types
- Unsupported connection parameters
- Missing PostgreSQL extensions
"""
class ArrayContentNotSupportedError(NotSupportedError):
"""
Exception for unsupported array content errors.
Raised when attempting to use array data types with
content that is not supported by pg8000's array handling.
Common causes:
- Nested arrays beyond supported depth
- Array elements of unsupported types
- Mixed-type arrays
- Invalid array structure
"""Warning class for non-error conditions that may require attention.
class Warning(Exception):
"""
Exception for important warnings.
Raised for important warnings like data truncation while
inserting, etc. This exception is part of the DB-API 2.0
specification but is not currently used by pg8000.
Note: This class exists for DB-API 2.0 compliance but
pg8000 does not currently raise Warning exceptions.
"""Standard DB-API 2.0 constructor functions for date/time and binary objects.
def Date(year: int, month: int, day: int) -> datetime.date:
"""
Construct date object from year, month, day.
Parameters:
- year: Year value
- month: Month value (1-12)
- day: Day value (1-31)
Returns:
Python date object
Raises:
ValueError: If date values are invalid
"""
def Time(hour: int, minute: int, second: int) -> datetime.time:
"""
Construct time object from hour, minute, second.
Parameters:
- hour: Hour value (0-23)
- minute: Minute value (0-59)
- second: Second value (0-59)
Returns:
Python time object
Raises:
ValueError: If time values are invalid
"""
def Timestamp(year: int, month: int, day: int, hour: int, minute: int, second: int) -> datetime.datetime:
"""
Construct timestamp object from date and time components.
Parameters:
- year: Year value
- month: Month value (1-12)
- day: Day value (1-31)
- hour: Hour value (0-23)
- minute: Minute value (0-59)
- second: Second value (0-59)
Returns:
Python datetime object
Raises:
ValueError: If date/time values are invalid
"""
def DateFromTicks(ticks: float) -> datetime.date:
"""
Construct date object from Unix timestamp.
Parameters:
- ticks: Unix timestamp (seconds since epoch)
Returns:
Python date object
"""
def TimeFromTicks(ticks: float) -> datetime.time:
"""
Construct time object from Unix timestamp.
Parameters:
- ticks: Unix timestamp (seconds since epoch)
Returns:
Python time object
"""
def TimestampFromTicks(ticks: float) -> datetime.datetime:
"""
Construct timestamp object from Unix timestamp.
Parameters:
- ticks: Unix timestamp (seconds since epoch)
Returns:
Python datetime object
"""
def Binary(value: bytes) -> bytes:
"""
Construct binary object for database storage.
Parameters:
- value: Binary data as bytes
Returns:
Binary data object for database insertion
"""import pg8000
try:
conn = pg8000.connect(
user="invalid_user",
password="wrong_password",
database="nonexistent_db"
)
except pg8000.OperationalError as e:
print(f"Connection failed: {e}")
# Handle connection errors (retry, fallback, etc.)
except pg8000.InterfaceError as e:
print(f"Interface error: {e}")
# Handle parameter or interface errors
except pg8000.Error as e:
print(f"Database error: {e}")
# Handle any other pg8000 errorsimport pg8000
conn = pg8000.connect(user="myuser", password="mypass", database="mydb")
cursor = conn.cursor()
try:
# Attempt potentially problematic operations
cursor.execute("""
INSERT INTO users (id, email, age)
VALUES (%s, %s, %s)
""", (1, "user@example.com", 25))
conn.commit()
print("User inserted successfully")
except pg8000.IntegrityError as e:
print(f"Integrity constraint violated: {e}")
# Handle unique constraint, foreign key violations, etc.
conn.rollback()
except pg8000.DataError as e:
print(f"Data error: {e}")
# Handle data type errors, value out of range, etc.
conn.rollback()
except pg8000.ProgrammingError as e:
print(f"Programming error: {e}")
# Handle SQL syntax errors, invalid table names, etc.
conn.rollback()
except pg8000.OperationalError as e:
print(f"Operational error: {e}")
# Handle connection lost, server shutdown, etc.
conn.rollback()
except pg8000.DatabaseError as e:
print(f"Database error: {e}")
# Handle any other database-related errors
conn.rollback()
finally:
cursor.close()
conn.close()import pg8000
conn = pg8000.connect(user="myuser", password="mypass", database="mydb")
cursor = conn.cursor()
# Scenario 1: SQL Syntax Error
try:
cursor.execute("SELCT * FROM users") # Typo in SELECT
except pg8000.ProgrammingError as e:
print(f"SQL syntax error: {e}")
# Scenario 2: Constraint Violation
try:
cursor.execute("INSERT INTO users (id, email) VALUES (%s, %s)", (1, "duplicate@example.com"))
cursor.execute("INSERT INTO users (id, email) VALUES (%s, %s)", (2, "duplicate@example.com")) # Unique constraint
conn.commit()
except pg8000.IntegrityError as e:
print(f"Constraint violation: {e}")
conn.rollback()
# Scenario 3: Data Type Error
try:
cursor.execute("INSERT INTO users (age) VALUES (%s)", ("not_a_number",))
conn.commit()
except pg8000.DataError as e:
print(f"Data type error: {e}")
conn.rollback()
# Scenario 4: Unsupported Operation
try:
cursor.execute("SELECT * FROM users FOR JSON AUTO") # SQL Server syntax
except pg8000.NotSupportedError as e:
print(f"Unsupported operation: {e}")
cursor.close()
conn.close()import pg8000
import time
# Using DB-API 2.0 constructors
date_obj = pg8000.Date(2023, 12, 25)
time_obj = pg8000.Time(14, 30, 0)
timestamp_obj = pg8000.Timestamp(2023, 12, 25, 14, 30, 0)
# From Unix timestamps
current_time = time.time()
date_from_ticks = pg8000.DateFromTicks(current_time)
time_from_ticks = pg8000.TimeFromTicks(current_time)
timestamp_from_ticks = pg8000.TimestampFromTicks(current_time)
# Binary data
binary_data = pg8000.Binary(b"binary content")
# Use in database operations
conn = pg8000.connect(user="myuser", password="mypass", database="mydb")
cursor = conn.cursor()
try:
cursor.execute("""
INSERT INTO events (event_date, event_time, created_at, data)
VALUES (%s, %s, %s, %s)
""", (date_obj, time_obj, timestamp_obj, binary_data))
conn.commit()
print("Event data inserted successfully")
except pg8000.Error as e:
print(f"Error inserting event data: {e}")
conn.rollback()
finally:
cursor.close()
conn.close()Install with Tessl CLI
npx tessl i tessl/pypi-pg8000