Documentation
¶
Overview ¶
Package postgres provides a PostgreSQL implementation for the orm.Database interface.
Index ¶
- Constants
- Variables
- func ConvertPostgreSQLError(err error) error
- func FormatPostgreSQLError(err error) string
- func GetPostgreSQLErrorCode(err error) string
- func GetPostgreSQLErrorDetail(err error) (code, message, detail, hint string)
- func IsCheckViolation(err error) bool
- func IsConnectionError(err error) bool
- func IsConstraintViolation(err error) bool
- func IsDeadlock(err error) bool
- func IsDuplicateColumn(err error) bool
- func IsDuplicateTable(err error) bool
- func IsForeignKeyViolation(err error) bool
- func IsInsufficientResources(err error) bool
- func IsNotNullViolation(err error) bool
- func IsRetryable(err error) bool
- func IsSerializationFailure(err error) bool
- func IsTooManyConnections(err error) bool
- func IsUndefinedColumn(err error) bool
- func IsUndefinedTable(err error) bool
- func IsUniqueViolation(err error) bool
- func WrapPostgreSQLError(err error, operation, table, query string) error
- type PostgreSQLError
- type PostgresConfig
- func (c *PostgresConfig) Clone() *PostgresConfig
- func (c *PostgresConfig) String() string
- func (c *PostgresConfig) ToDSN() (string, error)
- func (c *PostgresConfig) ToSimpleDSN() (string, error)
- func (c *PostgresConfig) Validate() error
- func (c *PostgresConfig) WithApplicationName(name string) *PostgresConfig
- func (c *PostgresConfig) WithConnectionPool(maxOpen, maxIdle int, maxLifetime, maxIdleTime time.Duration) *PostgresConfig
- func (c *PostgresConfig) WithExtraParam(key, value string) *PostgresConfig
- func (c *PostgresConfig) WithSSLMode(mode string) *PostgresConfig
- func (c *PostgresConfig) WithSearchPath(path string) *PostgresConfig
- func (c *PostgresConfig) WithTimeouts(connectTimeout, queryTimeout time.Duration) *PostgresConfig
- func (c *PostgresConfig) WithTimezone(tz string) *PostgresConfig
- type PostgresDirectDB
Constants ¶
const ( DefaultHost = "localhost" DefaultPort = 5432 DefaultSSLMode = "disable" DefaultConnectTimeout = 10 * time.Second DefaultQueryTimeout = 30 * time.Second DefaultMaxOpenConns = 25 DefaultMaxIdleConns = 5 DefaultConnMaxLifetime = 5 * time.Minute DefaultConnMaxIdleTime = 10 * time.Minute DefaultApplicationName = "simpleorm" )
Default configuration values
const ( // Class 23 - Integrity Constraint Violation ErrCodeUniqueViolation = "23505" ErrCodeForeignKeyViolation = "23503" ErrCodeNotNullViolation = "23502" ErrCodeCheckViolation = "23514" ErrCodeExclusionViolation = "23P01" // Class 42 - Syntax Error or Access Rule Violation ErrCodeUndefinedTable = "42P01" ErrCodeUndefinedColumn = "42703" ErrCodeDuplicateTable = "42P07" ErrCodeDuplicateColumn = "42701" ErrCodeInvalidSchemaName = "3F000" // Class 08 - Connection Exception ErrCodeConnectionException = "08000" ErrCodeConnectionFailure = "08006" ErrCodeSQLClientCannotConnect = "08001" // Class 57 - Operator Intervention ErrCodeAdminShutdown = "57P01" ErrCodeCrashShutdown = "57P02" ErrCodeCannotConnectNow = "57P03" // Class 53 - Insufficient Resources ErrCodeInsufficientResources = "53000" ErrCodeDiskFull = "53100" ErrCodeOutOfMemory = "53200" ErrCodeTooManyConnections = "53300" // Class 40 - Transaction Rollback ErrCodeDeadlockDetected = "40P01" ErrCodeSerializationFailure = "40001" )
PostgreSQL-specific error codes See: https://www.postgresql.org/docs/current/errcodes-appendix.html
Variables ¶
var ( ErrPostgresNotConnected medaerror.MedaError = medaerror.MedaError{Message: "PostgreSQL database is not connected"} ErrPostgresInvalidDSN medaerror.MedaError = medaerror.MedaError{Message: "invalid PostgreSQL DSN connection string"} ErrPostgresConnectionFailed medaerror.MedaError = medaerror.MedaError{Message: "failed to connect to PostgreSQL database"} ErrPostgresQueryFailed medaerror.MedaError = medaerror.MedaError{Message: "PostgreSQL query execution failed"} ErrPostgresTransactionFailed medaerror.MedaError = medaerror.MedaError{Message: "PostgreSQL transaction failed"} ErrPostgresInvalidConfig medaerror.MedaError = medaerror.MedaError{Message: "invalid PostgreSQL configuration"} ErrPostgresTimeout medaerror.MedaError = medaerror.MedaError{Message: "PostgreSQL operation timed out"} ErrPostgresNoAffectedRows medaerror.MedaError = medaerror.MedaError{Message: "PostgreSQL query affected zero rows"} )
Custom PostgreSQL errors using medaerror
Functions ¶
func ConvertPostgreSQLError ¶
ConvertPostgreSQLError converts a PostgreSQL error to an appropriate ORM error
func FormatPostgreSQLError ¶
FormatPostgreSQLError formats a PostgreSQL error for logging or display
func GetPostgreSQLErrorCode ¶
GetPostgreSQLErrorCode extracts the PostgreSQL error code from an error
func GetPostgreSQLErrorDetail ¶
GetPostgreSQLErrorDetail extracts the detailed error information
func IsCheckViolation ¶
IsCheckViolation checks if the error is a CHECK constraint violation
func IsConnectionError ¶
IsConnectionError checks if the error is related to database connection
func IsConstraintViolation ¶
IsConstraintViolation checks if the error is any type of constraint violation
func IsDeadlock ¶
IsDeadlock checks if the error is due to a deadlock
func IsDuplicateColumn ¶
IsDuplicateColumn checks if the error is due to attempting to create an existing column
func IsDuplicateTable ¶
IsDuplicateTable checks if the error is due to attempting to create an existing table
func IsForeignKeyViolation ¶
IsForeignKeyViolation checks if the error is a foreign key constraint violation
func IsInsufficientResources ¶
IsInsufficientResources checks if the error is due to insufficient resources
func IsNotNullViolation ¶
IsNotNullViolation checks if the error is a NOT NULL constraint violation
func IsRetryable ¶
IsRetryable checks if the error is transient and the operation can be retried
func IsSerializationFailure ¶
IsSerializationFailure checks if the error is a serialization failure
func IsTooManyConnections ¶
IsTooManyConnections checks if the error is due to too many connections
func IsUndefinedColumn ¶
IsUndefinedColumn checks if the error is due to a non-existent column
func IsUndefinedTable ¶
IsUndefinedTable checks if the error is due to a non-existent table
func IsUniqueViolation ¶
IsUniqueViolation checks if the error is a unique constraint violation
func WrapPostgreSQLError ¶
WrapPostgreSQLError wraps a PostgreSQL error with additional context
Types ¶
type PostgreSQLError ¶
type PostgreSQLError struct {
Operation string // The operation that failed (e.g., "INSERT", "SELECT", "UPDATE")
Table string // The table involved (if applicable)
Query string // The SQL query that failed (if applicable)
Code string // PostgreSQL error code
Message string // Error message
Detail string // Detailed error information
Hint string // Hint for fixing the error
Err error // Original error
}
PostgreSQLError wraps PostgreSQL-specific errors with additional context
func (*PostgreSQLError) Error ¶
func (e *PostgreSQLError) Error() string
Error implements the error interface
func (*PostgreSQLError) Unwrap ¶
func (e *PostgreSQLError) Unwrap() error
Unwrap returns the underlying error
type PostgresConfig ¶
type PostgresConfig struct {
// Connection parameters
Host string // Database host (default: "localhost")
Port int // Database port (default: 5432)
User string // Database user (required)
Password string // Database password (required)
DBName string // Database name (required)
SSLMode string // SSL mode: "disable", "require", "verify-ca", "verify-full" (default: "disable")
// Connection pooling
MaxOpenConns int // Maximum number of open connections (default: 25)
MaxIdleConns int // Maximum number of idle connections (default: 5)
ConnMaxLifetime time.Duration // Maximum lifetime of a connection (default: 5 minutes)
ConnMaxIdleTime time.Duration // Maximum idle time of a connection (default: 10 minutes)
// Timeouts
ConnectTimeout time.Duration // Connection timeout (default: 10 seconds)
QueryTimeout time.Duration // Query execution timeout (default: 30 seconds)
// Additional parameters
ApplicationName string // Application name for logging (default: "simpleorm")
SearchPath string // Schema search path (optional)
Timezone string // Timezone (optional, e.g., "UTC")
ExtraParams map[string]string // Additional connection parameters (optional)
}
PostgresConfig holds the configuration for PostgreSQL database connection
func NewConfig ¶
func NewConfig(host string, port int, user, password, dbName string) *PostgresConfig
NewConfig creates a new PostgresConfig with the specified database credentials and applies default values for other settings
func NewDefaultConfig ¶
func NewDefaultConfig() *PostgresConfig
NewDefaultConfig creates a new PostgresConfig with default values
func ParseDSN ¶
func ParseDSN(dsn string) (*PostgresConfig, error)
ParseDSN parses a PostgreSQL DSN connection string and returns a PostgresConfig Supports both URL format and key=value format
func (*PostgresConfig) Clone ¶
func (c *PostgresConfig) Clone() *PostgresConfig
Clone creates a deep copy of the PostgresConfig
func (*PostgresConfig) String ¶
func (c *PostgresConfig) String() string
String returns a safe string representation of the config (without password)
func (*PostgresConfig) ToDSN ¶
func (c *PostgresConfig) ToDSN() (string, error)
ToDSN converts the PostgresConfig to a Data Source Name (DSN) connection string Format: postgres://user:password@host:port/dbname?param1=value1¶m2=value2
func (*PostgresConfig) ToSimpleDSN ¶
func (c *PostgresConfig) ToSimpleDSN() (string, error)
ToSimpleDSN converts the PostgresConfig to a simple DSN connection string Format: host=localhost port=5432 user=postgres password=secret dbname=mydb sslmode=disable
func (*PostgresConfig) Validate ¶
func (c *PostgresConfig) Validate() error
Validate checks if the configuration is valid
func (*PostgresConfig) WithApplicationName ¶
func (c *PostgresConfig) WithApplicationName(name string) *PostgresConfig
WithApplicationName sets the application name and returns the config for method chaining
func (*PostgresConfig) WithConnectionPool ¶
func (c *PostgresConfig) WithConnectionPool(maxOpen, maxIdle int, maxLifetime, maxIdleTime time.Duration) *PostgresConfig
WithConnectionPool sets the connection pool parameters and returns the config for method chaining
func (*PostgresConfig) WithExtraParam ¶
func (c *PostgresConfig) WithExtraParam(key, value string) *PostgresConfig
WithExtraParam adds an extra connection parameter and returns the config for method chaining
func (*PostgresConfig) WithSSLMode ¶
func (c *PostgresConfig) WithSSLMode(mode string) *PostgresConfig
WithSSLMode sets the SSL mode and returns the config for method chaining
func (*PostgresConfig) WithSearchPath ¶
func (c *PostgresConfig) WithSearchPath(path string) *PostgresConfig
WithSearchPath sets the schema search path and returns the config for method chaining
func (*PostgresConfig) WithTimeouts ¶
func (c *PostgresConfig) WithTimeouts(connectTimeout, queryTimeout time.Duration) *PostgresConfig
WithTimeouts sets the timeout parameters and returns the config for method chaining
func (*PostgresConfig) WithTimezone ¶
func (c *PostgresConfig) WithTimezone(tz string) *PostgresConfig
WithTimezone sets the timezone and returns the config for method chaining
type PostgresDirectDB ¶
type PostgresDirectDB = *postgres
PostgresDirectDB is an alias to *postgres for external use The actual implementation is in the private postgres struct
func NewDatabase ¶
func NewDatabase(config PostgresConfig) (PostgresDirectDB, error)
NewDatabase creates a new PostgreSQL database instance. It takes a PostgresConfig and returns an implementation of orm.Database.