Files
ITWorx Pulse release export bd774932d5
Public source validation / validate (push) Failing after 3m8s
Publish ITWorx Pulse source
2026-09-03 02:09:19 +02:00

54 lines
1.6 KiB
Go

package onboarding
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
type StateStore struct {
Pool *pgxpool.Pool
}
func (s StateStore) Load(ctx context.Context) (State, error) {
if s.Pool == nil {
return State{}, errors.New("onboarding state store is not configured")
}
var raw []byte
if err := s.Pool.QueryRow(ctx, `SELECT value FROM system_settings WHERE key=$1`, StateKey).Scan(&raw); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return State{SchemaVersion: SchemaVersion, Step: "welcome"}, nil
}
return State{}, fmt.Errorf("load onboarding state: %w", err)
}
var state State
if err := json.Unmarshal(raw, &state); err != nil {
return State{}, fmt.Errorf("decode onboarding state: %w", err)
}
if state.SchemaVersion != SchemaVersion {
return State{}, fmt.Errorf("unsupported onboarding state schema version %d", state.SchemaVersion)
}
return state, nil
}
func (s StateStore) Save(ctx context.Context, state State) error {
if s.Pool == nil {
return errors.New("onboarding state store is not configured")
}
state.SchemaVersion = SchemaVersion
state.UpdatedAt = time.Now().UTC()
raw, err := json.Marshal(state)
if err != nil {
return fmt.Errorf("encode onboarding state: %w", err)
}
if _, err := s.Pool.Exec(ctx, `INSERT INTO system_settings (key,value,version) VALUES ($1,$2::jsonb,1) ON CONFLICT (key) DO UPDATE SET value=EXCLUDED.value,version=system_settings.version+1,updated_at=now()`, StateKey, raw); err != nil {
return fmt.Errorf("save onboarding state: %w", err)
}
return nil
}