package storage import ( "context" "database/sql" "errors" "fmt" "github.com/uptrace/bun" "git.kmalloc.org/squid/sonda/internal/usersettings" ) // UserSettingsRepo stores per-user settings. It implements usersettings.Store. type UserSettingsRepo struct{ db *bun.DB } // NewUserSettingsRepo builds a UserSettingsRepo. func NewUserSettingsRepo(db *bun.DB) *UserSettingsRepo { return &UserSettingsRepo{db: db} } // Get returns the user's settings: the defaults when no row exists yet. func (r *UserSettingsRepo) Get(ctx context.Context, userID int64) (usersettings.Settings, error) { return getUserSettings(ctx, r.db, userID) } type queryer interface { QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row } func getUserSettings(ctx context.Context, q queryer, userID int64) (usersettings.Settings, error) { var s usersettings.Settings err := q.QueryRowContext(ctx, `SELECT COALESCE(s.discover_from_listening, FALSE), COALESCE(s.radio_in_apps, FALSE) FROM users u LEFT JOIN user_settings s ON s.user_id = u.id WHERE u.id = ?`, userID). Scan(&s.DiscoverFromListening, &s.RadioInApps) if errors.Is(err, sql.ErrNoRows) { return usersettings.Settings{}, usersettings.ErrUserNotFound } if err != nil { return usersettings.Settings{}, fmt.Errorf("read user settings: %w", err) } return s, nil } // Update applies the patch in one transaction and returns the result. func (r *UserSettingsRepo) Update(ctx context.Context, userID int64, p usersettings.Patch) (usersettings.Settings, error) { var out usersettings.Settings err := r.db.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error { cur, err := getUserSettings(ctx, tx, userID) if err != nil { return err } // Each setting that the patch names is written on its own, so that the others keep what they have. for _, w := range []struct { column string value *bool into *bool }{ {"discover_from_listening", p.DiscoverFromListening, &cur.DiscoverFromListening}, {"radio_in_apps", p.RadioInApps, &cur.RadioInApps}, } { if w.value == nil { continue } *w.into = *w.value if _, err := tx.ExecContext(ctx, `INSERT INTO user_settings (user_id, `+w.column+`) VALUES (?, ?) ON CONFLICT (user_id) DO UPDATE SET `+w.column+` = excluded.`+w.column, userID, *w.value); err != nil { if isForeignKeyViolation(err) { return usersettings.ErrUserNotFound // deleted between the read and the write } return fmt.Errorf("write user settings: %w", err) } } out = cur return nil }) return out, err }