Files
archie/modules/judgement/internal/store/store.go
T

72 lines
2.4 KiB
Go

// Package store holds the judgement module's SQL: every decision, with the
// action class it belongs to.
package store
import (
"context"
"database/sql"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
)
// Decision is one recorded decision. Body is the whole decision as JSON.
type Decision struct {
ID uuid.UUID `db:"id"`
OrgID string `db:"org_id"`
RunID uuid.UUID `db:"run_id"`
Key string `db:"key"`
Connector string `db:"connector"`
Action string `db:"action"`
TargetKind string `db:"target_kind"`
Environment string `db:"environment"`
Level string `db:"level"`
Body []byte `db:"body"`
// CreatedAt is set by the database and read only by the class history.
CreatedAt time.Time `db:"created_at"`
}
// Store is the judgement module's Postgres store.
type Store struct {
db *sqlx.DB
}
// New returns a store on db.
func New(db *sqlx.DB) *Store { return &Store{db: db} }
// Record stores d unless a decision with its key exists, and returns the
// decision that is kept.
func (s *Store) Record(ctx context.Context, d Decision) (Decision, error) {
var kept Decision
err := s.db.GetContext(ctx, &kept, `
INSERT INTO judgement.decisions
(id, org_id, run_id, key, connector, action, target_kind, environment, level, body)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
ON CONFLICT (org_id, key) DO NOTHING
RETURNING id, org_id, run_id, key, connector, action, target_kind, environment, level, body`,
d.ID, d.OrgID, d.RunID, d.Key, d.Connector, d.Action, d.TargetKind, d.Environment, d.Level, d.Body)
if errors.Is(err, sql.ErrNoRows) {
err = s.db.GetContext(ctx, &kept, `
SELECT id, org_id, run_id, key, connector, action, target_kind, environment, level, body
FROM judgement.decisions WHERE org_id = $1 AND key = $2`, d.OrgID, d.Key)
}
if err != nil {
return Decision{}, fmt.Errorf("record decision: %w", err)
}
return kept, nil
}
// ForRun returns a run's decisions in the order they were made.
func (s *Store) ForRun(ctx context.Context, orgID string, runID uuid.UUID) ([]Decision, error) {
var out []Decision
if err := s.db.SelectContext(ctx, &out, `
SELECT id, org_id, run_id, key, connector, action, target_kind, environment, level, body
FROM judgement.decisions WHERE org_id = $1 AND run_id = $2 ORDER BY created_at, id`, orgID, runID); err != nil {
return nil, fmt.Errorf("list decisions: %w", err)
}
return out, nil
}