summaryrefslogtreecommitdiff
path: root/player-server/internal/repository/progress_transaction.go
blob: b16018f67b4c8f33a95972e2af48682b3555ef29 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package repository

import (
	"context"
	"fmt"

	"codeberg.org/snonux/player/internal/model"
)

// WithProgressTransaction runs progress updates in one SQLite transaction.
func (s *SQLite) WithProgressTransaction(ctx context.Context, fn func(ProgressUpdateStore) error) error {
	tx, err := s.db.BeginTx(ctx, nil)
	if err != nil {
		return fmt.Errorf("begin progress transaction: %w", err)
	}

	txStore := &progressTxStore{tx: tx}
	if err := fn(txStore); err != nil {
		if rollbackErr := tx.Rollback(); rollbackErr != nil {
			return fmt.Errorf("rollback progress transaction after %w: %v", err, rollbackErr)
		}
		return err
	}
	if err := tx.Commit(); err != nil {
		return fmt.Errorf("commit progress transaction: %w", err)
	}
	return nil
}

type progressTxStore struct {
	tx sqlProgressTx
}

type sqlProgressTx interface {
	sqlExecer
	sqlQueryRower
}

func (s *progressTxStore) UpsertProgress(ctx context.Context, progress *model.PlaybackProgress) error {
	return upsertProgress(ctx, s.tx, progress)
}

func (s *progressTxStore) GetProgress(ctx context.Context, userID, mediaID int64) (*model.PlaybackProgress, error) {
	return getProgress(ctx, s.tx, userID, mediaID)
}

func (s *progressTxStore) GetAccumulator(ctx context.Context, sessionID string, mediaID int64) (*model.PlaybackAccumulator, error) {
	return getAccumulator(ctx, s.tx, sessionID, mediaID)
}

func (s *progressTxStore) UpsertAccumulator(ctx context.Context, acc *model.PlaybackAccumulator) error {
	return upsertAccumulator(ctx, s.tx, acc)
}

func (s *progressTxStore) IncrementPlayCount(ctx context.Context, id int64) error {
	return incrementPlayCount(ctx, s.tx, id)
}

var _ ProgressUpdateStore = (*progressTxStore)(nil)