### Check for Insufficient Resources Errors in Go Source: https://context7.com/jackc/pgerrcode/llms.txt Use `pgerrcode.IsInsufficientResources` to check if an error belongs to Class 53. This example demonstrates handling specific resource errors like TooManyConnections, DiskFull, and OutOfMemory by retrying or returning critical messages. ```go package main import ( "database/sql" "errors" "fmt" "time" "github.com/jackc/pgerrcode" "github.com/jackc/pgx/v5/pgconn" ) func executeWithResourceCheck(db *sql.DB, query string) error { _, err := db.Exec(query) if err != nil { var pgErr *pgconn.PgError if errors.As(err, &pgErr) { if pgerrcode.IsInsufficientResources(pgErr.Code) { switch pgErr.Code { case pgerrcode.TooManyConnections: // Wait and retry for connection pool exhaustion time.Sleep(5 * time.Second) return fmt.Errorf("server overloaded, please retry: %w", err) case pgerrcode.DiskFull: return fmt.Errorf("critical: database disk full - %w", err) case pgerrcode.OutOfMemory: return fmt.Errorf("critical: database out of memory - %w", err) default: return fmt.Errorf("resource constraint: %s - %w", pgerrcode.Name(pgErr.Code), err) } } } return err } return nil } // Handles: TooManyConnections (53300), DiskFull (53100), OutOfMemory (53200), etc. ``` -------------------------------- ### Get PostgreSQL Error Code Names in Go Source: https://context7.com/jackc/pgerrcode/llms.txt Use pgerrcode.Name to retrieve the human-readable string name for a PostgreSQL error code. This is useful for logging and debugging, returning an empty string for unrecognized codes. ```go package main import ( "database/sql" "errors" "fmt" "log" "github.com/jackc/pgerrcode" "github.com/jackc/pgx/v5/pgconn" ) func logDatabaseError(operation string, err error) { var pgErr *pgconn.PgError if errors.As(err, &pgErr) { codeName := pgerrcode.Name(pgErr.Code) if codeName == "" { codeName = "Unknown" } log.Printf("[DB ERROR] Operation: %s | Code: %s (%s) | Message: %s | Detail: %s", operation, pgErr.Code, codeName, pgErr.Message, pgErr.Detail, ) } else { log.Printf("[DB ERROR] Operation: %s | Error: %v", operation, err) } } func main() { // Example: Get human-readable names for common error codes codes := []string{"23505", "23503", "42P01", "40001", "53300"} for _, code := range codes { fmt.Printf("Code %s = %s\n", code, pgerrcode.Name(code)) } } // Output: // Code 23505 = UniqueViolation // Code 23503 = ForeignKeyViolation // Code 42P01 = UndefinedTable // Code 40001 = SerializationFailure // Code 53300 = TooManyConnections ``` -------------------------------- ### Handle PostgreSQL Errors with pgerrcode Source: https://context7.com/jackc/pgerrcode/llms.txt Demonstrates how to use pgerrcode constants to identify and handle specific PostgreSQL errors, such as unique violations, when inserting data. Requires importing 'github.com/jackc/pgerrcode' and 'github.com/jackc/pgx/v5/pgconn'. ```go package main import ( "database/sql" "errors" "fmt" "log" "github.com/jackc/pgerrcode" "github.com/jackc/pgx/v5/pgconn" _ "github.com/jackc/pgx/v5/stdlib" ) func main() { db, err := sql.Open("pgx", "postgres://localhost/mydb") if err != nil { log.Fatal(err) } defer db.Close() // Attempt to insert a duplicate record _, err = db.Exec("INSERT INTO users (id, email) VALUES (1, 'test@example.com')") if err != nil { var pgErr *pgconn.PgError if errors.As(err, &pgErr) { switch pgErr.Code { case pgerrcode.UniqueViolation: fmt.Println("Duplicate entry - record already exists") case pgerrcode.ForeignKeyViolation: fmt.Println("Foreign key constraint failed") case pgerrcode.NotNullViolation: fmt.Println("Required field is missing") case pgerrcode.CheckViolation: fmt.Println("Check constraint failed") default: fmt.Printf("Database error: %s (code: %s)\n", pgErr.Message, pgErr.Code) } } } } // Output: Duplicate entry - record already exists ``` -------------------------------- ### Common PostgreSQL Error Code Constants in Go Source: https://context7.com/jackc/pgerrcode/llms.txt Reference common PostgreSQL error code constants provided by the pgerrcode package. These constants, such as `UniqueViolation` and `ConnectionFailure`, can be used for direct comparison with error codes. ```go package main import "github.com/jackc/pgerrcode" // Integrity Constraint Violations (Class 23) var _ = pgerrcode.UniqueViolation // "23505" - Duplicate key var _ = pgerrcode.ForeignKeyViolation // "23503" - FK constraint failed var _ = pgerrcode.NotNullViolation // "23502" - NULL in non-null column var _ = pgerrcode.CheckViolation // "23514" - Check constraint failed var _ = pgerrcode.ExclusionViolation // "23P01" - Exclusion constraint failed // Connection Exceptions (Class 08) var _ = pgerrcode.ConnectionException // "08000" - General connection error var _ = pgerrcode.ConnectionFailure // "08006" - Connection lost var _ = pgerrcode.ProtocolViolation // "08P01" - Protocol error // Transaction Rollback (Class 40) var _ = pgerrcode.SerializationFailure // "40001" - Serializable isolation conflict var _ = pgerrcode.DeadlockDetected // "40P01" - Deadlock between transactions // Syntax/Access Errors (Class 42) var _ = pgerrcode.SyntaxError // "42601" - SQL syntax error var _ = pgerrcode.UndefinedTable // "42P01" - Table does not exist var _ = pgerrcode.UndefinedColumn // "42703" - Column does not exist var _ = pgerrcode.InsufficientPrivilege // "42501" - Permission denied var _ = pgerrcode.DuplicateTable // "42P07" - Table already exists // Resource Errors (Class 53) var _ = pgerrcode.TooManyConnections // "53300" - Connection limit exceeded var _ = pgerrcode.DiskFull // "53100" - No disk space var _ = pgerrcode.OutOfMemory // "53200" - Memory exhausted // Data Exceptions (Class 22) var _ = pgerrcode.DivisionByZero // "22012" - Division by zero var _ = pgerrcode.NumericValueOutOfRange // "22003" - Value out of range var _ = pgerrcode.InvalidTextRepresentation // "22P02" - Invalid input syntax ``` -------------------------------- ### Validate SQL Queries for Syntax Errors in Go Source: https://context7.com/jackc/pgerrcode/llms.txt Use IsSyntaxErrororAccessRuleViolation to validate SQL queries without execution using EXPLAIN. This helps catch syntax errors, undefined tables/columns, and permission issues early. ```go package main import ( "database/sql" "errors" "fmt" "github.com/jackc/pgerrcode" "github.com/jackc/pgx/v5/pgconn" ) func validateQuery(db *sql.DB, query string) error { // Use EXPLAIN to validate query without executing _, err := db.Exec("EXPLAIN " + query) if err != nil { var pgErr *pgconn.PgError if errors.As(err, &pgErr) { if pgerrcode.IsSyntaxErrororAccessRuleViolation(pgErr.Code) { switch pgErr.Code { case pgerrcode.SyntaxError: return fmt.Errorf("SQL syntax error at position %d: %s", pgErr.Position, pgErr.Message) case pgerrcode.UndefinedTable: return fmt.Errorf("table does not exist: %s", pgErr.Message) case pgerrcode.UndefinedColumn: return fmt.Errorf("column does not exist: %s", pgErr.Message) case pgerrcode.InsufficientPrivilege: return fmt.Errorf("permission denied: %s", pgErr.Message) default: return fmt.Errorf("query validation failed: %s", pgErr.Message) } } } return err } return nil } // Validates queries and provides specific error messages for Class 42 errors ``` -------------------------------- ### Retry Database Operations on Connection Exceptions Source: https://context7.com/jackc/pgerrcode/llms.txt Implements a retry mechanism for database operations, specifically retrying on connection-related errors identified by `pgerrcode.IsConnectionException`. It includes a maximum retry count and exponential backoff. ```go package main import ( "context" "database/sql" "errors" "fmt" "time" "github.com/jackc/pgerrcode" "github.com/jackc/pgx/v5/pgconn" ) func executeWithRetry(db *sql.DB, query string, maxRetries int) error { var lastErr error for attempt := 0; attempt < maxRetries; attempt++ { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) _, err := db.ExecContext(ctx, query) cancel() if err == nil { return nil } lastErr = err var pgErr *pgconn.PgError if errors.As(err, &pgErr) { if pgerrcode.IsConnectionException(pgErr.Code) { fmt.Printf("Connection error (attempt %d/%d): %s\n", attempt+1, maxRetries, pgErr.Message) time.Sleep(time.Duration(attempt+1) * time.Second) continue } } // Non-retryable error return err } return fmt.Errorf("max retries exceeded: %w", lastErr) } // Retries on: ConnectionFailure (08006), ConnectionDoesNotExist (08003), ProtocolViolation (08P01), etc. ``` -------------------------------- ### Check for Integrity Constraint Violations Source: https://context7.com/jackc/pgerrcode/llms.txt Utilizes `pgerrcode.IsIntegrityConstraintViolation` to uniformly handle data integrity errors, such as unique or foreign key violations. This function requires a PostgreSQL error code string. ```go package main import ( "database/sql" "errors" "fmt" "github.com/jackc/pgerrcode" "github.com/jackc/pgx/v5/pgconn" ) func handleDatabaseError(err error) error { var pgErr *pgconn.PgError if errors.As(err, &pgErr) { if pgerrcode.IsIntegrityConstraintViolation(pgErr.Code) { // Handle all constraint violations uniformly return fmt.Errorf("data integrity error: %s (constraint: %s)", pgErr.Message, pgErr.ConstraintName) } } return err } func createUser(db *sql.DB, email string) error { _, err := db.Exec("INSERT INTO users (email) VALUES ($1)", email) if err != nil { return handleDatabaseError(err) } return nil } // Example usage: createUser returns "data integrity error: duplicate key value violates unique constraint \"users_email_key\" (constraint: users_email_key)" ``` -------------------------------- ### Check for Transaction Rollback Errors in Go Source: https://context7.com/jackc/pgerrcode/llms.txt Use IsTransactionRollback to check if an error warrants retrying a transaction, such as serialization failures or deadlocks. This function is useful within transaction retry logic. ```go package main import ( "context" "database/sql" "errors" "fmt" "github.com/jackc/pgerrcode" "github.com/jackc/pgx/v5/pgconn" ) func executeInTransaction(db *sql.DB, fn func(*sql.Tx) error) error { maxRetries := 3 for attempt := 0; attempt < maxRetries; attempt++ { tx, err := db.BeginTx(context.Background(), &sql.TxOptions{ Isolation: sql.LevelSerializable, }) if err != nil { return err } err = fn(tx) if err != nil { tx.Rollback() var pgErr *pgconn.PgError if errors.As(err, &pgErr) { if pgerrcode.IsTransactionRollback(pgErr.Code) { // Serialization failure or deadlock - safe to retry fmt.Printf("Transaction conflict, retrying (attempt %d): %s\n", attempt+1, pgerrcode.Name(pgErr.Code)) continue } } return err } if err := tx.Commit(); err != nil { var pgErr *pgconn.PgError if errors.As(err, &pgErr) && pgerrcode.IsTransactionRollback(pgErr.Code) { continue } return err } return nil } return fmt.Errorf("transaction failed after %d attempts", maxRetries) } // Handles: SerializationFailure (40001), DeadlockDetected (40P01), etc. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.