From 9a4fec8bf31f7cf6b9afb56819248dbd2bf4d8e6 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sat, 18 Apr 2026 18:19:31 +0200 Subject: [PATCH] Refactor the workout session provider The logs are read in the session repository, the logs one is only used for CRUD operations --- lib/database/powersync/database.g.dart | 26 ++++---- lib/database/powersync/tables/routines.dart | 4 +- lib/helpers/errors.dart | 2 +- .../trophies/user_trophy_context_data.dart | 4 +- .../trophies/user_trophy_context_data.g.dart | 4 +- lib/models/workouts/log.dart | 4 +- lib/providers/routines.dart | 10 ++- lib/providers/routines.g.dart | 6 +- lib/providers/workout_logs.dart | 34 ++++------ lib/providers/workout_logs.g.dart | 54 --------------- lib/providers/workout_logs_repository.dart | 66 ++----------------- lib/providers/workout_session_repository.dart | 58 +++++++++++++--- lib/widgets/routines/gym_mode/log_page.dart | 2 +- lib/widgets/routines/gym_mode/summary.dart | 2 +- .../routines/logs/day_logs_container.dart | 2 +- .../routine_logs_screen_test.mocks.dart | 8 --- 16 files changed, 100 insertions(+), 186 deletions(-) delete mode 100644 lib/providers/workout_logs.g.dart diff --git a/lib/database/powersync/database.g.dart b/lib/database/powersync/database.g.dart index 33b207f08..b466a7758 100644 --- a/lib/database/powersync/database.g.dart +++ b/lib/database/powersync/database.g.dart @@ -3737,11 +3737,11 @@ class $WorkoutLogTableTable extends WorkoutLogTable with TableInfo<$WorkoutLogTa 'sessionId', ); @override - late final GeneratedColumn sessionId = GeneratedColumn( + late final GeneratedColumn sessionId = GeneratedColumn( 'session_id', aliasedName, true, - type: DriftSqlType.int, + type: DriftSqlType.string, requiredDuringInsert: false, ); static const VerificationMeta _iterationMeta = const VerificationMeta( @@ -4078,7 +4078,7 @@ class WorkoutLogTableCompanion extends UpdateCompanion { final Value id; final Value exerciseId; final Value routineId; - final Value sessionId; + final Value sessionId; final Value iteration; final Value slotEntryId; final Value rir; @@ -4133,7 +4133,7 @@ class WorkoutLogTableCompanion extends UpdateCompanion { Expression? id, Expression? exerciseId, Expression? routineId, - Expression? sessionId, + Expression? sessionId, Expression? iteration, Expression? slotEntryId, Expression? rir, @@ -4171,7 +4171,7 @@ class WorkoutLogTableCompanion extends UpdateCompanion { Value? id, Value? exerciseId, Value? routineId, - Value? sessionId, + Value? sessionId, Value? iteration, Value? slotEntryId, Value? rir, @@ -4218,7 +4218,7 @@ class WorkoutLogTableCompanion extends UpdateCompanion { map['routine_id'] = Variable(routineId.value); } if (sessionId.present) { - map['session_id'] = Variable(sessionId.value); + map['session_id'] = Variable(sessionId.value); } if (iteration.present) { map['iteration'] = Variable(iteration.value); @@ -11690,7 +11690,7 @@ typedef $$WorkoutLogTableTableCreateCompanionBuilder = Value id, required int exerciseId, required int routineId, - Value sessionId, + Value sessionId, Value iteration, Value slotEntryId, Value rir, @@ -11709,7 +11709,7 @@ typedef $$WorkoutLogTableTableUpdateCompanionBuilder = Value id, Value exerciseId, Value routineId, - Value sessionId, + Value sessionId, Value iteration, Value slotEntryId, Value rir, @@ -11748,7 +11748,7 @@ class $$WorkoutLogTableTableFilterComposer builder: (column) => ColumnFilters(column), ); - ColumnFilters get sessionId => $composableBuilder( + ColumnFilters get sessionId => $composableBuilder( column: $table.sessionId, builder: (column) => ColumnFilters(column), ); @@ -11833,7 +11833,7 @@ class $$WorkoutLogTableTableOrderingComposer builder: (column) => ColumnOrderings(column), ); - ColumnOrderings get sessionId => $composableBuilder( + ColumnOrderings get sessionId => $composableBuilder( column: $table.sessionId, builder: (column) => ColumnOrderings(column), ); @@ -11914,7 +11914,7 @@ class $$WorkoutLogTableTableAnnotationComposer GeneratedColumn get routineId => $composableBuilder(column: $table.routineId, builder: (column) => column); - GeneratedColumn get sessionId => + GeneratedColumn get sessionId => $composableBuilder(column: $table.sessionId, builder: (column) => column); GeneratedColumn get iteration => @@ -11999,7 +11999,7 @@ class $$WorkoutLogTableTableTableManager Value id = const Value.absent(), Value exerciseId = const Value.absent(), Value routineId = const Value.absent(), - Value sessionId = const Value.absent(), + Value sessionId = const Value.absent(), Value iteration = const Value.absent(), Value slotEntryId = const Value.absent(), Value rir = const Value.absent(), @@ -12035,7 +12035,7 @@ class $$WorkoutLogTableTableTableManager Value id = const Value.absent(), required int exerciseId, required int routineId, - Value sessionId = const Value.absent(), + Value sessionId = const Value.absent(), Value iteration = const Value.absent(), Value slotEntryId = const Value.absent(), Value rir = const Value.absent(), diff --git a/lib/database/powersync/tables/routines.dart b/lib/database/powersync/tables/routines.dart index 0f8c235d4..a74d7d24d 100644 --- a/lib/database/powersync/tables/routines.dart +++ b/lib/database/powersync/tables/routines.dart @@ -33,7 +33,7 @@ class WorkoutLogTable extends Table { TextColumn get id => text().clientDefault(() => ps.uuid.v7())(); IntColumn get exerciseId => integer().named('exercise_id')(); IntColumn get routineId => integer().named('routine_id')(); - IntColumn get sessionId => integer().named('session_id').nullable()(); + TextColumn get sessionId => text().named('session_id').nullable()(); IntColumn get iteration => integer().nullable()(); IntColumn get slotEntryId => integer().named('slot_entry_id').nullable()(); @@ -56,7 +56,7 @@ const PowersyncWorkoutLogTable = ps.Table( [ ps.Column.integer('exercise_id'), ps.Column.integer('routine_id'), - ps.Column.integer('session_id'), + ps.Column.text('session_id'), ps.Column.integer('iteration'), ps.Column.integer('slot_entry_id'), ps.Column.real('rir'), diff --git a/lib/helpers/errors.dart b/lib/helpers/errors.dart index eadb3a93c..bbc5795ff 100644 --- a/lib/helpers/errors.dart +++ b/lib/helpers/errors.dart @@ -332,7 +332,7 @@ void showDeleteLogDialog(BuildContext context, String confirmDeleteName, Log log onPressed: () async { await ProviderScope.containerOf( context, - ).read(workoutLogProvider.notifier).deleteEntry(log.id.toString()); + ).read(workoutLogProvider).deleteEntry(log.id.toString()); Navigator.of(contextDialog).pop(); diff --git a/lib/models/trophies/user_trophy_context_data.dart b/lib/models/trophies/user_trophy_context_data.dart index d114e1e1b..ae2650bb2 100644 --- a/lib/models/trophies/user_trophy_context_data.dart +++ b/lib/models/trophies/user_trophy_context_data.dart @@ -26,13 +26,13 @@ part 'user_trophy_context_data.g.dart'; @JsonSerializable() class ContextData { @JsonKey(required: true, name: 'log_id') - final int logId; + final String logId; @JsonKey(required: true, fromJson: utcIso8601ToLocalDate) final DateTime date; @JsonKey(required: true, name: 'session_id') - final int sessionId; + final String sessionId; @JsonKey(required: true, name: 'exercise_id') final int exerciseId; diff --git a/lib/models/trophies/user_trophy_context_data.g.dart b/lib/models/trophies/user_trophy_context_data.g.dart index e1fcc63a4..b16d3dbed 100644 --- a/lib/models/trophies/user_trophy_context_data.g.dart +++ b/lib/models/trophies/user_trophy_context_data.g.dart @@ -23,9 +23,9 @@ ContextData _$ContextDataFromJson(Map json) { ], ); return ContextData( - logId: (json['log_id'] as num).toInt(), + logId: json['log_id'] as String, date: utcIso8601ToLocalDate(json['date'] as String), - sessionId: (json['session_id'] as num).toInt(), + sessionId: json['session_id'] as String, exerciseId: (json['exercise_id'] as num).toInt(), repetitionsUnitId: (json['repetitions_unit_id'] as num).toInt(), repetitions: json['repetitions'] as num, diff --git a/lib/models/workouts/log.dart b/lib/models/workouts/log.dart index a14c95ff3..021c03acc 100644 --- a/lib/models/workouts/log.dart +++ b/lib/models/workouts/log.dart @@ -42,7 +42,7 @@ class Log { late Exercise exerciseObj; late int routineId; - int? sessionId; + String? sessionId; int? iteration; int? slotEntryId; num? rir; @@ -110,7 +110,7 @@ class Log { String? id, int? exerciseId, int? routineId, - int? sessionId, + String? sessionId, int? iteration, int? slotEntryId, num? rir, diff --git a/lib/providers/routines.dart b/lib/providers/routines.dart index e5e5da31e..50e299ecf 100644 --- a/lib/providers/routines.dart +++ b/lib/providers/routines.dart @@ -31,7 +31,6 @@ import 'package:wger/models/workouts/weight_unit.dart'; import 'package:wger/providers/base_provider.dart'; import 'package:wger/providers/exercise_data.dart'; import 'package:wger/providers/wger_base_riverpod.dart'; -import 'package:wger/providers/workout_logs.dart'; import 'package:wger/providers/workout_session.dart'; part 'routines.g.dart'; @@ -128,12 +127,13 @@ class RoutinesRiverpod extends _$RoutinesRiverpod { final exercises = await ref.read(exercisesProvider.future); final repetitionUnits = await ref.read(routineRepetitionUnitProvider.future); final weightUnits = await ref.read(routineWeightUnitProvider.future); + // Sessions arrive pre-joined with their logs from + // [WorkoutSessionRepository.watchAllDrift]. final sessions = await ref.read(workoutSessionProvider.future); - final logs = await ref.read(workoutLogProvider.future); final routine = await repo.fetchAndSetRoutineFullServer(routineId); - // Hydrate data + // Hydrate exercises + units on every set config Future setExercisesAndUnits(List entries) async { for (final entry in entries) { for (final slot in entry.slots) { @@ -152,6 +152,10 @@ class RoutinesRiverpod extends _$RoutinesRiverpod { setExercisesAndUnits(routine.dayDataGym); setExercisesAndUnits(routine.dayData); + // Attach sessions (already joined with their logs) that belong to this + // routine. + routine.sessions = sessions.where((s) => s.routineId == routineId).toList(); + // Update state final current = _currentOrEmpty(); final updatedRoutines = [...current.routines]; diff --git a/lib/providers/routines.g.dart b/lib/providers/routines.g.dart index 65fe7f3bd..a830debe4 100644 --- a/lib/providers/routines.g.dart +++ b/lib/providers/routines.g.dart @@ -111,7 +111,7 @@ final class RoutinesRiverpodProvider RoutinesRiverpod create() => RoutinesRiverpod(); } -String _$routinesRiverpodHash() => r'c10fb6498ffd50152051a625089c53fc9fdd6be8'; +String _$routinesRiverpodHash() => r'f6f92cff3c549ae5c7117e82d59c2d7c90182ee6'; abstract class _$RoutinesRiverpod extends $AsyncNotifier { FutureOr build(); @@ -143,7 +143,7 @@ final class RoutinesRepositoryProvider argument: null, retry: null, name: r'routinesRepositoryProvider', - isAutoDispose: true, + isAutoDispose: false, dependencies: null, $allTransitiveDependencies: null, ); @@ -171,4 +171,4 @@ final class RoutinesRepositoryProvider } } -String _$routinesRepositoryHash() => r'866fede3b610fa71c3204c57ad004465f3e5e3fc'; +String _$routinesRepositoryHash() => r'0cdeb7e33ac45c9a1e4cdf541bf57b565033cc38'; diff --git a/lib/providers/workout_logs.dart b/lib/providers/workout_logs.dart index c027cef3c..682e2d2db 100644 --- a/lib/providers/workout_logs.dart +++ b/lib/providers/workout_logs.dart @@ -16,34 +16,22 @@ * along with this program. If not, see . */ -import 'package:logging/logging.dart'; -import 'package:riverpod_annotation/riverpod_annotation.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:wger/models/workouts/log.dart'; +import 'package:wger/providers/workout_logs_repository.dart'; -import 'workout_logs_repository.dart'; +final workoutLogProvider = Provider((ref) { + return WorkoutLogMutations(ref.read(workoutLogRepositoryProvider)); +}); -part 'workout_logs.g.dart'; +class WorkoutLogMutations { + final WorkoutLogRepository _repo; -@riverpod -final class WorkoutLogNotifier extends _$WorkoutLogNotifier { - final _logger = Logger('WorkoutLogNotifier'); - late WorkoutLogRepository _repo; + WorkoutLogMutations(this._repo); - @override - Stream> build() { - _repo = ref.read(workoutLogRepositoryProvider); - return _repo.watchAllDrift(); - } + Future addEntry(Log log) => _repo.addLocalDrift(log); - Future deleteEntry(String id) async { - await _repo.deleteLocalDrift(id); - } + Future updateEntry(Log log) => _repo.updateLocalDrift(log); - Future updateEntry(Log log) async { - await _repo.updateLocalDrift(log); - } - - Future addEntry(Log log) async { - await _repo.addLocalDrift(log); - } + Future deleteEntry(String id) => _repo.deleteLocalDrift(id); } diff --git a/lib/providers/workout_logs.g.dart b/lib/providers/workout_logs.g.dart deleted file mode 100644 index bd5a69830..000000000 --- a/lib/providers/workout_logs.g.dart +++ /dev/null @@ -1,54 +0,0 @@ -// GENERATED CODE - DO NOT MODIFY BY HAND - -part of 'workout_logs.dart'; - -// ************************************************************************** -// RiverpodGenerator -// ************************************************************************** - -// GENERATED CODE - DO NOT MODIFY BY HAND -// ignore_for_file: type=lint, type=warning - -@ProviderFor(WorkoutLogNotifier) -final workoutLogProvider = WorkoutLogNotifierProvider._(); - -final class WorkoutLogNotifierProvider - extends $StreamNotifierProvider> { - WorkoutLogNotifierProvider._() - : super( - from: null, - argument: null, - retry: null, - name: r'workoutLogProvider', - isAutoDispose: true, - dependencies: null, - $allTransitiveDependencies: null, - ); - - @override - String debugGetCreateSourceHash() => _$workoutLogNotifierHash(); - - @$internal - @override - WorkoutLogNotifier create() => WorkoutLogNotifier(); -} - -String _$workoutLogNotifierHash() => r'ecc623162bd8e9c315335cab649a671c9e15759e'; - -abstract class _$WorkoutLogNotifier extends $StreamNotifier> { - Stream> build(); - @$mustCallSuper - @override - void runBuild() { - final ref = this.ref as $Ref>, List>; - final element = - ref.element - as $ClassProviderElement< - AnyNotifier>, List>, - AsyncValue>, - Object?, - Object? - >; - element.handleCreate(ref, build); - } -} diff --git a/lib/providers/workout_logs_repository.dart b/lib/providers/workout_logs_repository.dart index f7a75bb66..b09d34b0f 100644 --- a/lib/providers/workout_logs_repository.dart +++ b/lib/providers/workout_logs_repository.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (c) 2020, wger Team + * Copyright (c) 2020 - 2026 wger Team * * wger Workout Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by @@ -20,79 +20,25 @@ * Repository for body weight network operations. */ -import 'package:drift/drift.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:logging/logging.dart'; import 'package:wger/models/workouts/log.dart'; -import 'package:wger/providers/exercise_state_notifier.dart'; import '../database/powersync/database.dart'; final workoutLogRepositoryProvider = Provider((ref) { final db = ref.read(driftPowerSyncDatabase); - return WorkoutLogRepository(db, ref); + return WorkoutLogRepository(db); }); +/// Write-side access to the local `workout_log` table. Reading logs happens +/// through [WorkoutSessionRepository.watchAllDrift], which joins logs onto +/// their parent session. class WorkoutLogRepository { final _logger = Logger('WorkoutLogRepository'); final DriftPowersyncDatabase _db; - final Ref _ref; - WorkoutLogRepository(this._db, this._ref); - - Stream> watchAllDrift() { - _logger.finer('Watching all local workout log entries'); - final exercisesProvider = _ref.read(exerciseStateProvider.notifier); - - final query = _db.select(_db.workoutLogTable) - ..orderBy( - [(t) => OrderingTerm(expression: t.date, mode: OrderingMode.desc)], - ); - - final joined = query.join([ - leftOuterJoin( - _db.routineRepetitionUnitTable, - _db.routineRepetitionUnitTable.id.equalsExp(_db.workoutLogTable.repetitionsUnitId), - ), - leftOuterJoin( - _db.routineWeightUnitTable, - _db.routineWeightUnitTable.id.equalsExp(_db.workoutLogTable.weightUnitId), - ), - ]); - - return joined.watch().map((rows) { - final Map map = {}; - - for (final row in rows) { - final log = row.readTable(_db.workoutLogTable); - final repetitionUnit = row.readTableOrNull(_db.routineRepetitionUnitTable); - final weightUnit = row.readTableOrNull(_db.routineWeightUnitTable); - - final entry = map.putIfAbsent( - log.id!, - () => log, - ); - - if (repetitionUnit != null) { - entry.repetitionUnit = repetitionUnit; - } - - if (weightUnit != null) { - entry.weightUnit = weightUnit; - } - - // try { - // log.exercise = exercisesProvider.getById(log.exerciseId); - // } catch (e) { - // _logger.warning( - // 'Could not find exercise for log entry ${log.id} with exercise ID ${log.exerciseId}', - // ); - // } - } - - return map.values.toList(); - }); - } + WorkoutLogRepository(this._db); Future deleteLocalDrift(String id) async { _logger.finer('Deleting local workout log entry $id'); diff --git a/lib/providers/workout_session_repository.dart b/lib/providers/workout_session_repository.dart index 916945585..fc3037fdb 100644 --- a/lib/providers/workout_session_repository.dart +++ b/lib/providers/workout_session_repository.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (c) 2020, wger Team + * Copyright (c) 2020 - 2026 wger Team * * wger Workout Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by @@ -17,7 +17,7 @@ */ /* - * Repository for body weight network operations. + * Repository for workout session local storage. */ import 'package:drift/drift.dart'; @@ -38,17 +38,55 @@ class WorkoutSessionRepository { WorkoutSessionRepository(this._db); + /// Streams all workout sessions with their logs attached. Stream> watchAllDrift() { _logger.finer('Watching all local workout session entries'); - // Note that we can't join to the log table because we don't have access to the - // "real" IDs used by the postgres backend here, only the local UUIDs. - final query = _db.select(_db.workoutSessionTable) - ..orderBy( - [(t) => OrderingTerm(expression: t.date, mode: OrderingMode.desc)], - ); + final query = _db.select(_db.workoutSessionTable).join([ + leftOuterJoin( + _db.workoutLogTable, + _db.workoutLogTable.sessionId.equalsExp(_db.workoutSessionTable.id), + ), + leftOuterJoin( + _db.routineRepetitionUnitTable, + _db.routineRepetitionUnitTable.id.equalsExp(_db.workoutLogTable.repetitionsUnitId), + ), + leftOuterJoin( + _db.routineWeightUnitTable, + _db.routineWeightUnitTable.id.equalsExp(_db.workoutLogTable.weightUnitId), + ), + ])..orderBy([OrderingTerm(expression: _db.workoutSessionTable.date, mode: OrderingMode.desc)]); - return query.watch(); + return query.watch().map((rows) { + final sessions = {}; + final seenLogs = {}; + + for (final row in rows) { + final session = row.readTable(_db.workoutSessionTable); + final entry = sessions.putIfAbsent(session.id, () { + session.logs = []; + return session; + }); + + final log = row.readTableOrNull(_db.workoutLogTable); + if (log == null || seenLogs.contains(log.id)) { + continue; + } + seenLogs.add(log.id); + + final repetitionUnit = row.readTableOrNull(_db.routineRepetitionUnitTable); + if (repetitionUnit != null) { + log.repetitionUnit = repetitionUnit; + } + final weightUnit = row.readTableOrNull(_db.routineWeightUnitTable); + if (weightUnit != null) { + log.weightUnit = weightUnit; + } + entry.logs.add(log); + } + + return sessions.values.toList(); + }); } Future deleteLocalDrift(String id) async { @@ -58,7 +96,7 @@ class WorkoutSessionRepository { Future editLocalDrift(WorkoutSession session) async { _logger.finer('Updating local workout session entry ${session.id}'); - final stmt = _db.update(_db.workoutSessionTable)..where((t) => t.id.equals(session.id!)); + final stmt = _db.update(_db.workoutSessionTable)..where((t) => t.id.equals(session.id)); await stmt.write(session.toCompanion()); } diff --git a/lib/widgets/routines/gym_mode/log_page.dart b/lib/widgets/routines/gym_mode/log_page.dart index 91b32a8e1..aa3f64d23 100644 --- a/lib/widgets/routines/gym_mode/log_page.dart +++ b/lib/widgets/routines/gym_mode/log_page.dart @@ -274,7 +274,7 @@ class _LogFormWidgetState extends ConsumerState { @override Widget build(BuildContext context) { final i18n = AppLocalizations.of(context); - final logProvider = ref.watch(workoutLogProvider.notifier); + final logProvider = ref.read(workoutLogProvider); final log = ref.watch(gymLogProvider); return Form( diff --git a/lib/widgets/routines/gym_mode/summary.dart b/lib/widgets/routines/gym_mode/summary.dart index 044ac35cc..f8fe61356 100644 --- a/lib/widgets/routines/gym_mode/summary.dart +++ b/lib/widgets/routines/gym_mode/summary.dart @@ -103,7 +103,7 @@ class _WorkoutSummaryState extends ConsumerState { (s) => s.date.isSameDayAs(clock.now()), ); final userTrophies = trophyState.prTrophies - .where((t) => t.contextData?.sessionId.toString() == session?.id) + .where((t) => t.contextData?.sessionId == session?.id) .toList(); return WorkoutSessionStats(session, userTrophies); diff --git a/lib/widgets/routines/logs/day_logs_container.dart b/lib/widgets/routines/logs/day_logs_container.dart index 1d68fa8a7..a5b2e7a7c 100644 --- a/lib/widgets/routines/logs/day_logs_container.dart +++ b/lib/widgets/routines/logs/day_logs_container.dart @@ -49,7 +49,7 @@ class DayLogWidget extends ConsumerWidget { final exercises = session.exercises; final prTrophies = trophyState.prTrophies - .where((t) => t.contextData?.sessionId.toString() == session.id) + .where((t) => t.contextData?.sessionId == session.id) .toList(); return Column( diff --git a/test/routine/routine_logs_screen_test.mocks.dart b/test/routine/routine_logs_screen_test.mocks.dart index bd6927f49..b2a385850 100644 --- a/test/routine/routine_logs_screen_test.mocks.dart +++ b/test/routine/routine_logs_screen_test.mocks.dart @@ -144,14 +144,6 @@ class MockWorkoutLogRepository extends _i1.Mock implements _i9.WorkoutLogReposit _i1.throwOnMissingStub(this); } - @override - _i5.Stream> watchAllDrift() => - (super.noSuchMethod( - Invocation.method(#watchAllDrift, []), - returnValue: _i5.Stream>.empty(), - ) - as _i5.Stream>); - @override _i5.Future deleteLocalDrift(String? id) => (super.noSuchMethod(