55 lines
1.6 KiB
Go
55 lines
1.6 KiB
Go
package postgres
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
|
|
"lincodex/backend/internal/port/outbound"
|
|
)
|
|
|
|
const (
|
|
deadlockDetectedCode = "40P01"
|
|
serializationFailureCode = "40001"
|
|
)
|
|
|
|
// databaseError keeps only the SQLSTATE and constraint name of a PostgreSQL
|
|
// error. The message and detail of a pgconn.PgError can quote row values, such
|
|
// as an email address or a password hash, so repositories that handle
|
|
// personal data return this type instead.
|
|
type databaseError struct {
|
|
code string
|
|
constraint string
|
|
}
|
|
|
|
func (err *databaseError) Error() string {
|
|
if err.constraint == "" {
|
|
return "PostgreSQL error SQLSTATE " + err.code
|
|
}
|
|
return "PostgreSQL error SQLSTATE " + err.code + " on constraint " + err.constraint
|
|
}
|
|
|
|
// SQLState matches the method of pgconn.PgError, so callers can read the code
|
|
// from either type.
|
|
func (err *databaseError) SQLState() string { return err.code }
|
|
|
|
// sqlStateError is implemented by pgconn.PgError and databaseError.
|
|
type sqlStateError interface {
|
|
error
|
|
SQLState() string
|
|
}
|
|
|
|
// markTransactionConflict makes a deadlock or serialization failure also
|
|
// match outbound.ErrTransactionConflict and returns other errors unchanged.
|
|
func markTransactionConflict(err error) error {
|
|
var stateError sqlStateError
|
|
if err == nil || errors.Is(err, outbound.ErrTransactionConflict) || !errors.As(err, &stateError) {
|
|
return err
|
|
}
|
|
switch code := stateError.SQLState(); code {
|
|
case deadlockDetectedCode, serializationFailureCode:
|
|
return fmt.Errorf("postgres.markTransactionConflict - SQLSTATE %s: %w: %w", code, outbound.ErrTransactionConflict, err)
|
|
default:
|
|
return err
|
|
}
|
|
}
|