From 4866551ef4f2a96a63d3c01f210380dd57bb47cc Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Wed, 20 May 2026 15:05:45 +0200 Subject: [PATCH] Move exercises and their translations to RawTables This was causing some delays since we always load all exercise data upfront and this was causing a noticeable delay. --- lib/database/powersync/powersync.dart | 66 ++++++ lib/database/powersync/tables/exercise.dart | 41 ++-- lib/powersync/schema.dart | 81 +++---- lib/providers/exercise_repository.dart | 221 ++++++++++++-------- 4 files changed, 252 insertions(+), 157 deletions(-) diff --git a/lib/database/powersync/powersync.dart b/lib/database/powersync/powersync.dart index 0e8c19ef7..d7d42b3c5 100644 --- a/lib/database/powersync/powersync.dart +++ b/lib/database/powersync/powersync.dart @@ -37,6 +37,7 @@ Future powerSyncInstance(Ref ref) async { logger: attachedLogger, ); await db.initialize(); + await _createRawTables(db); final baseProvider = ref.read(wgerBaseProvider); connectPowerSync(db, baseProvider.serverUrl!); @@ -45,6 +46,71 @@ Future powerSyncInstance(Ref ref) async { return db; } +/// Materialise the native SQLite tables for the raw entries declared in +/// [schema]. PowerSync only manages the JSON view tables itself, so any +/// `RawTable` entry must have its `CREATE TABLE`/`CREATE INDEX` statements +/// applied by us. +/// +/// Skips all work when the raw tables already exist, so warm restarts don't +/// take a write lock on the DB. +Future _createRawTables(PowerSyncDatabase db) async { + // Not STRICT: keep SQLite's type affinity behaviour so PowerSync's + // inferred inserts can bind values as they arrive from the JSON wire + // protocol without us having to coerce types up front. + const rawTables = ['exercises_exercise', 'exercises_translation']; + final existing = await db.getAll( + 'SELECT name FROM sqlite_master ' + 'WHERE type = ? AND name IN (${rawTables.map((_) => '?').join(', ')})', + ['table', ...rawTables], + ); + + if (existing.length == rawTables.length) { + return; + } + + await db.writeTransaction((tx) async { + await tx.execute(''' + CREATE TABLE IF NOT EXISTS exercises_exercise( + id TEXT NOT NULL PRIMARY KEY, + uuid TEXT, + category_id INTEGER, + variation_group TEXT, + created TEXT, + last_update TEXT + ) + '''); + await tx.execute( + 'CREATE INDEX IF NOT EXISTS exercises_exercise__category ' + 'ON exercises_exercise(category_id)', + ); + await tx.execute( + 'CREATE INDEX IF NOT EXISTS exercises_exercise__variation ' + 'ON exercises_exercise(variation_group)', + ); + + await tx.execute(''' + CREATE TABLE IF NOT EXISTS exercises_translation( + id TEXT NOT NULL PRIMARY KEY, + uuid TEXT, + language_id INTEGER, + exercise_id INTEGER, + description TEXT, + name TEXT, + created TEXT, + last_update TEXT + ) + '''); + await tx.execute( + 'CREATE INDEX IF NOT EXISTS exercises_translation__language ' + 'ON exercises_translation(language_id)', + ); + await tx.execute( + 'CREATE INDEX IF NOT EXISTS exercises_translation__exercise ' + 'ON exercises_translation(exercise_id)', + ); + }); +} + /// Creates a fresh [DjangoConnector] for [baseUrl] and connects [db] to it. /// Used both at initial creation and after a logout/login cycle to pick up /// the new user's server URL / credentials. diff --git a/lib/database/powersync/tables/exercise.dart b/lib/database/powersync/tables/exercise.dart index 11f1f861b..a4b1ec893 100644 --- a/lib/database/powersync/tables/exercise.dart +++ b/lib/database/powersync/tables/exercise.dart @@ -43,19 +43,14 @@ class ExerciseTable extends Table { DateTimeColumn get lastUpdate => dateTime().named('last_update')(); } -const PowersyncExerciseTable = ps.Table( - 'exercises_exercise', - [ - ps.Column.text('uuid'), - ps.Column.integer('category_id'), - ps.Column.text('variation_group'), - ps.Column.text('created'), - ps.Column.text('last_update'), - ], - indexes: [ - ps.Index('category', [ps.IndexedColumn('category_id')]), - ps.Index('variation', [ps.IndexedColumn('variation_group')]), - ], +/// Raw table: native SQLite storage instead of the default JSON-view layer. +/// Exercises are server-owned (read-only on the client) and dominate the +/// per-row JSON decode cost, so bypassing the view layer is the lever with +/// the biggest impact. The actual `CREATE TABLE` + `CREATE INDEX` statements +/// live next to `PowerSyncDatabase.initialize()` in `database/powersync/powersync.dart`. +const PowersyncExerciseTable = ps.RawTable.inferred( + name: 'exercises_exercise', + schema: ps.RawTableSchema(), ); @UseRowClass(Translation) @@ -73,21 +68,11 @@ class ExerciseTranslationTable extends Table { DateTimeColumn get lastUpdate => dateTime().named('last_update')(); } -const PowersyncTranslationTable = ps.Table( - 'exercises_translation', - [ - ps.Column.text('uuid'), - ps.Column.integer('language_id'), - ps.Column.integer('exercise_id'), - ps.Column.text('description'), - ps.Column.text('name'), - ps.Column.text('created'), - ps.Column.text('last_update'), - ], - indexes: [ - ps.Index('language', [ps.IndexedColumn('language_id')]), - ps.Index('exercise', [ps.IndexedColumn('exercise_id')]), - ], +/// See [PowersyncExerciseTable]: translations live in the same raw-table +/// store for the same reason (2k+ rows, wide text columns). +const PowersyncTranslationTable = ps.RawTable.inferred( + name: 'exercises_translation', + schema: ps.RawTableSchema(), ); @UseRowClass(ExerciseCategory) diff --git a/lib/powersync/schema.dart b/lib/powersync/schema.dart index 595da5b52..5c7e51c09 100644 --- a/lib/powersync/schema.dart +++ b/lib/powersync/schema.dart @@ -27,46 +27,53 @@ import 'package:wger/database/powersync/tables/nutrition.dart'; import 'package:wger/database/powersync/tables/routines.dart'; import 'package:wger/database/powersync/tables/weight.dart'; -Schema schema = const Schema([ - // Core - PowersyncLanguageTable, - PowersyncLicenseTable, +Schema schema = const Schema( + [ + // Core + PowersyncLanguageTable, + PowersyncLicenseTable, - // Exercises - PowersyncExerciseTable, - PowersyncTranslationTable, - PowersyncMuscleTable, - PowersyncExerciseMuscleM2N, - PowersyncExerciseSecondaryMuscleM2N, - PowersyncEquipmentTable, - PowersyncExerciseEquipmentM2N, - PowersyncExerciseCategoryTable, - PowersyncExerciseImageTable, - PowersyncExerciseVideoTable, + // Exercises (large or wide tables live in the rawTables slot below) + PowersyncMuscleTable, + PowersyncExerciseMuscleM2N, + PowersyncExerciseSecondaryMuscleM2N, + PowersyncEquipmentTable, + PowersyncExerciseEquipmentM2N, + PowersyncExerciseCategoryTable, + PowersyncExerciseImageTable, + PowersyncExerciseVideoTable, - // Nutrition - PowersyncIngredientTable, - PowersyncIngredientImageTable, - PowersyncIngredientWeightUnitTable, - PowersyncNutritionalPlanTable, - PowersyncMealTable, - PowersyncMealItemTable, - PowersyncLogItemTable, + // Nutrition + PowersyncIngredientTable, + PowersyncIngredientImageTable, + PowersyncIngredientWeightUnitTable, + PowersyncNutritionalPlanTable, + PowersyncMealTable, + PowersyncMealItemTable, + PowersyncLogItemTable, - // Body weight - PowersyncWeightEntryTable, + // Body weight + PowersyncWeightEntryTable, - // Measurements - PowersyncMeasurementCategoryTable, - PowersyncMeasurementEntryTable, + // Measurements + PowersyncMeasurementCategoryTable, + PowersyncMeasurementEntryTable, - // Routines - PowersyncRoutineTable, - PowersyncWorkoutLogTable, - PowersyncWorkoutSessionTable, - PowersyncRoutineRepetitionUnitTable, - PowersyncRoutineWeightUnitTable, + // Routines + PowersyncRoutineTable, + PowersyncWorkoutLogTable, + PowersyncWorkoutSessionTable, + PowersyncRoutineRepetitionUnitTable, + PowersyncRoutineWeightUnitTable, - // Gallery - PowersyncGalleryImageTable, -]); + // Gallery + PowersyncGalleryImageTable, + ], + // Raw (native SQLite) tables bypass the JSON-view layer for big read-only + // catalogue tables. The matching CREATE TABLE/INDEX statements live in + // `database/powersync/powersync.dart`. + rawTables: [ + PowersyncExerciseTable, + PowersyncTranslationTable, + ], +); diff --git a/lib/providers/exercise_repository.dart b/lib/providers/exercise_repository.dart index c6be0ed36..ca1a7d64c 100644 --- a/lib/providers/exercise_repository.dart +++ b/lib/providers/exercise_repository.dart @@ -16,6 +16,8 @@ * along with this program. If not, see . */ +import 'dart:async'; + import 'package:drift/drift.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:logging/logging.dart'; @@ -27,7 +29,9 @@ import 'package:wger/models/exercises/category.dart'; import 'package:wger/models/exercises/equipment.dart'; import 'package:wger/models/exercises/exercise.dart'; import 'package:wger/models/exercises/exercise_filters.dart'; +import 'package:wger/models/exercises/image.dart'; import 'package:wger/models/exercises/muscle.dart'; +import 'package:wger/models/exercises/video.dart'; import 'package:wger/providers/base_provider.dart'; import 'package:wger/providers/exercises_notifier.dart'; import 'package:wger/providers/wger_base.dart'; @@ -127,119 +131,152 @@ class ExerciseRepository { /// Streams the full exercise catalogue, hydrated with translations, /// muscles, equipment, category, images and videos. + /// + /// Only the exercise + translation (+ translation language) part runs as + /// a SQL JOIN. The reference tables (muscles, equipment, categories) and + /// the fan-out tables (M2N relations, images, videos) are streamed + /// separately and joined in Dart. This is more effective and we don't have to + /// pay drift's per-row mapping for every joined column. Stream watchAllDrift() { _logger.finer('Watching all local exercises'); - final primaryMuscleTable = _db.alias(_db.muscleTable, 'pm'); - final secondaryMuscleTable = _db.alias(_db.muscleTable, 'sm'); - - final joined = _db.select(_db.exerciseTable).join([ - // Translations + final exerciseTranslationStream = _db.select(_db.exerciseTable).join([ leftOuterJoin( _db.exerciseTranslationTable, _db.exerciseTranslationTable.exerciseId.equalsExp(_db.exerciseTable.id), ), + ]).watch(); - // Language - leftOuterJoin( - _db.languageTable, - _db.languageTable.id.equalsExp(_db.exerciseTranslationTable.languageId), - ), + List? exerciseRows; + List? muscles; + List? equipment; + List? categories; + List? languages; + List? primaryM2N; + List? secondaryM2N; + List? equipmentM2N; + List? images; + List