common.go 858 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. package repositories
  2. import (
  3. "context"
  4. "database/sql"
  5. "errors"
  6. "github.com/lib/pq"
  7. )
  8. const (
  9. FKViolationErrorCode = "23503"
  10. DuplicateKeyErrorCode = "23505"
  11. )
  12. type DB interface {
  13. SelectContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error
  14. GetContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error
  15. ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
  16. QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
  17. }
  18. func IsFKViolationError(err error) bool {
  19. var pgErr *pq.Error
  20. if errors.As(err, &pgErr) {
  21. return pgErr.Code == FKViolationErrorCode
  22. }
  23. return false
  24. }
  25. func IsDuplicateKeyError(err error) bool {
  26. var pgErr *pq.Error
  27. if errors.As(err, &pgErr) {
  28. return pgErr.Code == DuplicateKeyErrorCode
  29. }
  30. return false
  31. }