Migrating hosting from Codeberg to git.kmalloc.org. Renames the module path in go.mod, every internal import, and the OCI image source label in the Dockerfile. Build and full test suite verified green after the rename.
60 lines
1.9 KiB
Go
60 lines
1.9 KiB
Go
package storage
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
|
|
"github.com/uptrace/bun"
|
|
|
|
"git.kmalloc.org/squid/sonda/internal/spotifyimport"
|
|
)
|
|
|
|
type outsidePlayRow struct {
|
|
bun.BaseModel `bun:"table:outside_plays"`
|
|
|
|
UserID int64 `bun:"user_id,pk"`
|
|
IdempotencyKey string `bun:"idempotency_key,pk"`
|
|
Artist string `bun:"artist,notnull"`
|
|
ArtistKey string `bun:"artist_key,notnull"`
|
|
PlayedAt int64 `bun:"played_at,notnull"`
|
|
}
|
|
|
|
// OutsidePlayRepo keeps the plays of artists a person has no music of. It implements spotifyimport.Outside.
|
|
type OutsidePlayRepo struct{ db *bun.DB }
|
|
|
|
// NewOutsidePlayRepo builds an OutsidePlayRepo.
|
|
func NewOutsidePlayRepo(db *bun.DB) *OutsidePlayRepo { return &OutsidePlayRepo{db: db} }
|
|
|
|
// outsideChunk is how many plays one statement inserts: five columns each.
|
|
const outsideChunk = 500
|
|
|
|
// RecordOutside keeps the plays of one person in one transaction and says how many were new. A play whose key is
|
|
// already there is skipped, also one that is twice in the batch.
|
|
func (r *OutsidePlayRepo) RecordOutside(ctx context.Context, userID int64, plays []spotifyimport.OutsidePlay) (int, error) {
|
|
created := 0
|
|
err := r.db.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error {
|
|
for start := 0; start < len(plays); start += outsideChunk {
|
|
end := min(start+outsideChunk, len(plays))
|
|
rows := make([]outsidePlayRow, 0, end-start)
|
|
for _, p := range plays[start:end] {
|
|
rows = append(rows, outsidePlayRow{
|
|
UserID: userID, IdempotencyKey: p.Key, Artist: p.Artist, ArtistKey: SearchKey(p.Artist), PlayedAt: p.PlayedAt.Unix(),
|
|
})
|
|
}
|
|
res, err := tx.NewInsert().Model(&rows).On("CONFLICT (user_id, idempotency_key) DO NOTHING").Exec(ctx)
|
|
if err != nil {
|
|
return fmt.Errorf("insert outside plays: %w", err)
|
|
}
|
|
n, err := res.RowsAffected()
|
|
if err != nil {
|
|
return fmt.Errorf("rows affected: %w", err)
|
|
}
|
|
created += int(n)
|
|
}
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
return created, nil
|
|
}
|