From df2791a1f720ae04ceaf83aab0399364188bc8ef Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sun, 9 Aug 2026 18:42:49 +0200 Subject: [PATCH] Keep pre-2.7 measurement rows readable --- lib/database/powersync/database.g.dart | 100 +++++++++--------- .../powersync/tables/measurements.dart | 17 +-- .../models/measurement_category.dart | 25 +++++ .../models/measurement_entry.dart | 23 ++++ .../providers/chart_range_setting.g.dart | 22 ++-- .../providers/measurement_repository.dart | 3 +- test/core/validators_test.mocks.dart | 44 ++++++++ .../measurement_repository_test.dart | 21 ++++ 8 files changed, 190 insertions(+), 65 deletions(-) diff --git a/lib/database/powersync/database.g.dart b/lib/database/powersync/database.g.dart index 20396ba14..2f706ad44 100644 --- a/lib/database/powersync/database.g.dart +++ b/lib/database/powersync/database.g.dart @@ -4709,15 +4709,15 @@ class $MeasurementCategoryTableTable extends MeasurementCategoryTable requiredDuringInsert: true, ); @override - late final GeneratedColumnWithTypeConverter metricType = + late final GeneratedColumnWithTypeConverter metricType = GeneratedColumn( 'metric_type', aliasedName, - false, + true, type: DriftSqlType.string, - requiredDuringInsert: true, - ).withConverter( - $MeasurementCategoryTableTable.$convertermetricType, + requiredDuringInsert: false, + ).withConverter( + $MeasurementCategoryTableTable.$convertermetricTypen, ); @override late final GeneratedColumnWithTypeConverter chartType = @@ -4760,7 +4760,7 @@ class $MeasurementCategoryTableTable extends MeasurementCategoryTable late final GeneratedColumn order = GeneratedColumn( 'order', aliasedName, - false, + true, type: DriftSqlType.int, requiredDuringInsert: false, defaultValue: const Constant(0), @@ -4772,7 +4772,7 @@ class $MeasurementCategoryTableTable extends MeasurementCategoryTable late final GeneratedColumn isOfficial = GeneratedColumn( 'is_official', aliasedName, - false, + true, type: DriftSqlType.bool, requiredDuringInsert: false, defaultConstraints: GeneratedColumn.constraintIsAlways( @@ -4849,7 +4849,7 @@ class $MeasurementCategoryTableTable extends MeasurementCategoryTable @override MeasurementCategory map(Map data, {String? tablePrefix}) { final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; - return MeasurementCategory( + return MeasurementCategory.fromDb( id: attachedDatabase.typeMapping.read( DriftSqlType.string, data['${effectivePrefix}id'], @@ -4862,18 +4862,18 @@ class $MeasurementCategoryTableTable extends MeasurementCategoryTable DriftSqlType.string, data['${effectivePrefix}unit'], )!, - metricType: $MeasurementCategoryTableTable.$convertermetricType.fromSql( - attachedDatabase.typeMapping.read( - DriftSqlType.string, - data['${effectivePrefix}metric_type'], - )!, - ), chartType: $MeasurementCategoryTableTable.$converterchartType.fromSql( attachedDatabase.typeMapping.read( DriftSqlType.string, data['${effectivePrefix}chart_type'], ), ), + metricType: $MeasurementCategoryTableTable.$convertermetricTypen.fromSql( + attachedDatabase.typeMapping.read( + DriftSqlType.string, + data['${effectivePrefix}metric_type'], + ), + ), chartConfig: $MeasurementCategoryTableTable.$converterchartConfign.fromSql( attachedDatabase.typeMapping.read( DriftSqlType.string, @@ -4887,11 +4887,11 @@ class $MeasurementCategoryTableTable extends MeasurementCategoryTable order: attachedDatabase.typeMapping.read( DriftSqlType.int, data['${effectivePrefix}order'], - )!, + ), isOfficial: attachedDatabase.typeMapping.read( DriftSqlType.bool, data['${effectivePrefix}is_official'], - )!, + ), ); } @@ -4902,6 +4902,9 @@ class $MeasurementCategoryTableTable extends MeasurementCategoryTable static TypeConverter $convertermetricType = const MeasurementMetricTypeConverter(); + static TypeConverter $convertermetricTypen = NullAwareTypeConverter.wrap( + $convertermetricType, + ); static TypeConverter $converterchartType = const MeasurementChartTypeConverter(); static TypeConverter, String> $converterchartConfig = @@ -4914,12 +4917,12 @@ class MeasurementCategoryTableCompanion extends UpdateCompanion id; final Value name; final Value unit; - final Value metricType; + final Value metricType; final Value chartType; final Value?> chartConfig; final Value parentId; - final Value order; - final Value isOfficial; + final Value order; + final Value isOfficial; final Value rowid; const MeasurementCategoryTableCompanion({ this.id = const Value.absent(), @@ -4937,7 +4940,7 @@ class MeasurementCategoryTableCompanion extends UpdateCompanion custom({ Expression? id, Expression? name, @@ -4977,12 +4979,12 @@ class MeasurementCategoryTableCompanion extends UpdateCompanion? id, Value? name, Value? unit, - Value? metricType, + Value? metricType, Value? chartType, Value?>? chartConfig, Value? parentId, - Value? order, - Value? isOfficial, + Value? order, + Value? isOfficial, Value? rowid, }) { return MeasurementCategoryTableCompanion( @@ -5013,7 +5015,7 @@ class MeasurementCategoryTableCompanion extends UpdateCompanion( - $MeasurementCategoryTableTable.$convertermetricType.toSql( + $MeasurementCategoryTableTable.$convertermetricTypen.toSql( metricType.value, ), ); @@ -5126,7 +5128,7 @@ class $MeasurementEntryTableTable extends MeasurementEntryTable late final GeneratedColumn source = GeneratedColumn( 'source', aliasedName, - false, + true, type: DriftSqlType.string, requiredDuringInsert: false, defaultValue: const Constant('user'), @@ -5223,7 +5225,7 @@ class $MeasurementEntryTableTable extends MeasurementEntryTable @override MeasurementEntry map(Map data, {String? tablePrefix}) { final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; - return MeasurementEntry( + return MeasurementEntry.fromDb( id: attachedDatabase.typeMapping.read( DriftSqlType.string, data['${effectivePrefix}id'], @@ -5249,7 +5251,7 @@ class $MeasurementEntryTableTable extends MeasurementEntryTable source: attachedDatabase.typeMapping.read( DriftSqlType.string, data['${effectivePrefix}source'], - )!, + ), externalId: attachedDatabase.typeMapping.read( DriftSqlType.string, data['${effectivePrefix}external_id'], @@ -5280,7 +5282,7 @@ class MeasurementEntryTableCompanion extends UpdateCompanion { final Value date; final Value value; final Value notes; - final Value source; + final Value source; final Value externalId; final Value?> extraData; final Value rowid; @@ -5339,7 +5341,7 @@ class MeasurementEntryTableCompanion extends UpdateCompanion { Value? date, Value? value, Value? notes, - Value? source, + Value? source, Value? externalId, Value?>? extraData, Value? rowid, @@ -16349,12 +16351,12 @@ typedef $$MeasurementCategoryTableTableCreateCompanionBuilder = Value id, required String name, required String unit, - required MetricType metricType, + Value metricType, Value chartType, Value?> chartConfig, Value parentId, - Value order, - Value isOfficial, + Value order, + Value isOfficial, Value rowid, }); typedef $$MeasurementCategoryTableTableUpdateCompanionBuilder = @@ -16362,12 +16364,12 @@ typedef $$MeasurementCategoryTableTableUpdateCompanionBuilder = Value id, Value name, Value unit, - Value metricType, + Value metricType, Value chartType, Value?> chartConfig, Value parentId, - Value order, - Value isOfficial, + Value order, + Value isOfficial, Value rowid, }); @@ -16449,7 +16451,7 @@ class $$MeasurementCategoryTableTableFilterComposer builder: (column) => ColumnFilters(column), ); - ColumnWithTypeConverterFilters get metricType => + ColumnWithTypeConverterFilters get metricType => $composableBuilder( column: $table.metricType, builder: (column) => ColumnWithTypeConverterFilters(column), @@ -16613,7 +16615,7 @@ class $$MeasurementCategoryTableTableAnnotationComposer GeneratedColumn get unit => $composableBuilder(column: $table.unit, builder: (column) => column); - GeneratedColumnWithTypeConverter get metricType => $composableBuilder( + GeneratedColumnWithTypeConverter get metricType => $composableBuilder( column: $table.metricType, builder: (column) => column, ); @@ -16724,12 +16726,12 @@ class $$MeasurementCategoryTableTableTableManager Value id = const Value.absent(), Value name = const Value.absent(), Value unit = const Value.absent(), - Value metricType = const Value.absent(), + Value metricType = const Value.absent(), Value chartType = const Value.absent(), Value?> chartConfig = const Value.absent(), Value parentId = const Value.absent(), - Value order = const Value.absent(), - Value isOfficial = const Value.absent(), + Value order = const Value.absent(), + Value isOfficial = const Value.absent(), Value rowid = const Value.absent(), }) => MeasurementCategoryTableCompanion( id: id, @@ -16748,12 +16750,12 @@ class $$MeasurementCategoryTableTableTableManager Value id = const Value.absent(), required String name, required String unit, - required MetricType metricType, + Value metricType = const Value.absent(), Value chartType = const Value.absent(), Value?> chartConfig = const Value.absent(), Value parentId = const Value.absent(), - Value order = const Value.absent(), - Value isOfficial = const Value.absent(), + Value order = const Value.absent(), + Value isOfficial = const Value.absent(), Value rowid = const Value.absent(), }) => MeasurementCategoryTableCompanion.insert( id: id, @@ -16864,7 +16866,7 @@ typedef $$MeasurementEntryTableTableCreateCompanionBuilder = required DateTime date, required double value, required String notes, - Value source, + Value source, Value externalId, Value?> extraData, Value rowid, @@ -16876,7 +16878,7 @@ typedef $$MeasurementEntryTableTableUpdateCompanionBuilder = Value date, Value value, Value notes, - Value source, + Value source, Value externalId, Value?> extraData, Value rowid, @@ -17143,7 +17145,7 @@ class $$MeasurementEntryTableTableTableManager Value date = const Value.absent(), Value value = const Value.absent(), Value notes = const Value.absent(), - Value source = const Value.absent(), + Value source = const Value.absent(), Value externalId = const Value.absent(), Value?> extraData = const Value.absent(), Value rowid = const Value.absent(), @@ -17165,7 +17167,7 @@ class $$MeasurementEntryTableTableTableManager required DateTime date, required double value, required String notes, - Value source = const Value.absent(), + Value source = const Value.absent(), Value externalId = const Value.absent(), Value?> extraData = const Value.absent(), Value rowid = const Value.absent(), diff --git a/lib/database/powersync/tables/measurements.dart b/lib/database/powersync/tables/measurements.dart index 0f1519639..79cb1edee 100644 --- a/lib/database/powersync/tables/measurements.dart +++ b/lib/database/powersync/tables/measurements.dart @@ -25,7 +25,7 @@ import 'package:wger/database/converters/utc_datetime_converter.dart'; import 'package:wger/features/measurements/models/measurement_category.dart'; import 'package:wger/features/measurements/models/measurement_entry.dart'; -@UseRowClass(MeasurementCategory) +@UseRowClass(MeasurementCategory, constructor: 'fromDb') class MeasurementCategoryTable extends Table { @override String get tableName => 'measurements_category'; @@ -34,8 +34,12 @@ class MeasurementCategoryTable extends Table { TextColumn get name => text()(); TextColumn get unit => text()(); + // The new 2.7 columns (metricType, order, isOfficial, source) are nullable: + // rows synced before the schema change lack the keys in their local ps_data + // and read as NULL until the full re-sync replaces them. The `fromDb` + // constructors map NULL to the defaults so the UI keeps working meanwhile. TextColumn get metricType => - text().named('metric_type').map(const MeasurementMetricTypeConverter())(); + text().named('metric_type').map(const MeasurementMetricTypeConverter()).nullable()(); /// Chart the user picked, NULL for the one derived from the metric type. TextColumn get chartType => @@ -52,11 +56,12 @@ class MeasurementCategoryTable extends Table { text().named('parent_id').nullable().references(MeasurementCategoryTable, #id)(); /// Position in the category list; for children, the position within the group - IntColumn get order => integer().withDefault(const Constant(0))(); + IntColumn get order => integer().withDefault(const Constant(0)).nullable()(); /// Server-managed official category (max. one per metric type and user). /// Body weight entries live in the official `body_weight` category. - BoolColumn get isOfficial => boolean().named('is_official').withDefault(const Constant(false))(); + BoolColumn get isOfficial => + boolean().named('is_official').withDefault(const Constant(false)).nullable()(); } const PowersyncMeasurementCategoryTable = ps.Table( @@ -78,7 +83,7 @@ const PowersyncMeasurementCategoryTable = ps.Table( ], ); -@UseRowClass(MeasurementEntry) +@UseRowClass(MeasurementEntry, constructor: 'fromDb') class MeasurementEntryTable extends Table { @override String get tableName => 'measurements_measurement'; @@ -93,7 +98,7 @@ class MeasurementEntryTable extends Table { /// Where the reading came from; one of the server's `source` values: /// `user` for manual entries or a health platform (`apple`, `google`). - TextColumn get source => text().withDefault(const Constant('user'))(); + TextColumn get source => text().withDefault(const Constant('user')).nullable()(); /// Platform record UUID, used to deduplicate re-imports. `null` for manual /// entries. diff --git a/lib/features/measurements/models/measurement_category.dart b/lib/features/measurements/models/measurement_category.dart index f21669562..f1254b046 100644 --- a/lib/features/measurements/models/measurement_category.dart +++ b/lib/features/measurements/models/measurement_category.dart @@ -573,6 +573,31 @@ class MeasurementCategory with _$MeasurementCategory { this.children = const [], }); + /// Maps a row of the local database. Rows synced before the 2.7 schema + /// change lack the new columns and read as NULL; they fall back to the + /// defaults until the full re-sync replaces them. + MeasurementCategory.fromDb({ + required String id, + required String name, + required String unit, + required ChartType chartType, + MetricType? metricType, + Map? chartConfig, + String? parentId, + int? order, + bool? isOfficial, + }) : this( + id: id, + name: name, + unit: unit, + metricType: metricType ?? MetricType.custom, + chartType: chartType, + chartConfig: chartConfig, + parentId: parentId, + order: order ?? 0, + isOfficial: isOfficial ?? false, + ); + /// How this category is drawn, beyond the chart type: see [ChartSettings]. ChartSettings get chartSettings => ChartSettings.fromConfig(chartConfig); diff --git a/lib/features/measurements/models/measurement_entry.dart b/lib/features/measurements/models/measurement_entry.dart index a1cadd88e..8e3128ef7 100644 --- a/lib/features/measurements/models/measurement_entry.dart +++ b/lib/features/measurements/models/measurement_entry.dart @@ -68,6 +68,29 @@ class MeasurementEntry with _$MeasurementEntry { this.extraData, }); + /// Maps a row of the local database. Rows synced before the 2.7 schema + /// change lack the new columns and read as NULL; they fall back to the + /// defaults until the full re-sync replaces them. + MeasurementEntry.fromDb({ + required String id, + required String categoryId, + required DateTime date, + required double value, + required String notes, + String? source, + String? externalId, + Map? extraData, + }) : this( + id: id, + categoryId: categoryId, + date: date, + value: value, + notes: notes, + source: source ?? 'user', + externalId: externalId, + extraData: extraData, + ); + // Boilerplate MeasurementEntryTableCompanion toCompanion() { return MeasurementEntryTableCompanion( diff --git a/lib/features/measurements/providers/chart_range_setting.g.dart b/lib/features/measurements/providers/chart_range_setting.g.dart index d692a9324..a12ee23d3 100644 --- a/lib/features/measurements/providers/chart_range_setting.g.dart +++ b/lib/features/measurements/providers/chart_range_setting.g.dart @@ -10,30 +10,33 @@ part of 'chart_range_setting.dart'; // ignore_for_file: type=lint, type=warning /// The time range the measurement charts cover, shared by the overview, the /// category detail screens and the weight screen: a pick follows the user -/// through them instead of every screen starting over at its own default. +/// through them instead of every screen starting over at its own default, +/// and it is persisted /// /// keepAlive on purpose: autoDispose would reset the pick whenever no screen /// is listening for a moment (a tab switch), which is exactly the surprise -/// this provider removes. It holds for the session; a restart starts over. +/// this provider removes. @ProviderFor(ChartRangeSetting) final chartRangeSettingProvider = ChartRangeSettingProvider._(); /// The time range the measurement charts cover, shared by the overview, the /// category detail screens and the weight screen: a pick follows the user -/// through them instead of every screen starting over at its own default. +/// through them instead of every screen starting over at its own default, +/// and it is persisted /// /// keepAlive on purpose: autoDispose would reset the pick whenever no screen /// is listening for a moment (a tab switch), which is exactly the surprise -/// this provider removes. It holds for the session; a restart starts over. +/// this provider removes. final class ChartRangeSettingProvider extends $NotifierProvider { /// The time range the measurement charts cover, shared by the overview, the /// category detail screens and the weight screen: a pick follows the user - /// through them instead of every screen starting over at its own default. + /// through them instead of every screen starting over at its own default, + /// and it is persisted /// /// keepAlive on purpose: autoDispose would reset the pick whenever no screen /// is listening for a moment (a tab switch), which is exactly the surprise - /// this provider removes. It holds for the session; a restart starts over. + /// this provider removes. ChartRangeSettingProvider._() : super( from: null, @@ -61,15 +64,16 @@ final class ChartRangeSettingProvider extends $NotifierProvider r'ca0074ed6745f437866cdddccf93eec3b6e1dd7b'; +String _$chartRangeSettingHash() => r'1baa3a7e0c1a7643fa93631c51f8f3672b54e30f'; /// The time range the measurement charts cover, shared by the overview, the /// category detail screens and the weight screen: a pick follows the user -/// through them instead of every screen starting over at its own default. +/// through them instead of every screen starting over at its own default, +/// and it is persisted /// /// keepAlive on purpose: autoDispose would reset the pick whenever no screen /// is listening for a moment (a tab switch), which is exactly the surprise -/// this provider removes. It holds for the session; a restart starts over. +/// this provider removes. abstract class _$ChartRangeSetting extends $Notifier { ChartRange build(); diff --git a/lib/features/measurements/providers/measurement_repository.dart b/lib/features/measurements/providers/measurement_repository.dart index 569abac7e..2e357e693 100644 --- a/lib/features/measurements/providers/measurement_repository.dart +++ b/lib/features/measurements/providers/measurement_repository.dart @@ -575,7 +575,8 @@ class MeasurementRepository { await _db.transaction(() async { for (var i = 0; i < orderedIds.length; i++) { final stmt = _db.update(_db.measurementCategoryTable) - ..where((t) => t.id.equals(orderedIds[i]) & t.order.equals(i).not()); + // IS NOT so legacy rows with a NULL order still get written + ..where((t) => t.id.equals(orderedIds[i]) & t.order.isNotValue(i)); await stmt.write(MeasurementCategoryTableCompanion(order: Value(i))); } }); diff --git a/test/core/validators_test.mocks.dart b/test/core/validators_test.mocks.dart index 08f0ddbc3..6261e84f6 100644 --- a/test/core/validators_test.mocks.dart +++ b/test/core/validators_test.mocks.dart @@ -5490,6 +5490,50 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations { ) as String); + @override + String relativeDaysAgo(int? count) => + (super.noSuchMethod( + Invocation.method(#relativeDaysAgo, [count]), + returnValue: _i3.dummyValue( + this, + Invocation.method(#relativeDaysAgo, [count]), + ), + ) + as String); + + @override + String relativeWeeksAgo(int? count) => + (super.noSuchMethod( + Invocation.method(#relativeWeeksAgo, [count]), + returnValue: _i3.dummyValue( + this, + Invocation.method(#relativeWeeksAgo, [count]), + ), + ) + as String); + + @override + String relativeMonthsAgo(int? count) => + (super.noSuchMethod( + Invocation.method(#relativeMonthsAgo, [count]), + returnValue: _i3.dummyValue( + this, + Invocation.method(#relativeMonthsAgo, [count]), + ), + ) + as String); + + @override + String relativeYearsAgo(int? count) => + (super.noSuchMethod( + Invocation.method(#relativeYearsAgo, [count]), + returnValue: _i3.dummyValue( + this, + Invocation.method(#relativeYearsAgo, [count]), + ), + ) + as String); + @override String sparkAverage(String? value) => (super.noSuchMethod( diff --git a/test/features/measurements/providers/measurement_repository_test.dart b/test/features/measurements/providers/measurement_repository_test.dart index 250b8ccdf..addd97f4d 100644 --- a/test/features/measurements/providers/measurement_repository_test.dart +++ b/test/features/measurements/providers/measurement_repository_test.dart @@ -218,6 +218,27 @@ void main() { (await repo.watchAllWithoutEntries().first).map((c) => c.id), ); }); + + test('maps the NULL columns of a pre-2.7 row to the defaults', () async { + // A row synced before the 2.7 schema change carries no value for the new + // columns and reads NULL until a re-sync replaces it + await db.customStatement( + 'INSERT INTO measurements_category (id, name, unit, metric_type, "order", is_official) ' + "VALUES ('legacy', 'Old category', 'cm', NULL, NULL, NULL)", + ); + await db.customStatement( + 'INSERT INTO measurements_measurement (id, category_id, date, value, notes, source) ' + "VALUES ('legacy-entry', 'legacy', '2026-01-01T00:00:00.000Z', 42, '', NULL)", + ); + + final category = (await repo.watchAllWithoutEntries().first).single; + expect(category.metricType, MetricType.custom); + expect(category.order, 0); + expect(category.isOfficial, isFalse); + + final entry = (await repo.watchEntries('legacy', limit: 10).first).single; + expect(entry.source, 'user'); + }); }); group('the import dedup queries', () {