Documentation
¶
Overview ¶
Package postgres implements evt.Repository and evt.Store with PostgreSQL.
Events are append-only and unique per (entity_id, sequence); duplicate commits return evt.ConflictError. Reads are sequence-ordered, event and snapshot writes are atomic, and durable snapshots become the replay floor after compaction.
Repository implements evt.Compactor, evt.SnapshotStreamer, evt.EntityHeadStreamer, and evt.EntityHeadVisitor. EnsureSchema owns the idempotent table DDL.
Index ¶
- Constants
- func NewStore(db DB, opts ...Option) evt.Store
- func NewStoreFromRepo(repo evt.Repository) evt.Store
- type DB
- type Option
- type Repository
- func (repo *Repository) Commit(ctx context.Context, res evt.SerializedResult) error
- func (repo *Repository) CommitStream(ctx context.Context, channel <-chan result.Result[evt.SerializedResult]) []error
- func (repo *Repository) CommitWithSnapshot(ctx context.Context, res evt.SerializedResult, entityType evt.EntityType, ...) error
- func (repo *Repository) CompactBelow(ctx context.Context, entityID evt.EntityID, throughSequence evt.EventSequence) (int, error)
- func (repo *Repository) EnsureSchema(ctx context.Context) error
- func (repo *Repository) GetEvents(ctx context.Context, entityID evt.EntityID) ([]evt.SerializedEvent, error)
- func (repo *Repository) GetLatestEvents(ctx context.Context, entityID evt.EntityID, lastSequence evt.EventSequence) ([]evt.SerializedEvent, error)
- func (repo *Repository) GetSnapshot(ctx context.Context, entityID evt.EntityID) (*evt.SerializedSnapshot, error)
- func (repo *Repository) StreamAllEvents(ctx context.Context, filter evt.StreamFilter) <-chan result.Result[[]evt.SerializedEvent]
- func (repo *Repository) StreamEntities(ctx context.Context, filter evt.StreamFilter, ...) <-chan result.Result[evt.Entity]
- func (repo *Repository) StreamEntitiesFromSnapshots(ctx context.Context, entityType evt.EntityType, seedEntity evt.SnapshotSeeder, ...) <-chan result.Result[evt.Entity]
- func (repo *Repository) StreamEntityHeads(ctx context.Context, entityType evt.EntityType) (map[evt.EntityID]evt.EventSequence, error)
- func (repo *Repository) StreamEntityHeadsFunc(ctx context.Context, entityType evt.EntityType, ...) error
Constants ¶
const DefaultSnapshotInterval = 5
DefaultSnapshotInterval is the number of events between durable snapshots for stores constructed with NewStore. It mirrors the in-memory and DynamoDB defaults.
const StorageTypePostgres evt.StorageType = "postgres"
StorageTypePostgres identifies transaction groups and repositories backed by PostgreSQL.
Variables ¶
This section is empty.
Functions ¶
func NewStoreFromRepo ¶
func NewStoreFromRepo(repo evt.Repository) evt.Store
NewStoreFromRepo wraps an existing Repository in a snapshot-taking evt.Store.
Types ¶
type DB ¶
type DB interface {
Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error)
Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
QueryRow(ctx context.Context, sql string, args ...any) pgx.Row
Begin(ctx context.Context) (pgx.Tx, error)
}
DB is the minimal subset of the pgx API the Repository depends on. Both *pgxpool.Pool and pgx.Tx satisfy it, so callers can pass a pool (the common case) or an ambient transaction. It is the abstraction point for the backend, mirroring dynamo.Client.
type Option ¶
type Option func(*Repository)
Option configures a Repository at construction time.
func WithEventsTable ¶
WithEventsTable overrides the event-log table name (default "evt_events").
func WithSnapshotsTable ¶
WithSnapshotsTable overrides the snapshot table name (default "evt_snapshots").
type Repository ¶
type Repository struct {
// contains filtered or unexported fields
}
Repository is a PostgreSQL-backed evt.Repository. Construct it with NewRepository.
func NewRepository ¶
func NewRepository(db DB, opts ...Option) *Repository
NewRepository constructs a Repository over the given pgx handle (typically a *pgxpool.Pool). It panics if a configured table name is not a valid SQL identifier, since that is a programming error in wiring rather than a runtime condition.
func (*Repository) Commit ¶
func (repo *Repository) Commit(ctx context.Context, res evt.SerializedResult) error
Commit persists the events in a SerializedResult inside a single transaction. A duplicate (entity_id, sequence) pair violates the primary key and is returned as an evt.ConflictError, giving the optimistic-concurrency guarantee the contract requires.
This backend is an event log only: it does not interpret res.Transaction, since projector view writes are backend-specific (the only TransactionGroup implementation today is DynamoDB's) and no PostgreSQL view store exists yet. Adding one later would extend this to write the view rows in the same transaction as the events, preserving atomicity.
func (*Repository) CommitStream ¶
func (repo *Repository) CommitStream( ctx context.Context, channel <-chan result.Result[evt.SerializedResult], ) []error
CommitStream commits each SerializedResult from the channel in its own transaction, collecting per-result errors without aborting the stream. The batch size is one result, which keeps each commit atomic and lets a single bad result fail in isolation.
func (*Repository) CommitWithSnapshot ¶
func (repo *Repository) CommitWithSnapshot( ctx context.Context, res evt.SerializedResult, entityType evt.EntityType, entityID evt.EntityID, payload []byte, currentSnapshot evt.EventSequence, ) error
CommitWithSnapshot commits the events and upserts the entity's durable snapshot in one transaction, so the snapshot is never observable without the events it summarizes.
func (*Repository) CompactBelow ¶
func (repo *Repository) CompactBelow( ctx context.Context, entityID evt.EntityID, throughSequence evt.EventSequence, ) (int, error)
CompactBelow deletes events for the entity whose sequence is in [1, throughSequence], but only after confirming a durable snapshot covers (>=) throughSequence. It implements evt.Compactor.
The snapshot row lives in a separate table and is never touched, so the "never delete the sk=0 snapshot" invariant holds structurally. A throughSequence < 1 is a no-op. When no covering snapshot exists nothing is deleted and ErrCompactionUncovered is returned.
func (*Repository) EnsureSchema ¶
func (repo *Repository) EnsureSchema(ctx context.Context) error
EnsureSchema creates the event-log and snapshot tables if they do not already exist. It is idempotent and safe to call on every startup; the integration suite calls it during setup. The Repository owns this DDL because the relational schema must stay in lockstep with the Go types that marshal into and out of it.
func (*Repository) GetEvents ¶
func (repo *Repository) GetEvents( ctx context.Context, entityID evt.EntityID, ) ([]evt.SerializedEvent, error)
GetEvents returns every event for an entity in ascending sequence order.
func (*Repository) GetLatestEvents ¶
func (repo *Repository) GetLatestEvents( ctx context.Context, entityID evt.EntityID, lastSequence evt.EventSequence, ) ([]evt.SerializedEvent, error)
GetLatestEvents returns the events for an entity whose sequence is greater than lastSequence, ascending. It is the path used to load the events after a snapshot.
func (*Repository) GetSnapshot ¶
func (repo *Repository) GetSnapshot( ctx context.Context, entityID evt.EntityID, ) (*evt.SerializedSnapshot, error)
GetSnapshot returns the entity's durable snapshot, or nil when none exists.
func (*Repository) StreamAllEvents ¶
func (repo *Repository) StreamAllEvents( ctx context.Context, filter evt.StreamFilter, ) <-chan result.Result[[]evt.SerializedEvent]
StreamAllEvents streams the event log as one batch per entity, narrowed by the StreamFilter's entity-type predicate (pushed into the WHERE clause). A zero filter streams every event.
func (*Repository) StreamEntities ¶
func (repo *Repository) StreamEntities( ctx context.Context, filter evt.StreamFilter, applyEvent func(context.Context, evt.SerializedEvent, evt.Entity) (evt.Entity, error), ) <-chan result.Result[evt.Entity]
StreamEntities streams each entity folded from its events via applyEvent, narrowed by the StreamFilter's entity-type predicate. A zero filter streams every entity. Each entity is reconstructed from its own contiguous run of events, so the result is correct regardless of how many entities the log holds.
func (*Repository) StreamEntitiesFromSnapshots ¶
func (repo *Repository) StreamEntitiesFromSnapshots( ctx context.Context, entityType evt.EntityType, seedEntity evt.SnapshotSeeder, applyEvent func(context.Context, evt.SerializedEvent, evt.Entity) (evt.Entity, error), ) <-chan result.Result[evt.Entity]
StreamEntitiesFromSnapshots streams completed entities, seeding each from its durable snapshot and applying only the events recorded after that snapshot. Streams with no snapshot fall back to full replay from sequence 1. entityType, when non-empty, restricts the rebuild to that type. It implements evt.SnapshotStreamer.
Each entity is reconstructed from its own partition (per-entity queries), so the result stays correct after compaction has removed events below a snapshot — the snapshot, not event 1, is the authoritative floor.
func (*Repository) StreamEntityHeads ¶
func (repo *Repository) StreamEntityHeads( ctx context.Context, entityType evt.EntityType, ) (map[evt.EntityID]evt.EventSequence, error)
StreamEntityHeads enumerates the distinct entities in the log and returns each entity's current head sequence. It implements evt.EntityHeadStreamer by materializing the streamed visitor into a map.
func (*Repository) StreamEntityHeadsFunc ¶
func (repo *Repository) StreamEntityHeadsFunc( ctx context.Context, entityType evt.EntityType, visit func(evt.EntityID, evt.EventSequence) error, ) error
StreamEntityHeadsFunc enumerates entity heads and invokes visit once per entity, paging the result cursor without accumulating the full set — the constant-memory change-detection primitive a SQL backend can offer (a streamed cursor over SELECT entity_id, MAX(sequence) …). It implements evt.EntityHeadVisitor. If visit returns an error, enumeration stops and returns it.