Use leftOuterJoin in the nutrition sql

This commit is contained in:
Roland Geider
2026-06-03 15:26:14 +02:00
parent f86ee0838e
commit ae2c6939fb
2 changed files with 33 additions and 10 deletions

View File

@@ -252,7 +252,7 @@ class NutritionRepository {
Stream<List<LogItem>> watchAllLogsHydrated() {
_logger.finer('Watching all local diary entries');
final query = _db.select(_db.logItemTable).join([
innerJoin(
leftOuterJoin(
_db.ingredientTable,
_db.ingredientTable.id.equalsExp(_db.logItemTable.ingredientId),
),
@@ -277,18 +277,20 @@ class NutritionRepository {
for (final row in rows) {
final log = row.readTable(_db.logItemTable);
final ingredient = row.readTable(_db.ingredientTable);
final ingredient = row.readTableOrNull(_db.ingredientTable);
final image = row.readTableOrNull(_db.ingredientImageTable);
final wu = row.readTableOrNull(_db.ingredientWeightUnitTable);
final ingEntry = ingredients.putIfAbsent(ingredient.id, () => ingredient);
if (image != null) {
ingEntry.image = image;
}
if (wu != null) {
final list = weightUnitsByIngredient.putIfAbsent(ingredient.id, () => []);
if (!list.any((w) => w.id == wu.id)) {
list.add(wu);
if (ingredient != null) {
final ingEntry = ingredients.putIfAbsent(ingredient.id, () => ingredient);
if (image != null) {
ingEntry.image = image;
}
if (wu != null) {
final list = weightUnitsByIngredient.putIfAbsent(ingredient.id, () => []);
if (!list.any((w) => w.id == wu.id)) {
list.add(wu);
}
}
}

View File

@@ -443,6 +443,27 @@ void main() {
expect(emitted.single.ingredient?.name, 'Apple');
});
test('log whose ingredient has not synced yet still emits with null', () async {
// Models the window between addLogLocalDrift and PowerSync pulling the
// referenced ingredient down. The diary entry must stay visible (else the
// daily totals undercount) rather than being dropped by the join.
await seedPlan(id: planUuid1);
await repo.addLogLocalDrift(
LogItem(
planId: planUuid1,
ingredientId: 42,
amount: 100,
datetime: DateTime.utc(2026, 4, 15),
),
);
final emitted = await repo.watchAllLogsHydrated().first;
expect(emitted, hasLength(1));
expect(emitted.single.ingredient, isNull);
expect(emitted.single.amount, 100);
});
test('watchAllLogsHydrated attaches image and weight units to each ingredient', () async {
await seedPlan(id: planUuid1);
await seedIngredient(id: 1, name: 'Apple');