Test the persistence base layer

This commit is contained in:
Roland Geider
2026-08-10 09:46:27 +02:00
parent 7ac0a1ebeb
commit 8df72293b5
10 changed files with 637 additions and 51 deletions

View File

@@ -140,17 +140,52 @@ Future<PowerSyncDatabase> powerSyncInstance(Ref ref) async {
///
/// Skips all work when the raw tables already exist, so warm restarts don't
/// take a write lock on the DB.
/// `CREATE TABLE` statement per raw table, keyed by table name.
///
/// 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.
///
/// `id` is INTEGER, not the PowerSync-conventional TEXT, so it matches the
/// Drift `IntColumn id` and the integer `exercise_id` FK: the catalogue join
/// is then native INTEGER == INTEGER instead of relying on TEXT-vs-INTEGER
/// affinity coercion. PowerSync's string oplog id coerces to INTEGER on insert
/// (safe: Django exercise PKs are always numeric).
@visibleForTesting
const rawTableStatements = <String, String>{
'exercises_exercise': '''
CREATE TABLE IF NOT EXISTS exercises_exercise(
id INTEGER NOT NULL PRIMARY KEY,
uuid TEXT,
category_id INTEGER,
variation_group TEXT,
created TEXT,
last_update TEXT
)
''',
'exercises_translation': '''
CREATE TABLE IF NOT EXISTS exercises_translation(
id INTEGER NOT NULL PRIMARY KEY,
uuid TEXT,
language_id INTEGER,
exercise_id INTEGER,
description TEXT,
name TEXT,
created TEXT,
last_update TEXT
)
''',
};
const _rawTableIndexStatements = [
'CREATE INDEX IF NOT EXISTS exercises_exercise__category ON exercises_exercise(category_id)',
'CREATE INDEX IF NOT EXISTS exercises_exercise__variation ON exercises_exercise(variation_group)',
'CREATE INDEX IF NOT EXISTS exercises_translation__language ON exercises_translation(language_id)',
'CREATE INDEX IF NOT EXISTS exercises_translation__exercise ON exercises_translation(exercise_id)',
];
Future<void> _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.
//
// `id` is INTEGER, not the PowerSync-conventional TEXT, so it matches the
// Drift `IntColumn id` and the integer `exercise_id` FK: the catalogue join
// is then native INTEGER == INTEGER instead of relying on TEXT-vs-INTEGER
// affinity coercion. PowerSync's string oplog id coerces to INTEGER on insert
// (safe: Django exercise PKs are always numeric).
const rawTables = ['exercises_exercise', 'exercises_translation'];
final rawTables = rawTableStatements.keys.toList();
final existing = await db.getAll(
'SELECT name FROM sqlite_master '
'WHERE type = ? AND name IN (${rawTables.map((_) => '?').join(', ')})',
@@ -162,45 +197,9 @@ Future<void> _createRawTables(PowerSyncDatabase db) async {
}
await db.writeTransaction((tx) async {
await tx.execute('''
CREATE TABLE IF NOT EXISTS exercises_exercise(
id INTEGER 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 INTEGER 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)',
);
for (final statement in [...rawTableStatements.values, ..._rawTableIndexStatements]) {
await tx.execute(statement);
}
});
}

41
test/core/uuid_test.dart Normal file
View File

@@ -0,0 +1,41 @@
/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* Copyright (c) 2026 - 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
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:flutter_test/flutter_test.dart';
import 'package:wger/core/uuid.dart';
void main() {
test('generates lowercase hex in the canonical 8-4-4-4-12 shape', () {
expect(uuidV4(), matches(RegExp(r'^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$')));
});
test('sets the version and variant bits of a v4 UUID', () {
for (var i = 0; i < 200; i++) {
final parts = uuidV4().split('-');
expect(parts[2][0], '4', reason: 'version nibble');
expect('89ab', contains(parts[3][0]), reason: 'RFC 4122 variant');
}
});
test('does not repeat itself', () {
final seen = {for (var i = 0; i < 1000; i++) uuidV4()};
expect(seen, hasLength(1000));
});
}

View File

@@ -0,0 +1,68 @@
/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* Copyright (c) 2026 - 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
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:flutter_test/flutter_test.dart';
import 'package:wger/database/converters/date_only_text_converter.dart';
void main() {
const converter = DateOnlyTextConverter();
group('toSql', () {
test('writes the calendar day zero-padded', () {
expect(converter.toSql(DateTime(2026, 3, 7)), '2026-03-07');
});
test('drops the time of day', () {
expect(converter.toSql(DateTime(2026, 3, 7, 23, 59, 59)), '2026-03-07');
});
test('writes the day the value represents in its own zone', () {
expect(converter.toSql(DateTime.utc(2026, 3, 7)), '2026-03-07');
});
});
group('fromSql', () {
test('parses a bare date into UTC midnight', () {
final read = converter.fromSql('2026-03-07');
expect(read, DateTime.utc(2026, 3, 7));
expect(read.isUtc, isTrue);
});
test('takes the leading day of a legacy full timestamp', () {
// Rows written before this converter carry a full ISO timestamp
expect(converter.fromSql('2026-03-07T00:00:00.000Z'), DateTime.utc(2026, 3, 7));
});
});
test('a locally written day and the same day synced back compare equal', () {
// The regression this converter exists for: a `.equals()` lookup on a date
// column has to match whether the row was written here or came from the
// server, which sends a bare `YYYY-MM-DD`
final writtenLocally = converter.toSql(DateTime(2026, 3, 7, 18, 45));
final syncedBack = converter.toSql(converter.fromSql('2026-03-07'));
expect(writtenLocally, syncedBack);
});
test('a round trip keeps the calendar day', () {
final read = converter.fromSql(converter.toSql(DateTime(2026, 12, 31, 22)));
expect([read.year, read.month, read.day], [2026, 12, 31]);
});
}

View File

@@ -0,0 +1,43 @@
/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* Copyright (c) 2026 - 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
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:flutter_test/flutter_test.dart';
import 'package:wger/database/converters/exercise_image_style_converter.dart';
import 'package:wger/features/exercises/models/image.dart';
void main() {
const converter = ExerciseImageStyleConverter();
test('maps every wire value to its enum case', () {
expect(converter.fromSql('1'), ExerciseImageStyle.lineArt);
expect(converter.fromSql('2'), ExerciseImageStyle.threeD);
expect(converter.fromSql('3'), ExerciseImageStyle.lowPoly);
expect(converter.fromSql('4'), ExerciseImageStyle.photo);
expect(converter.fromSql('5'), ExerciseImageStyle.other);
});
test('every enum case survives a round trip', () {
for (final style in ExerciseImageStyle.values) {
expect(converter.fromSql(converter.toSql(style)), style);
}
});
test('an unknown wire value throws', () {
expect(() => converter.fromSql('6'), throwsStateError);
});
}

View File

@@ -0,0 +1,45 @@
/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* Copyright (c) 2026 - 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
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:wger/database/converters/time_of_day_converter.dart';
void main() {
const converter = TimeOfDayConverter();
test('writes 24 hour format regardless of the device locale', () {
expect(converter.toSql(const TimeOfDay(hour: 18, minute: 5)), '18:05');
expect(converter.toSql(const TimeOfDay(hour: 0, minute: 0)), '00:00');
});
test('reads a stored time back', () {
expect(converter.fromSql('18:05'), const TimeOfDay(hour: 18, minute: 5));
});
test('a round trip preserves the time', () {
const time = TimeOfDay(hour: 7, minute: 30);
expect(converter.fromSql(converter.toSql(time)), time);
});
test('reads a stored time that carries seconds', () {
// Django serializes `TimeField` with seconds
expect(converter.fromSql('18:05:00'), const TimeOfDay(hour: 18, minute: 5));
});
}

View File

@@ -0,0 +1,60 @@
/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* Copyright (c) 2026 - 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
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:flutter_test/flutter_test.dart';
import 'package:wger/database/converters/utc_datetime_converter.dart';
// The assertions compare instants and the isUtc flag, never wall-clock
// components, so they hold in every time zone.
void main() {
const converter = UtcDateTimeConverter();
group('toSql', () {
test('converts a local value to UTC without moving the instant', () {
final local = DateTime(2026, 6, 15, 14, 30);
final stored = converter.toSql(local);
expect(stored.isUtc, isTrue);
expect(stored.isAtSameMomentAs(local), isTrue);
});
test('leaves a value that is already UTC untouched', () {
final utc = DateTime.utc(2026, 6, 15, 14, 30);
expect(converter.toSql(utc), utc);
});
});
group('fromSql', () {
test('returns the stored instant in the local zone', () {
final stored = DateTime.utc(2026, 6, 15, 12);
final read = converter.fromSql(stored);
expect(read.isUtc, isFalse);
expect(read.isAtSameMomentAs(stored), isTrue);
});
});
test('a round trip preserves the instant', () {
final local = DateTime(2026, 1, 31, 23, 59, 59);
expect(converter.fromSql(converter.toSql(local)), local);
});
}

View File

@@ -0,0 +1,43 @@
/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* Copyright (c) 2026 - 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
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:flutter_test/flutter_test.dart';
import 'package:wger/database/converters/workout_impression_converter.dart';
import 'package:wger/features/routines/models/session.dart';
void main() {
const converter = WorkoutImpressionConverter();
test('maps every wire value to its enum case', () {
expect(converter.fromSql('1'), WorkoutImpression.bad);
expect(converter.fromSql('2'), WorkoutImpression.neutral);
expect(converter.fromSql('3'), WorkoutImpression.good);
});
test('every enum case survives a round trip', () {
for (final impression in WorkoutImpression.values) {
expect(converter.fromSql(converter.toSql(impression)), impression);
}
});
test('an unknown wire value throws', () {
// This sits on the read path of every session, so a new server-side
// choice surfaces as a StateError rather than a silent default
expect(() => converter.fromSql('4'), throwsStateError);
});
}

View File

@@ -0,0 +1,105 @@
/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* Copyright (c) 2026 - 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
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:drift/drift.dart' show DriftSqlType;
import 'package:drift/native.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:wger/database/powersync/database.dart';
import 'package:wger/database/powersync/powersync.dart';
import 'package:wger/powersync/schema.dart';
import '../../helpers/in_memory_drift.dart';
/// PowerSync manages the JSON view tables itself, but the raw tables are
/// materialised from hand-written DDL. Nothing fails loudly when that DDL and
/// the Drift definitions drift apart: the column is simply not there, and
/// every read of it comes back empty.
void main() {
late DriftPowersyncDatabase driftDb;
setUp(() async => driftDb = await openTestDatabase());
tearDown(() => driftDb.close());
/// Column name to SQLite type, as the DDL actually creates them.
Future<Map<String, String>> columnsOf(String table) async {
final db = DriftPowersyncDatabase(NativeDatabase.memory());
addTearDown(db.close);
await db.customStatement(rawTableStatements[table]!);
final rows = await db.customSelect('PRAGMA table_info($table)').get();
return {
for (final row in rows) row.read<String>('name'): row.read<String>('type'),
};
}
test('every raw table in the schema has a statement', () {
expect(
rawTableStatements.keys.toSet(),
schema.rawTables.map((table) => table.name).toSet(),
);
});
test('the created columns match the Drift definitions', () async {
for (final table in rawTableStatements.keys) {
final created = await columnsOf(table);
final driftTable = driftDb.allTables.firstWhere(
(candidate) => candidate.actualTableName == table,
);
expect(
created.keys.toSet(),
driftTable.$columns.map((column) => column.name).toSet(),
reason: 'the raw table $table does not carry every Drift column',
);
}
});
test('the created columns use the affinity of their Drift type', () async {
// `store_date_time_values_as_text` is on, so a Drift DateTimeColumn has to
// be created as TEXT here as well
const expectedAffinity = {
DriftSqlType.string: 'TEXT',
DriftSqlType.int: 'INTEGER',
DriftSqlType.dateTime: 'TEXT',
};
for (final table in rawTableStatements.keys) {
final created = await columnsOf(table);
final driftTable = driftDb.allTables.firstWhere(
(candidate) => candidate.actualTableName == table,
);
for (final column in driftTable.$columns) {
final expected = expectedAffinity[column.type];
expect(
expected,
isNotNull,
reason: 'no affinity defined for ${column.type} ($table.${column.name})',
);
expect(
created[column.name],
expected,
reason:
'$table.${column.name} is created as ${created[column.name]}, '
'but Drift reads it as ${column.type}',
);
}
}
});
}

View File

@@ -19,6 +19,7 @@
import 'dart:convert';
import 'dart:io';
import 'package:drift/drift.dart' show GeneratedColumnWithTypeConverter;
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
@@ -26,9 +27,11 @@ import 'package:logging/logging.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:powersync/powersync.dart';
import 'package:wger/database/converters/date_only_text_converter.dart';
import 'package:wger/powersync/api_client.dart';
import 'package:wger/powersync/connector.dart';
import '../helpers/in_memory_drift.dart';
import 'connector_test.mocks.dart';
@GenerateMocks([ApiClient])
@@ -164,6 +167,35 @@ void main() {
expect(out['start'], '2024-11-01');
expect(out['end'], isNull);
});
test('trims every date-only column in the Drift schema', () async {
// The registry of date-only fields is maintained by hand, so a new
// table backed by a Django `DateField` can be forgotten, and the push
// then fails on a value the backend cannot parse. Derive the columns
// from the schema instead of listing them here again.
final db = await openTestDatabase();
addTearDown(db.close);
final dateOnlyColumns = <(String, String)>[];
for (final table in db.allTables) {
for (final column in table.$columns) {
if (column is GeneratedColumnWithTypeConverter &&
column.converter is DateOnlyTextConverter) {
dateOnlyColumns.add((table.actualTableName, column.name));
}
}
}
expect(dateOnlyColumns, isNotEmpty);
for (final (table, column) in dateOnlyColumns) {
final out = connector.genericTransform(table, {column: '2024-11-01T00:00:00.000Z'}, '1');
expect(
out[column],
'2024-11-01',
reason: '$table.$column is not registered as a date-only field',
);
}
});
});
});
@@ -466,14 +498,16 @@ void main() {
completed = false;
});
CrudTransaction txWith(CrudEntry entry) => CrudTransaction(
CrudTransaction txWithAll(List<CrudEntry> entries) => CrudTransaction(
transactionId: 1,
crud: [entry],
crud: entries,
complete: ({String? writeCheckpoint}) async {
completed = true;
},
);
CrudTransaction txWith(CrudEntry entry) => txWithAll([entry]);
test('uploads a put through the transform and completes on success', () async {
when(api.upsert(any)).thenAnswer((_) async => http.Response('{}', 200));
@@ -519,6 +553,46 @@ void main() {
expect(completed, isTrue);
});
test('a rejected op does not stop the ops behind it', () async {
// One bad op must not block the queue: the rest of the transaction is
// still sent and the transaction completes.
when(api.upsert(any)).thenAnswer(
(_) async => http.Response(json.encode({'error': 'invalid'}), 200),
);
when(api.update(any)).thenAnswer((_) async => http.Response('{}', 200));
await conn.processTransaction(
txWithAll([
CrudEntry(1, UpdateType.put, 'manager_routine', 'r1', 1, {'name': 'x'}),
CrudEntry(2, UpdateType.patch, 'manager_routine', 'r2', 1, {'name': 'y'}),
]),
);
verify(api.update(any)).called(1);
expect(completed, isTrue);
});
test('a retryable op leaves the whole transaction queued for a replay', () async {
// The op ahead of it was already sent, so the replay re-sends it: this is
// the at-least-once delivery the backend handlers have to be idempotent
// for.
when(api.upsert(any)).thenAnswer((_) async => http.Response('{}', 200));
when(api.update(any)).thenAnswer((_) async => http.Response('', 503));
await expectLater(
conn.processTransaction(
txWithAll([
CrudEntry(1, UpdateType.put, 'manager_routine', 'r1', 1, {'name': 'x'}),
CrudEntry(2, UpdateType.patch, 'manager_routine', 'r2', 1, {'name': 'y'}),
]),
),
throwsA(isA<RetryableUploadException>()),
);
verify(api.upsert(any)).called(1);
expect(completed, isFalse);
});
test('rethrows and leaves the transaction queued when the backend is unreachable', () async {
when(api.upsert(any)).thenThrow(http.ClientException('Connection refused'));

View File

@@ -0,0 +1,108 @@
/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* Copyright (c) 2026 - 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
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:drift/drift.dart' as drift;
import 'package:flutter_test/flutter_test.dart';
import 'package:powersync/powersync.dart' as ps;
import 'package:wger/database/powersync/database.dart';
import 'package:wger/powersync/schema.dart';
import '../helpers/in_memory_drift.dart';
/// The PowerSync column type a Drift column of [type] has to be declared as.
///
/// A mismatch does not fail loudly: the generated view returns the value in
/// the declared type, so a `ps.Column.text` behind a Drift `BoolColumn` yields
/// `'0'`, and `'0' != 0` is true in Dart, which silently flips every read.
// Drift hides the common supertype of its column types, so this takes an
// Object and matches on the exported constants.
ps.ColumnType expectedPowerSyncType(Object type) => switch (type) {
drift.DriftSqlType.string => ps.ColumnType.text,
drift.DriftSqlType.bool ||
drift.DriftSqlType.int ||
drift.DriftSqlType.bigInt => ps.ColumnType.integer,
drift.DriftSqlType.double => ps.ColumnType.real,
// `store_date_time_values_as_text` is on (build.yaml)
drift.DriftSqlType.dateTime => ps.ColumnType.text,
_ => throw ArgumentError('No PowerSync mapping defined for $type'),
};
void main() {
late DriftPowersyncDatabase db;
late Map<String, drift.TableInfo<drift.Table, Object?>> driftTables;
setUp(() async {
db = await openTestDatabase();
driftTables = {for (final table in db.allTables) table.actualTableName: table};
});
tearDown(() => db.close());
test('the schema is not empty', () {
// Guards the loops below against silently iterating nothing
expect(schema.tables, isNotEmpty);
expect(driftTables, isNotEmpty);
});
test('every synced table has a Drift counterpart', () {
for (final table in schema.tables) {
expect(driftTables, contains(table.name));
}
});
test('every column is declared with the type of its Drift column', () {
for (final table in schema.tables) {
final driftColumns = {
for (final column in driftTables[table.name]!.$columns) column.name: column,
};
for (final column in table.columns) {
final driftColumn = driftColumns[column.name];
expect(
driftColumn,
isNotNull,
reason: '${table.name}.${column.name} has no Drift column',
);
expect(
column.type,
expectedPowerSyncType(driftColumn!.type),
reason:
'${table.name}.${column.name} is declared as ${column.type.name}, '
'but Drift reads it as ${driftColumn.type}',
);
}
}
});
test('every Drift column is part of the synced schema', () {
for (final table in schema.tables) {
// PowerSync stores the row id outside the payload, so it is never
// declared as a column
final expected = driftTables[table.name]!.$columns
.map((column) => column.name)
.where((name) => name != 'id')
.toSet();
expect(
table.columns.map((column) => column.name).toSet(),
expected,
reason: 'the view for ${table.name} would not carry every Drift column',
);
}
});
}