Help us shape the future of Go! Take the 2026 Go Developer Survey

pgcode

package module
v0.0.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 8, 2026 License: MIT Imports: 0 Imported by: 1

README

pgcode

CI Go Reference codecov

A small Go package exposing PostgreSQL SQLSTATE constants as typed string values.

It is useful when you want to check or compare database error codes without manually retyping the SQLSTATE values from PostgreSQL documentation.

Features

  • PostgreSQL SQLSTATE constants for common and advanced error classes
  • Easy-to-use string constants
  • Compatible with Go modules
  • No runtime dependency beyond the Go standard library

Installation

go get github.com/b0r1ssh/pgcode

Usage

package main

import (
    "fmt"

    "github.com/b0r1ssh/pgcode"
)

func main() {
    fmt.Println(pgcode.UniqueViolation) // 23505
    fmt.Println(pgcode.SyntaxError)     // 42601
    fmt.Println(pgcode.ConnectionException)
}

Example constants

pgcode.UniqueViolation
pgcode.NotNullViolation
pgcode.ForeignKeyViolation
pgcode.InvalidPassword
pgcode.TimeoutExpired
pgcode.ConnectionException
pgcode.SyntaxError

The package includes constants for the major PostgreSQL SQLSTATE classes and many commonly used codes, including:

  • Class 00: successful completion
  • Class 08: connection exceptions
  • Class 22: data exceptions
  • Class 23: integrity constraint violations
  • Class 42: syntax errors and invalid object references
  • and many more PostgreSQL-specific states

License

This project is licensed under the MIT License. See the LICENSE file for details.

Contributing

Contributions are welcome. If you want to improve the list of SQLSTATE values or documentation, feel free to open a pull request.

Documentation

Index

Constants

View Source
const (
	// Class 00 — Successful Completion
	SuccessfulCompletion = "00000"

	// Class 01 — Warning
	Warning                          = "01000"
	NullValueEliminatedInSetFunction = "01003"
	StringDataRightTruncation        = "01004"
	PrivilegeNotRevoked              = "01006"
	PrivilegeNotGranted              = "01007"
	ImplicitZeroBitPadding           = "01008"
	DynamicResultSetsReturned        = "0100C"
	DeprecatedFeature                = "01P01"

	// Class 02 — No Data (this is also a warning class per the SQL standard)
	NoData                                = "02000"
	NoAdditionalDynamicResultSetsReturned = "02001"

	// Class 03 — SQL Statement Not Yet Complete
	SQLStatementNotYetComplete = "03000"

	// Class 08 — Connection Exception
	ConnectionException                           = "08000"
	SqlclientUnableToEstablishSqlconnection       = "08001"
	ConnectionDoesNotExist                        = "08003"
	SqlserverRejectedEstablishmentOfSqlconnection = "08004"
	ConnectionFailure                             = "08006"
	TransactionResolutionUnknown                  = "08007"
	ProtocolViolation                             = "08P01"

	// Class 09 — Triggered Action Exception
	TriggeredActionException = "09000"

	// Class 0A — Feature Not Supported
	FeatureNotSupported = "0A000"

	// Class 0B — Invalid Transaction Initiation
	InvalidTransactionInitiation = "0B000"

	// Class 0F — Locator Exception
	LocatorException            = "0F000"
	InvalidLocatorSpecification = "0F001"

	// Class 0L — Invalid Grantor
	InvalidGrantor        = "0L000"
	InvalidGrantOperation = "0LP01"

	// Class 0P — Invalid Role Specification
	InvalidRoleSpecification = "0P000"

	// Class 0Z — Diagnostics Exception
	DiagnosticsException                           = "0Z000"
	StackedDiagnosticsAccessedWithoutActiveHandler = "0Z002"

	// Class 20 — Case Not Found
	CaseNotFound = "20000"

	// Class 21 — Cardinality Violation
	CardinalityViolation = "21000"

	// Class 22 — Data Exception
	DataException                             = "22000"
	StringDataRightTruncationClass22          = "22001"
	NullValueNoIndicatorParameter             = "22002"
	NumericValueOutOfRange                    = "22003"
	NullValueNotAllowed                       = "22004"
	ErrorInAssignment                         = "22005"
	InvalidDatetimeFormat                     = "22007"
	DatetimeFieldOverflow                     = "22008"
	InvalidTimeZoneDisplacementValue          = "22009"
	EscapeCharacterConflict                   = "2200B"
	InvalidUseOfEscapeCharacter               = "2200C"
	InvalidEscapeOctet                        = "2200D"
	ZeroLengthCharacterString                 = "2200F"
	MostSpecificTypeMismatch                  = "2200G"
	SequenceGeneratorLimitExceeded            = "2200H"
	NotAnXMLDocument                          = "2200L"
	InvalidXMLDocument                        = "2200M"
	InvalidXMLContent                         = "2200N"
	InvalidXMLComment                         = "2200S"
	InvalidXMLProcessingInstruction           = "2200T"
	InvalidIndicatorParameterValue            = "22010"
	SubstringError                            = "22011"
	DivisionByZero                            = "22012"
	InvalidPrecedingOrFollowingSize           = "22013"
	InvalidArgumentForNtileFunction           = "22014"
	IntervalFieldOverflow                     = "22015"
	InvalidArgumentForNthValueFunction        = "22016"
	InvalidCharacterValueForCast              = "22018"
	InvalidEscapeCharacter                    = "22019"
	InvalidRegularExpression                  = "2201B"
	InvalidArgumentForLogarithm               = "2201E"
	InvalidArgumentForPowerFunction           = "2201F"
	InvalidArgumentForWidthBucketFunction     = "2201G"
	InvalidRowCountInLimitClause              = "2201W"
	InvalidRowCountInResultOffsetClause       = "2201X"
	CharacterNotInRepertoire                  = "22021"
	IndicatorOverflow                         = "22022"
	InvalidParameterValue                     = "22023"
	UnterminatedCString                       = "22024"
	InvalidEscapeSequence                     = "22025"
	StringDataLengthMismatch                  = "22026"
	TrimError                                 = "22027"
	ArraySubscriptError                       = "2202E"
	InvalidTablesampleRepeat                  = "2202G"
	InvalidTablesampleArgument                = "2202H"
	DuplicateJSONObjectKeyValue               = "22030"
	InvalidArgumentForSQLJSONDatetimeFunction = "22031"
	InvalidJSONText                           = "22032"
	InvalidSQLJSONSubscript                   = "22033"
	MoreThanOneSQLJSONItem                    = "22034"
	NoSQLJSONItem                             = "22035"
	NonNumericSQLJSONItem                     = "22036"
	NonUniqueKeysInAJSONObject                = "22037"
	SingletonSQLJSONItemRequired              = "22038"
	SQLJSONArrayNotFound                      = "22039"
	SQLJSONMemberNotFound                     = "2203A"
	SQLJSONNumberNotFound                     = "2203B"
	SQLJSONObjectNotFound                     = "2203C"
	TooManyJSONArrayElements                  = "2203D"
	TooManyJSONObjectMembers                  = "2203E"
	SQLJSONScalarRequired                     = "2203F"
	SQLJSONItemCannotBeCastToTargetType       = "2203G" // since PG15
	FloatingPointException                    = "22P01"
	InvalidTextRepresentation                 = "22P02"
	InvalidBinaryRepresentation               = "22P03"
	BadCopyFileFormat                         = "22P04"
	UntranslatableCharacter                   = "22P05"
	NonstandardUseOfEscapeCharacter           = "22P06"

	// Class 23 — Integrity Constraint Violation
	IntegrityConstraintViolation = "23000"
	RestrictViolation            = "23001"
	NotNullViolation             = "23502"
	ForeignKeyViolation          = "23503"
	UniqueViolation              = "23505"
	CheckViolation               = "23514"
	ExclusionViolation           = "23P01"

	// Class 24 — Invalid Cursor State
	InvalidCursorState = "24000"

	// Class 25 — Invalid Transaction State
	InvalidTransactionState                         = "25000"
	ActiveSQLTransaction                            = "25001"
	BranchTransactionAlreadyActive                  = "25002"
	InappropriateAccessModeForBranchTransaction     = "25003"
	InappropriateIsolationLevelForBranchTransaction = "25004"
	NoActiveSQLTransactionForBranchTransaction      = "25005"
	ReadOnlySQLTransaction                          = "25006"
	SchemaAndDataStatementMixingNotSupported        = "25007"
	HeldCursorRequiresSameIsolationLevel            = "25008"
	NoActiveSQLTransaction                          = "25P01"
	InFailedSQLTransaction                          = "25P02"
	IdleInTransactionSessionTimeout                 = "25P03"
	TransactionTimeout                              = "25P04" // since PG17

	// Class 26 — Invalid SQL Statement Name
	InvalidSQLStatementName = "26000"

	// Class 27 — Triggered Data Change Violation
	TriggeredDataChangeViolation = "27000"

	// Class 28 — Invalid Authorization Specification
	InvalidAuthorizationSpecification = "28000"
	InvalidPassword                   = "28P01"

	// Class 2B — Dependent Privilege Descriptors Still Exist
	DependentPrivilegeDescriptorsStillExist = "2B000"
	DependentObjectsStillExist              = "2BP01"

	// Class 2D — Invalid Transaction Termination
	InvalidTransactionTermination = "2D000"

	// Class 2F — SQL Routine Exception
	SQLRoutineException               = "2F000"
	ModifyingSQLDataNotPermitted      = "2F002"
	ProhibitedSQLStatementAttempted   = "2F003"
	ReadingSQLDataNotPermitted        = "2F004"
	FunctionExecutedNoReturnStatement = "2F005"

	// Class 34 — Invalid Cursor Name
	InvalidCursorName = "34000"

	// Class 38 — External Routine Exception
	ExternalRoutineException               = "38000"
	ContainingSQLNotPermitted              = "38001"
	ModifyingSQLDataNotPermittedClass38    = "38002"
	ProhibitedSQLStatementAttemptedClass38 = "38003"
	ReadingSQLDataNotPermittedClass38      = "38004"

	// Class 39 — External Routine Invocation Exception
	ExternalRoutineInvocationException = "39000"
	InvalidSQLStateReturned            = "39001"
	NullValueNotAllowedClass39         = "39004"
	TriggerProtocolViolated            = "39P01"
	SRFProtocolViolated                = "39P02"
	EventTriggerProtocolViolated       = "39P03"

	// Class 3B — Savepoint Exception
	SavepointException            = "3B000"
	InvalidSavepointSpecification = "3B001"

	// Class 3D — Invalid Catalog Name
	InvalidCatalogName = "3D000"

	// Class 3F — Invalid Schema Name
	InvalidSchemaName = "3F000"

	// Class 40 — Transaction Rollback
	TransactionRollback                     = "40000"
	SerializationFailure                    = "40001"
	TransactionIntegrityConstraintViolation = "40002"
	StatementCompletionUnknown              = "40003"
	DeadlockDetected                        = "40P01"

	// Class 42 — Syntax Error or Access Rule Violation
	SyntaxErrorOrAccessRuleViolation   = "42000"
	InsufficientPrivilege              = "42501"
	SyntaxError                        = "42601"
	InvalidName                        = "42602"
	InvalidColumnDefinition            = "42611"
	NameTooLong                        = "42622"
	DuplicateColumn                    = "42701"
	AmbiguousColumn                    = "42702"
	UndefinedColumn                    = "42703"
	UndefinedObject                    = "42704"
	DuplicateObject                    = "42710"
	DuplicateAlias                     = "42712"
	DuplicateFunction                  = "42723"
	AmbiguousFunction                  = "42725"
	GroupingError                      = "42803"
	DatatypeMismatch                   = "42804"
	WrongObjectType                    = "42809"
	InvalidForeignKey                  = "42830"
	CannotCoerce                       = "42846"
	UndefinedFunction                  = "42883"
	GeneratedAlways                    = "428C9"
	ReservedName                       = "42939"
	UndefinedTable                     = "42P01"
	UndefinedParameter                 = "42P02"
	DuplicateCursor                    = "42P03"
	DuplicateDatabase                  = "42P04"
	DuplicatePreparedStatement         = "42P05"
	DuplicateSchema                    = "42P06"
	DuplicateTable                     = "42P07"
	AmbiguousParameter                 = "42P08"
	AmbiguousAlias                     = "42P09"
	InvalidColumnReference             = "42P10"
	InvalidCursorDefinition            = "42P11"
	InvalidDatabaseDefinition          = "42P12"
	InvalidFunctionDefinition          = "42P13"
	InvalidPreparedStatementDefinition = "42P14"
	InvalidSchemaDefinition            = "42P15"
	InvalidTableDefinition             = "42P16"
	InvalidObjectDefinition            = "42P17"
	IndeterminateDatatype              = "42P18"
	InvalidRecursion                   = "42P19"
	WindowingError                     = "42P20"
	CollationMismatch                  = "42P21"
	IndeterminateCollation             = "42P22"

	// Class 44 — WITH CHECK OPTION Violation
	WithCheckOptionViolation = "44000"

	// Class 53 — Insufficient Resources
	InsufficientResources      = "53000"
	DiskFull                   = "53100"
	OutOfMemory                = "53200"
	TooManyConnections         = "53300"
	ConfigurationLimitExceeded = "53400"

	// Class 54 — Program Limit Exceeded
	ProgramLimitExceeded = "54000"
	StatementTooComplex  = "54001"
	TooManyColumns       = "54011"
	TooManyArguments     = "54023"

	// Class 55 — Object Not In Prerequisite State
	ObjectNotInPrerequisiteState = "55000"
	ObjectInUse                  = "55006"
	CantChangeRuntimeParam       = "55P02"
	LockNotAvailable             = "55P03"
	UnsafeNewEnumValueUsage      = "55P04"

	// Class 57 — Operator Intervention
	OperatorIntervention = "57000"
	QueryCanceled        = "57014"
	AdminShutdown        = "57P01"
	CrashShutdown        = "57P02"
	CannotConnectNow     = "57P03"
	DatabaseDropped      = "57P04"
	IdleSessionTimeout   = "57P05"

	// Class 58 — System Error (errors external to PostgreSQL itself)
	SystemError     = "58000"
	IOError         = "58030"
	UndefinedFile   = "58P01"
	DuplicateFile   = "58P02"
	FileNameTooLong = "58P03" // since PG18

	// Class 72 — Snapshot Failure
	SnapshotTooOld = "72000"

	// Class F0 — Configuration File Error
	ConfigFileError = "F0000"
	LockFileExists  = "F0001"

	// Class HV — Foreign Data Wrapper Error (SQL/MED)
	FDWError                             = "HV000"
	FDWOutOfMemory                       = "HV001"
	FDWDynamicParameterValueNeeded       = "HV002"
	FDWInvalidDataType                   = "HV004"
	FDWColumnNameNotFound                = "HV005"
	FDWInvalidDataTypeDescriptors        = "HV006"
	FDWInvalidColumnName                 = "HV007"
	FDWInvalidColumnNumber               = "HV008"
	FDWInvalidUseOfNullPointer           = "HV009"
	FDWInvalidStringFormat               = "HV00A"
	FDWInvalidHandle                     = "HV00B"
	FDWInvalidOptionIndex                = "HV00C"
	FDWInvalidOptionName                 = "HV00D"
	FDWOptionNameNotFound                = "HV00J"
	FDWReplyHandle                       = "HV00K"
	FDWUnableToCreateExecution           = "HV00L"
	FDWUnableToCreateReply               = "HV00M"
	FDWUnableToEstablishConnection       = "HV00N"
	FDWNoSchemas                         = "HV00P"
	FDWSchemaNotFound                    = "HV00Q"
	FDWTableNotFound                     = "HV00R"
	FDWFunctionSequenceError             = "HV010"
	FDWTooManyHandles                    = "HV014"
	FDWInconsistentDescriptorInformation = "HV021"
	FDWInvalidAttributeValue             = "HV024"
	FDWInvalidStringLengthOrBufferLength = "HV090"
	FDWInvalidDescriptorFieldIdentifier  = "HV091"

	// Class P0 — PL/pgSQL Error
	PLpgSQLError   = "P0000"
	RaiseException = "P0001"
	NoDataFound    = "P0002"
	TooManyRows    = "P0003"
	AssertFailure  = "P0004"

	// Class XX — Internal Error
	InternalError  = "XX000"
	DataCorrupted  = "XX001"
	IndexCorrupted = "XX002"

	// Class 10 — XQuery Error
	InvalidArgumentForXquery = "10608" // since PG18
)

Constants for every PostgreSQL SQLSTATE code. When multiple codes share a condition name, the primary code keeps the clean name and aliases are suffixed with their class: e.g. ModifyingSQLDataNotPermittedClass38.

Variables

This section is empty.

Functions

func IsCardinalityViolation

func IsCardinalityViolation(code string) bool

IsCardinalityViolation returns true if code belongs to Class 21 — Cardinality Violation.

func IsCaseNotFound

func IsCaseNotFound(code string) bool

IsCaseNotFound returns true if code belongs to Class 20 — Case Not Found.

func IsConfigurationFileError

func IsConfigurationFileError(code string) bool

IsConfigurationFileError returns true if code belongs to Class F0 — Configuration File Error.

func IsConnectionException

func IsConnectionException(code string) bool

IsConnectionException returns true if code belongs to Class 08 — Connection Exception.

func IsDataException

func IsDataException(code string) bool

IsDataException returns true if code belongs to Class 22 — Data Exception.

func IsDependentPrivilegeDescriptorsStillExist

func IsDependentPrivilegeDescriptorsStillExist(code string) bool

IsDependentPrivilegeDescriptorsStillExist returns true if code belongs to Class 2B — Dependent Privilege Descriptors Still Exist.

func IsDiagnosticsException

func IsDiagnosticsException(code string) bool

IsDiagnosticsException returns true if code belongs to Class 0Z — Diagnostics Exception.

func IsExternalRoutineException

func IsExternalRoutineException(code string) bool

IsExternalRoutineException returns true if code belongs to Class 38 — External Routine Exception.

func IsExternalRoutineInvocationException

func IsExternalRoutineInvocationException(code string) bool

IsExternalRoutineInvocationException returns true if code belongs to Class 39 — External Routine Invocation Exception.

func IsFeatureNotSupported

func IsFeatureNotSupported(code string) bool

IsFeatureNotSupported returns true if code belongs to Class 0A — Feature Not Supported.

func IsForeignDataWrapperError

func IsForeignDataWrapperError(code string) bool

IsForeignDataWrapperError returns true if code belongs to Class HV — Foreign Data Wrapper Error (SQL/MED).

func IsInsufficientResources

func IsInsufficientResources(code string) bool

IsInsufficientResources returns true if code belongs to Class 53 — Insufficient Resources.

func IsIntegrityConstraintViolation

func IsIntegrityConstraintViolation(code string) bool

IsIntegrityConstraintViolation returns true if code belongs to Class 23 — Integrity Constraint Violation.

func IsInternalError

func IsInternalError(code string) bool

IsInternalError returns true if code belongs to Class XX — Internal Error.

func IsInvalidAuthorizationSpecification

func IsInvalidAuthorizationSpecification(code string) bool

IsInvalidAuthorizationSpecification returns true if code belongs to Class 28 — Invalid Authorization Specification.

func IsInvalidCatalogName

func IsInvalidCatalogName(code string) bool

IsInvalidCatalogName returns true if code belongs to Class 3D — Invalid Catalog Name.

func IsInvalidCursorName

func IsInvalidCursorName(code string) bool

IsInvalidCursorName returns true if code belongs to Class 34 — Invalid Cursor Name.

func IsInvalidCursorState

func IsInvalidCursorState(code string) bool

IsInvalidCursorState returns true if code belongs to Class 24 — Invalid Cursor State.

func IsInvalidGrantor

func IsInvalidGrantor(code string) bool

IsInvalidGrantor returns true if code belongs to Class 0L — Invalid Grantor.

func IsInvalidRoleSpecification

func IsInvalidRoleSpecification(code string) bool

IsInvalidRoleSpecification returns true if code belongs to Class 0P — Invalid Role Specification.

func IsInvalidSchemaName

func IsInvalidSchemaName(code string) bool

IsInvalidSchemaName returns true if code belongs to Class 3F — Invalid Schema Name.

func IsInvalidSqlStatementName

func IsInvalidSqlStatementName(code string) bool

IsInvalidSqlStatementName returns true if code belongs to Class 26 — Invalid SQL Statement Name.

func IsInvalidTransactionInitiation

func IsInvalidTransactionInitiation(code string) bool

IsInvalidTransactionInitiation returns true if code belongs to Class 0B — Invalid Transaction Initiation.

func IsInvalidTransactionState

func IsInvalidTransactionState(code string) bool

IsInvalidTransactionState returns true if code belongs to Class 25 — Invalid Transaction State.

func IsInvalidTransactionTermination

func IsInvalidTransactionTermination(code string) bool

IsInvalidTransactionTermination returns true if code belongs to Class 2D — Invalid Transaction Termination.

func IsLocatorException

func IsLocatorException(code string) bool

IsLocatorException returns true if code belongs to Class 0F — Locator Exception.

func IsNoData

func IsNoData(code string) bool

IsNoData returns true if code belongs to Class 02 — No Data (this is also a warning class per the SQL standard).

func IsObjectNotInPrerequisiteState

func IsObjectNotInPrerequisiteState(code string) bool

IsObjectNotInPrerequisiteState returns true if code belongs to Class 55 — Object Not In Prerequisite State.

func IsOperatorIntervention

func IsOperatorIntervention(code string) bool

IsOperatorIntervention returns true if code belongs to Class 57 — Operator Intervention.

func IsPl

func IsPl(code string) bool

IsPl returns true if code belongs to Class P0 — PL/pgSQL Error.

func IsProgramLimitExceeded

func IsProgramLimitExceeded(code string) bool

IsProgramLimitExceeded returns true if code belongs to Class 54 — Program Limit Exceeded.

func IsSavepointException

func IsSavepointException(code string) bool

IsSavepointException returns true if code belongs to Class 3B — Savepoint Exception.

func IsSnapshotFailure

func IsSnapshotFailure(code string) bool

IsSnapshotFailure returns true if code belongs to Class 72 — Snapshot Failure.

func IsSqlRoutineException

func IsSqlRoutineException(code string) bool

IsSqlRoutineException returns true if code belongs to Class 2F — SQL Routine Exception.

func IsSqlStatementNotYetComplete

func IsSqlStatementNotYetComplete(code string) bool

IsSqlStatementNotYetComplete returns true if code belongs to Class 03 — SQL Statement Not Yet Complete.

func IsSuccessfulCompletion

func IsSuccessfulCompletion(code string) bool

IsSuccessfulCompletion returns true if code belongs to Class 00 — Successful Completion.

func IsSyntaxErrorOrAccessRuleViolation

func IsSyntaxErrorOrAccessRuleViolation(code string) bool

IsSyntaxErrorOrAccessRuleViolation returns true if code belongs to Class 42 — Syntax Error or Access Rule Violation.

func IsSystemError

func IsSystemError(code string) bool

IsSystemError returns true if code belongs to Class 58 — System Error (errors external to PostgreSQL itself).

func IsTransactionRollback

func IsTransactionRollback(code string) bool

IsTransactionRollback returns true if code belongs to Class 40 — Transaction Rollback.

func IsTriggeredActionException

func IsTriggeredActionException(code string) bool

IsTriggeredActionException returns true if code belongs to Class 09 — Triggered Action Exception.

func IsTriggeredDataChangeViolation

func IsTriggeredDataChangeViolation(code string) bool

IsTriggeredDataChangeViolation returns true if code belongs to Class 27 — Triggered Data Change Violation.

func IsWarning

func IsWarning(code string) bool

IsWarning returns true if code belongs to Class 01 — Warning.

func IsWithCheckOptionViolation

func IsWithCheckOptionViolation(code string) bool

IsWithCheckOptionViolation returns true if code belongs to Class 44 — WITH CHECK OPTION Violation.

func IsXqueryError

func IsXqueryError(code string) bool

IsXqueryError returns true if code belongs to Class 10 — XQuery Error.

func Name

func Name(code string) string

Name returns the constant name for a PostgreSQL error code, or an empty string if the code is not recognised.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL