// Package store holds the drafts module's SQL. package store import ( "context" "database/sql" "encoding/json/jsontext" "errors" "fmt" "time" "github.com/google/uuid" "github.com/jackc/pgx/v5/pgconn" "github.com/jmoiron/sqlx" ) // ErrNotFound means no such draft. var ErrNotFound = errors.New("no such draft") // ErrTaken indicates that another draft already uses the name. var ErrTaken = errors.New("name already used by another draft") // Draft is one stored draft. type Draft struct { ID uuid.UUID `db:"id"` OrgID string `db:"org_id"` GroupID uuid.UUID `db:"group_id"` Name string `db:"name"` Source string `db:"source"` EventType string `db:"event_type"` Filter jsontext.Value `db:"filter"` Document string `db:"document"` PolicyKind string `db:"policy_kind"` Policy string `db:"policy"` DryRunID uuid.NullUUID `db:"dry_run_id"` DryEventID uuid.NullUUID `db:"dry_event_id"` // InstalledVersion is recorded before the trigger is saved so a retry // can distinguish an earlier installation from a workflow name conflict. InstalledVersion sql.NullInt32 `db:"installed_version"` PublishedAt sql.NullTime `db:"published_at"` CreatedAt time.Time `db:"created_at"` UpdatedAt time.Time `db:"updated_at"` } const columns = `id, org_id, group_id, name, source, event_type, filter, document, policy_kind, policy, dry_run_id, dry_event_id, installed_version, published_at, created_at, updated_at` // Store is the drafts 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} } // Create inserts a draft or returns the existing draft for the group. func (s *Store) Create(ctx context.Context, d Draft) (Draft, error) { _, err := s.db.ExecContext(ctx, ` INSERT INTO drafts.drafts (id, org_id, group_id, name, source, event_type, filter, document, policy_kind, policy) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) ON CONFLICT (org_id, group_id) DO NOTHING`, d.ID, d.OrgID, d.GroupID, d.Name, d.Source, d.EventType, d.Filter, d.Document, d.PolicyKind, d.Policy) if err != nil { return Draft{}, fmt.Errorf("create draft: %w", err) } return s.ByGroup(ctx, d.OrgID, d.GroupID) } // ByGroup returns a group's draft. func (s *Store) ByGroup(ctx context.Context, orgID string, groupID uuid.UUID) (Draft, error) { return s.one(ctx, `WHERE org_id = $1 AND group_id = $2`, orgID, groupID) } // ByID returns one draft. func (s *Store) ByID(ctx context.Context, orgID string, id uuid.UUID) (Draft, error) { return s.one(ctx, `WHERE org_id = $1 AND id = $2`, orgID, id) } func (s *Store) one(ctx context.Context, where string, args ...any) (Draft, error) { var d Draft err := s.db.GetContext(ctx, &d, `SELECT `+columns+` FROM drafts.drafts `+where, args...) if errors.Is(err, sql.ErrNoRows) { return Draft{}, ErrNotFound } if err != nil { return Draft{}, fmt.Errorf("read draft: %w", err) } return d, nil } // List returns an organisation's drafts, newest first. func (s *Store) List(ctx context.Context, orgID string) ([]Draft, error) { var out []Draft if err := s.db.SelectContext(ctx, &out, ` SELECT `+columns+` FROM drafts.drafts WHERE org_id = $1 ORDER BY created_at DESC LIMIT 200`, orgID); err != nil { return nil, fmt.Errorf("list drafts: %w", err) } return out, nil } // Edit updates an unpublished draft and clears its dry-run references because // the previous run no longer represents the current draft. func (s *Store) Edit(ctx context.Context, orgID string, id uuid.UUID, name, document, policyKind, policy string) error { res, err := s.db.ExecContext(ctx, ` UPDATE drafts.drafts SET name = $3, document = $4, policy_kind = $5, policy = $6, dry_run_id = NULL, dry_event_id = NULL, updated_at = now() WHERE org_id = $1 AND id = $2 AND published_at IS NULL`, orgID, id, name, document, policyKind, policy) if err != nil { if isUnique(err) { return ErrTaken } return fmt.Errorf("edit draft: %w", err) } if n, _ := res.RowsAffected(); n == 0 { return ErrNotFound } return nil } // SetDryRun records the latest dry run and the event it replayed. func (s *Store) SetDryRun(ctx context.Context, orgID string, id, runID, eventID uuid.UUID) error { if _, err := s.db.ExecContext(ctx, ` UPDATE drafts.drafts SET dry_run_id = $3, dry_event_id = $4, updated_at = now() WHERE org_id = $1 AND id = $2`, orgID, id, runID, eventID); err != nil { return fmt.Errorf("record dry run: %w", err) } return nil } // MarkInstalled records the workflow version installed during publication. func (s *Store) MarkInstalled(ctx context.Context, orgID string, id uuid.UUID, version int) error { if _, err := s.db.ExecContext(ctx, ` UPDATE drafts.drafts SET installed_version = $3, updated_at = now() WHERE org_id = $1 AND id = $2`, orgID, id, version); err != nil { return fmt.Errorf("record installed version: %w", err) } return nil } // MarkPublished records the publication time without overwriting it on retry. func (s *Store) MarkPublished(ctx context.Context, orgID string, id uuid.UUID) error { if _, err := s.db.ExecContext(ctx, ` UPDATE drafts.drafts SET published_at = COALESCE(published_at, now()), updated_at = now() WHERE org_id = $1 AND id = $2`, orgID, id); err != nil { return fmt.Errorf("mark draft published: %w", err) } return nil } func isUnique(err error) bool { var pgerr *pgconn.PgError return errors.As(err, &pgerr) && pgerr.Code == "23505" }