getTopProductsToTranslate method

Future<List<String>> getTopProductsToTranslate(
  1. OpenFoodFactsLanguage language, {
  2. required int limit,
  3. required List<String> excludeBarcodes,
  4. required ProductType productType,
})

Returns the most recently locally accessed products with wrong language.

Typical use-case: when the user changes the app language, downloading incrementally all products with a different (or null) download language. We need excludeBarcodes because in some rare cases products may not be found anymore on the server - it happened to me with obviously fake test products being probably wiped out.

Implementation

Future<List<String>> getTopProductsToTranslate(
  OpenFoodFactsLanguage language, {
  required int limit,
  required List<String> excludeBarcodes,
  required ProductType productType,
}) async {
  final List<String> result = <String>[];

  const String tableJoin =
      'p.$_TABLE_PRODUCT_COLUMN_BARCODE = a.${DaoProductLastAccess.COLUMN_BARCODE}';
  const String columns =
      'p.$_TABLE_PRODUCT_COLUMN_GZIPPED_JSON'
      ',p.$_TABLE_PRODUCT_COLUMN_BARCODE'
      ',p.$_TABLE_PRODUCT_COLUMN_PRODUCT_TYPE';
  // we want rows with a different language - or a null language
  final String languageCondition =
      ' ('
      'p.$_TABLE_PRODUCT_COLUMN_LANGUAGE is null '
      "or p.$_TABLE_PRODUCT_COLUMN_LANGUAGE != '${language.offTag}'"
      ') ';
  // we want rows with that type - or a null type
  final String productTypeCondition =
      ' ('
      'p.$_TABLE_PRODUCT_COLUMN_PRODUCT_TYPE is null '
      "or p.$_TABLE_PRODUCT_COLUMN_PRODUCT_TYPE = '${productType.offTag}'"
      ') ';

  // Listing the rows with a last access, ordered by last access (desc).
  final String queryWithLastAccess =
      'select $columns '
      'from'
      ' $_TABLE_PRODUCT p '
      ' inner join ${DaoProductLastAccess.TABLE} a'
      '  on $tableJoin '
      'where'
      ' $languageCondition '
      ' and $productTypeCondition '
      'order by a.${DaoProductLastAccess.COLUMN_LAST_ACCESS} desc';

  // Listing the rows without a last access.
  final String queryWithoutLastAccess =
      'select $columns '
      'from'
      ' $_TABLE_PRODUCT p '
      'where'
      ' not exists('
      '  select null'
      '  from ${DaoProductLastAccess.TABLE} a '
      '  where $tableJoin '
      ' ) '
      ' and $productTypeCondition '
      ' and $languageCondition';

  final Map<String, String> updates = <String, String>{};

  /// Updates products that didn't have a product_type *in the table column*.
  ///
  /// This way, we lazily populate the database.
  /// After one "language refresh", all products will have a populated
  /// product_type column, so this method will do nothing afterwards.
  Future<void> updateUnknownProductTypes() async {
    for (final MapEntry<String, String> entry in updates.entries) {
      await localDatabase.database.update(
        _TABLE_PRODUCT,
        <String, String>{_TABLE_PRODUCT_COLUMN_PRODUCT_TYPE: entry.value},
        where: '$_TABLE_PRODUCT_COLUMN_BARCODE = ?',
        whereArgs: <String>[entry.key],
      );
    }
  }

  // optimization: using 2 more simple queries than a "left join" that proved
  // more expensive (less than .1s for each simple query, .5s for "left join")
  final List<String> queries = <String>[
    queryWithLastAccess,
    queryWithoutLastAccess,
  ];
  for (final String query in queries) {
    // optimization: using a cursor, as we don't want all the rows,
    // and we don't know how many rows we'll need.
    final QueryCursor queryCursor = await localDatabase.database
        .rawQueryCursor(query, null);
    while (await queryCursor.moveNext()) {
      final String barcode =
          queryCursor.current[_TABLE_PRODUCT_COLUMN_BARCODE]! as String;
      if (excludeBarcodes.contains(barcode)) {
        continue;
      }
      String? foundProductType =
          queryCursor.current[_TABLE_PRODUCT_COLUMN_PRODUCT_TYPE] as String?;
      if (foundProductType == null) {
        final Product product = _getProductFromQueryResult(
          queryCursor.current,
        );
        foundProductType = product.productType?.offTag;
        if (foundProductType != null) {
          updates[barcode] = foundProductType;
        }
      }
      if ((foundProductType ?? ProductType.food.offTag) !=
          productType.offTag) {
        continue;
      }
      result.add(barcode);
      if (result.length == limit) {
        await queryCursor.close();
        await updateUnknownProductTypes();
        return result;
      }
    }
  }

  await updateUnknownProductTypes();
  return result;
}