64 lines
2.0 KiB
Go
64 lines
2.0 KiB
Go
package postgres
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5/pgconn"
|
|
"github.com/jackc/pgx/v5/pgtype"
|
|
|
|
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
|
"lincodex/backend/internal/domain"
|
|
"lincodex/backend/internal/port/outbound"
|
|
)
|
|
|
|
const (
|
|
uniqueViolationCode = "23505"
|
|
|
|
outboxPrimaryKeyConstraint = "outbox_events_pkey"
|
|
outboxAggregateVersionConstraint = "outbox_events_aggregate_version_event_type_key"
|
|
)
|
|
|
|
type outboxWriter struct {
|
|
queries *sqlc.Queries
|
|
}
|
|
|
|
func (writer outboxWriter) Append(ctx context.Context, events ...domain.DomainEvent) error {
|
|
for _, event := range events {
|
|
if event.EventID() == uuid.Nil {
|
|
return fmt.Errorf("outboxWriter.Append - event was not built by domain.NewDomainEvent: %w", domain.ErrInvalidDomainEvent)
|
|
}
|
|
err := writer.queries.InsertOutboxEvent(ctx, sqlc.InsertOutboxEventParams{
|
|
EventID: pgtype.UUID{Bytes: event.EventID(), Valid: true},
|
|
EventType: event.EventType(),
|
|
SchemaVersion: event.SchemaVersion(),
|
|
AggregateType: event.AggregateType(),
|
|
AggregateID: pgtype.UUID{Bytes: event.AggregateID(), Valid: true},
|
|
AggregateVersion: event.AggregateVersion(),
|
|
Payload: event.Payload(),
|
|
})
|
|
if err != nil {
|
|
return fmt.Errorf("outboxWriter.Append - insert outbox event: %w", mapOutboxError(err))
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// mapOutboxError turns outbox uniqueness violations into a port sentinel that
|
|
// keeps the constraint name. Other errors pass through; PostgreSQL error text
|
|
// does not include key values.
|
|
func mapOutboxError(err error) error {
|
|
var pgError *pgconn.PgError
|
|
if !errors.As(err, &pgError) || pgError.Code != uniqueViolationCode {
|
|
return err
|
|
}
|
|
switch pgError.ConstraintName {
|
|
case outboxPrimaryKeyConstraint, outboxAggregateVersionConstraint:
|
|
return fmt.Errorf("postgres.mapOutboxError - violate constraint %s: %w", pgError.ConstraintName, outbound.ErrOutboxEventConflict)
|
|
default:
|
|
return err
|
|
}
|
|
}
|