Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.
Stop a duplicate upstream name from taking over another exercise's row (#208)
Carter6cc53ac12f90
diff --git a/backend/stores/exercise.go b/backend/stores/exercise.goindex a5bdfe1..17f37f3 100644--- a/backend/stores/exercise.go+++ b/backend/stores/exercise.go@@ -13,6 +13,7 @@ import ("github.com/Cawlumm/lyftr-backend/models""github.com/Cawlumm/lyftr-backend/oedb"+ "github.com/Cawlumm/lyftr-backend/utils")// ExerciseStore owns all SQL for the (global, read-only) exercises catalog, and@@ -204,6 +205,11 @@ func (s *ExerciseStore) Count() (int, error) {// exercise_translations row instead, so one user's Spanish search never rewrites// what an English reader sees. locale is the language that was asked for, and the// language the returned rows are shown in.+//+// Name matching only adopts a row that no upstream id owns yet. An upstream+// exercise whose name is already owned by another id, or that arrives translated+// with no English row to attach to, is skipped and left out of the result, because oedb names are not unique and re-pointing the row would re-point+// every workout that references it.func (s *ExerciseStore) Materialize(items []oedb.Exercise, imageBase, locale string) ([]models.Exercise, error) {if len(items) == 0 {return []models.Exercise{}, nil@@ -239,7 +245,8 @@ func (s *ExerciseStore) Materialize(items []oedb.Exercise, imageBase, locale strdescription = COALESCE(?, description),image_url = excluded.image_url,oedb_id = excluded.oedb_id,- slug = excluded.slug`)+ slug = excluded.slug+ WHERE exercises.oedb_id IS NULL`)if err != nil {return nil, err}@@ -269,10 +276,21 @@ func (s *ExerciseStore) Materialize(items []oedb.Exercise, imageBase, locale strdescEnglish = desc}- res, err := byOedbID.Exec(+ args := []any{nameEnglish, it.MuscleGroup, string(secondaryJSON), it.Category,it.Equipment, descEnglish, it.ImageURL(imageBase), it.Slug, it.ID,- )+ }+ res, err := byOedbID.Exec(args...)+ if utils.IsUniqueViolation(err) {+ // Moving the name would mean merging two rows that workouts point at.+ holderID, holderOedb, herr := nameHolder(tx, name)+ if herr != nil {+ return nil, herr+ }+ log.Printf("exercises: upstream %s renamed to %q, already held by local exercise %d (oedb_id %q); keeping its current name", it.ID, name, holderID, holderOedb)+ args[0] = nil+ res, err = byOedbID.Exec(args...)+ }if err != nil {return nil, err}@@ -282,19 +300,36 @@ func (s *ExerciseStore) Materialize(items []oedb.Exercise, imageBase, locale str}if n == 0 {if !nameEN {- return nil, fmt.Errorf("%w: %s", errNoEnglishBase, it.ID)+ // No English row to hang the translation on, and none to invent: either+ // the English read skipped this exercise (its name is held by another+ // id) or oedb did not return it. Leave it out; the rest of the batch stands.+ log.Printf("exercises: skipping upstream %s: no English base row for its %q translation", it.ID, locale)+ continue}baseDesc := ""if descEN {baseDesc = desc}- if _, err := byName.Exec(+ nameRes, err := byName.Exec(name, it.MuscleGroup, string(secondaryJSON), it.Category,it.Equipment, baseDesc, it.ImageURL(imageBase), it.ID, it.Slug,descEnglish,- ); err != nil {+ )+ if err != nil {return nil, err}+ adopted, err := nameRes.RowsAffected()+ if err != nil {+ return nil, err+ }+ if adopted == 0 {+ holderID, holderOedb, herr := nameHolder(tx, name)+ if herr != nil {+ return nil, herr+ }+ log.Printf("exercises: skipping upstream %s %q: name already held by local exercise %d (oedb_id %q)", it.ID, name, holderID, holderOedb)+ continue+ }}if locale != defaultLocale {@@ -317,11 +352,14 @@ func (s *ExerciseStore) Materialize(items []oedb.Exercise, imageBase, locale strreturn out, nil}-// errNoEnglishBase is returned when oedb served an exercise's name only in another-// language and no local row exists to hold the English one. Inserting the translated-// name as the base would show it to every English reader, so the whole batch rolls-// back and the caller falls back to the local snapshot.-var errNoEnglishBase = errors.New("exercises: no English base row for a translated exercise")+// nameHolder reports which local row holds name, for the log line when an upstream exercise cannot take it.+func nameHolder(tx *sql.Tx, name string) (id int64, oedbID string, err error) {+ err = tx.QueryRow(`SELECT id, COALESCE(oedb_id, '') FROM exercises WHERE name = ?`, name).Scan(&id, &oedbID)+ if errors.Is(err, sql.ErrNoRows) {+ return 0, "", nil+ }+ return+}// servedInEnglish reports whether a field oedb served is the English text. An empty// locale is an oedb that predates name_locale, which only ever served English.diff --git a/backend/stores/exercise_locale_test.go b/backend/stores/exercise_locale_test.goindex e454598..b86004c 100644--- a/backend/stores/exercise_locale_test.go+++ b/backend/stores/exercise_locale_test.go@@ -217,32 +217,39 @@ func TestMaterialize_OnlyReplacesItsOwnLocales(t *testing.T) {}}-func TestMaterialize_RefusesNonEnglishBaseInsert(t *testing.T) {+func TestMaterialize_SkipsTranslatedItemWithNoEnglishBase(t *testing.T) {conn := testDB(t)s := NewExerciseStore(conn)- _, err := s.Materialize([]oedb.Exercise{spanishSquat()}, imageBase, "es")- if err == nil {- t.Fatal("a translated item with no English base row was accepted")+ out, err := s.Materialize([]oedb.Exercise{spanishSquat()}, imageBase, "es")+ if err != nil {+ t.Fatalf("Materialize: %v", err)+ }+ if len(out) != 0 {+ t.Errorf("returned %d rows, want the translated item left out", len(out))}if n := countRows(t, conn, `SELECT COUNT(*) FROM exercises`); n != 0 {- t.Errorf("exercises = %d, want nothing written", n)+ t.Errorf("exercises = %d, want no English base invented from Spanish text", n)}if n := countRows(t, conn, `SELECT COUNT(*) FROM exercise_translations`); n != 0 {t.Errorf("translations = %d, want nothing written", n)}}-func TestMaterialize_RefusalRollsBackTheWholeBatch(t *testing.T) {+func TestMaterialize_SkippedTranslatedItemKeepsTheRestOfTheBatch(t *testing.T) {conn := testDB(t)s := NewExerciseStore(conn)other := served("uuid-2", "Deadlift", "en", []string{"Lift."}, "en")- if _, err := s.Materialize([]oedb.Exercise{other, spanishSquat()}, imageBase, "es"); err == nil {- t.Fatal("expected the batch to fail")+ out, err := s.Materialize([]oedb.Exercise{other, spanishSquat()}, imageBase, "es")+ if err != nil {+ t.Fatalf("Materialize: %v", err)}- if n := countRows(t, conn, `SELECT COUNT(*) FROM exercises`); n != 0 {- t.Errorf("exercises = %d, want the English item rolled back with the batch", n)+ if len(out) != 1 || out[0].Name != "Deadlift" {+ t.Errorf("returned %+v, want only Deadlift", out)+ }+ if n := countRows(t, conn, `SELECT COUNT(*) FROM exercises`); n != 1 {+ t.Errorf("exercises = %d, want 1", n)}}diff --git a/backend/stores/exercise_test.go b/backend/stores/exercise_test.goindex feab29d..67256a0 100644--- a/backend/stores/exercise_test.go+++ b/backend/stores/exercise_test.go@@ -9,6 +9,7 @@ import ("math/rand""net/http""net/http/httptest"+ "slices""strconv""strings""sync/atomic"@@ -403,3 +404,239 @@ func TestList_LocalFallbackPages(t *testing.T) {t.Errorf("page 3 starts at %q, want Exercise 20", page3[0].Name)}}++func ownerOf(t *testing.T, conn *sql.DB, id int64) string {+ t.Helper()+ var o sql.NullString+ if err := conn.QueryRow(`SELECT oedb_id FROM exercises WHERE id = ?`, id).Scan(&o); err != nil {+ t.Fatalf("owner of %d: %v", id, err)+ }+ return o.String+}++// oedb names are not unique. A second upstream id with a name another id already+// owns must not take that row over: every workout pointing at it would silently+// point at a different exercise.+func TestMaterialize_DuplicateNameDoesNotTakeOverOwnedRow(t *testing.T) {+ conn := testDB(t)+ s := NewExerciseStore(conn)++ first, err := s.Materialize([]oedb.Exercise{catalogExercise("uuid-A", "Squat")}, imageBase, "en")+ if err != nil || len(first) != 1 {+ t.Fatalf("first: %v %v", first, err)+ }+ aID := first[0].ID+ for _, q := range []string{+ `INSERT INTO users (id, email, password_hash) VALUES (1, '[email protected]', 'x')`,+ `INSERT INTO workouts (id, user_id, name) VALUES (1, 1, 'W')`,+ } {+ if _, err := conn.Exec(q); err != nil {+ t.Fatalf("seed: %v", err)+ }+ }+ if _, err := conn.Exec(`INSERT INTO workout_exercises (workout_id, exercise_id, order_index) VALUES (1, ?, 0)`, aID); err != nil {+ t.Fatalf("seed workout_exercise: %v", err)+ }++ out, err := s.Materialize([]oedb.Exercise{catalogExercise("uuid-B", "Squat")}, imageBase, "en")+ if err != nil {+ t.Fatalf("duplicate: %v", err)+ }+ if len(out) != 0 {+ t.Errorf("skipped duplicate returned %d rows, want 0", len(out))+ }+ if n := countRows(t, conn, `SELECT COUNT(*) FROM exercises`); n != 1 {+ t.Errorf("exercises = %d, want 1", n)+ }+ if got := ownerOf(t, conn, aID); got != "uuid-A" {+ t.Errorf("owner = %q, want uuid-A", got)+ }+ if n := countRows(t, conn, `SELECT COUNT(*) FROM exercises WHERE oedb_id = 'uuid-B'`); n != 0 {+ t.Errorf("uuid-B has %d rows, want 0", n)+ }+ var joined string+ if err := conn.QueryRow(`SELECT e.oedb_id FROM workout_exercises we JOIN exercises e ON e.id = we.exercise_id`).Scan(&joined); err != nil || joined != "uuid-A" {+ t.Errorf("workout points at %q (%v), want uuid-A", joined, err)+ }++ out, err = s.Materialize([]oedb.Exercise{catalogExercise("uuid-A", "Squat"), catalogExercise("uuid-B", "Squat")}, imageBase, "en")+ if err != nil {+ t.Fatalf("both: %v", err)+ }+ if got := ownerOf(t, conn, aID); got != "uuid-A" {+ t.Errorf("owner after both = %q, want uuid-A", got)+ }+ if len(out) != 1 || out[0].ID != aID {+ t.Errorf("out = %+v, want only local id %d", out, aID)+ }+}++func TestMaterialize_DuplicateInBatchKeepsTheRest(t *testing.T) {+ for _, locale := range []string{"en", "es"} {+ t.Run(locale, func(t *testing.T) {+ conn := testDB(t)+ s := NewExerciseStore(conn)+ mk := func(id, name string) oedb.Exercise {+ return served(id, name, "en", []string{"Step."}, "en")+ }+ out, err := s.Materialize([]oedb.Exercise{+ mk("uuid-A", "Squat"), mk("uuid-C", "Deadlift"), mk("uuid-B", "Squat"), mk("uuid-D", "Row"),+ }, imageBase, locale)+ if err != nil {+ t.Fatalf("Materialize: %v", err)+ }+ if len(out) != 3 {+ t.Fatalf("out = %d rows, want 3", len(out))+ }+ for i, want := range []string{"Squat", "Deadlift", "Row"} {+ if out[i].Name != want {+ t.Errorf("out[%d] = %q, want %q", i, out[i].Name, want)+ }+ }+ if n := countRows(t, conn, `SELECT COUNT(*) FROM exercises`); n != 3 {+ t.Errorf("exercises = %d, want 3", n)+ }+ if n := countRows(t, conn, `SELECT COUNT(*) FROM exercises WHERE oedb_id = 'uuid-A' AND name = 'Squat'`); n != 1 {+ t.Errorf("uuid-A does not own Squat")+ }+ if n := countRows(t, conn, `SELECT COUNT(*) FROM exercises WHERE oedb_id = 'uuid-B'`); n != 0 {+ t.Errorf("uuid-B has a row")+ }+ })+ }+}++func TestMaterialize_LegacyAdoptionThenDuplicateIsSkipped(t *testing.T) {+ conn := testDB(t)+ s := NewExerciseStore(conn)+ res, err := conn.Exec(`INSERT INTO exercises (name, muscle_group) VALUES ('Squat', 'legs')`)+ if err != nil {+ t.Fatalf("seed: %v", err)+ }+ legacyID, _ := res.LastInsertId()++ out, err := s.Materialize([]oedb.Exercise{catalogExercise("uuid-A", "Squat"), catalogExercise("uuid-B", "Squat")}, imageBase, "en")+ if err != nil {+ t.Fatalf("Materialize: %v", err)+ }+ if got := ownerOf(t, conn, legacyID); got != "uuid-A" {+ t.Errorf("legacy owner = %q, want uuid-A", got)+ }+ if len(out) != 1 || out[0].ID != legacyID {+ t.Errorf("out = %+v, want only legacy id %d", out, legacyID)+ }+ if n := countRows(t, conn, `SELECT COUNT(*) FROM exercises`); n != 1 {+ t.Errorf("exercises = %d, want 1", n)+ }+}++// An upstream rename onto a name another row holds cannot move the name without+// merging two rows workouts point at, so the row keeps its name and takes the rest.+func TestMaterialize_RenameOntoHeldNameKeepsCurrentName(t *testing.T) {+ conn := testDB(t)+ s := NewExerciseStore(conn)+ if _, err := s.Materialize([]oedb.Exercise{catalogExercise("uuid-A", "Barbell Squat"), catalogExercise("uuid-B", "Squat")}, imageBase, "en"); err != nil {+ t.Fatalf("seed: %v", err)+ }+ var aID int64+ if err := conn.QueryRow(`SELECT id FROM exercises WHERE oedb_id = 'uuid-A'`).Scan(&aID); err != nil {+ t.Fatalf("a id: %v", err)+ }+ if _, err := conn.Exec(`INSERT INTO exercises (name) VALUES ('Bench Press')`); err != nil {+ t.Fatalf("legacy: %v", err)+ }++ renamed := catalogExercise("uuid-A", "Squat")+ renamed.MuscleGroup = "quadriceps"+ out, err := s.Materialize([]oedb.Exercise{renamed, catalogExercise("uuid-C", "Lunge")}, imageBase, "en")+ if err != nil {+ t.Fatalf("Materialize: %v", err)+ }+ if len(out) != 2 || out[0].ID != aID {+ t.Errorf("out = %+v, want A then C", out)+ }+ var name, muscle string+ if err := conn.QueryRow(`SELECT name, muscle_group FROM exercises WHERE id = ?`, aID).Scan(&name, &muscle); err != nil {+ t.Fatalf("read a: %v", err)+ }+ if name != "Barbell Squat" || muscle != "quadriceps" {+ t.Errorf("A = %q/%q, want Barbell Squat/quadriceps", name, muscle)+ }+ if n := countRows(t, conn, `SELECT COUNT(*) FROM exercises WHERE name = 'Squat' AND oedb_id = 'uuid-B'`); n != 1 {+ t.Errorf("B lost its row")+ }+ if n := countRows(t, conn, `SELECT COUNT(*) FROM exercises WHERE oedb_id = 'uuid-C'`); n != 1 {+ t.Errorf("C not inserted")+ }++ onto := catalogExercise("uuid-A", "Bench Press")+ if _, err := s.Materialize([]oedb.Exercise{onto}, imageBase, "en"); err != nil {+ t.Fatalf("rename onto legacy: %v", err)+ }+ if err := conn.QueryRow(`SELECT name FROM exercises WHERE id = ?`, aID).Scan(&name); err != nil || name != "Barbell Squat" {+ t.Errorf("A name = %q (%v), want Barbell Squat", name, err)+ }+ if n := countRows(t, conn, `SELECT COUNT(*) FROM exercises WHERE name = 'Bench Press' AND oedb_id IS NULL`); n != 1 {+ t.Errorf("legacy Bench Press was adopted")+ }+}++// idx_exercises_name is BINARY, so names differing in case are different names.+func TestMaterialize_NameOwnershipFollowsIndexCollation(t *testing.T) {+ conn := testDB(t)+ s := NewExerciseStore(conn)+ out, err := s.Materialize([]oedb.Exercise{catalogExercise("uuid-A", "Squat"), catalogExercise("uuid-B", "squat")}, imageBase, "en")+ if err != nil {+ t.Fatalf("Materialize: %v", err)+ }+ if len(out) != 2 {+ t.Errorf("out = %d rows, want 2", len(out))+ }+ if n := countRows(t, conn, `SELECT COUNT(*) FROM exercises WHERE oedb_id IN ('uuid-A', 'uuid-B')`); n != 2 {+ t.Errorf("owned rows = %d, want 2", n)+ }+}++// A duplicate-named upstream exercise must cost a non-English reader only itself.+// The English read skips it (another id owns the name), so the localized read finds+// no base row for it; that used to roll back the whole page.+func TestSearch_DuplicateNameInSpanishPageKeepsTheOtherResults(t *testing.T) {+ english := []oedb.Exercise{+ served("uuid-b", "Squat", "en", []string{"Stand."}, "en"),+ served("uuid-c", "Deadlift", "en", []string{"Lift."}, "en"),+ }+ spanish := []oedb.Exercise{+ served("uuid-b", "Sentadilla", "es", []string{"Ponte."}, "es"),+ served("uuid-c", "Peso muerto", "es", []string{"Levanta."}, "es"),+ }+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ items := english+ if r.URL.Query().Get("locale") == "es" {+ items = spanish+ }+ json.NewEncoder(w).Encode(map[string]any{"exercises": items, "total": len(items)})+ }))+ defer srv.Close()++ conn := testDB(t)+ s := NewExerciseStore(conn)+ s.UseCatalog(oedb.New(srv.URL, "test"))+ materialize(t, s, "en", served("uuid-a", "Squat", "en", []string{"Stand."}, "en"))++ out, err := s.Search(context.Background(), ExerciseFilter{Query: "e", Locale: "es", Limit: 50})+ if err != nil {+ t.Fatalf("Search: %v", err)+ }+ var names []string+ for _, e := range out {+ names = append(names, e.Name)+ }+ if !slices.Contains(names, "Peso muerto") {+ t.Errorf("results = %v, want the unrelated Spanish result kept", names)+ }+ var oedbID string+ conn.QueryRow(`SELECT oedb_id FROM exercises WHERE name = 'Squat'`).Scan(&oedbID)+ if oedbID != "uuid-a" {+ t.Errorf("Squat oedb_id = %q, want uuid-a untouched", oedbID)+ }+}