Files
x/database/actor.go
Colin Henry 54aae5f242
All checks were successful
Go / build (1.23) (push) Successful in 3m51s
big updates: tests, bug fixed, documentation. oh my
2026-01-03 15:53:50 -08:00

40 lines
1.2 KiB
Go

// Package database provides an actor pattern implementation for sequential database operations.
package database
import (
"context"
"database/sql"
"git.sdf.org/jchenry/x"
)
// Func is a function type that performs a database operation.
// It receives a context and database connection, returning an error if the operation fails.
type Func func(ctx context.Context, db *sql.DB) error
// Actor provides a sequential executor for database operations via a channel.
// Operations sent to ActionChan are executed sequentially in the order received.
type Actor struct {
// DB is the database connection used by all operations
DB *sql.DB
// ActionChan receives database operations to execute sequentially
ActionChan chan Func
}
// Run starts the actor's event loop, processing database operations from ActionChan.
// It blocks until ctx is canceled or an operation returns an error.
// The context must not be nil or this function will panic.
func (a *Actor) Run(ctx context.Context) error {
x.Assert(ctx != nil, "Actor.Run: context cannot be nil")
for {
select {
case f := <-a.ActionChan:
if err := f(ctx, a.DB); err != nil {
return err
}
case <-ctx.Done():
return ctx.Err()
}
}
}