query static method

Future<List<Map<String, dynamic>>> query(
  1. String table, {
  2. String? where,
  3. String? orderby,
})

Implementation

static Future<List<Map<String, dynamic>>> query(
    String table,
    {
      String? where,
      String? orderby
    }) async {

  List<Map<String, dynamic>> list = [];
  if (!initialized) return list;

  try {
    // open the table
    var box = await Hive.openBox(table);

    // where clause
    Iterable values = box.values.where((map) {
      bool? ok = true;
      if (!isNullOrEmpty(where)) {
        String? sql = Binding.applyMap(where, map, caseSensitive: false);
        ok = toBool(fml_eval.Eval.evaluate(sql));
      }
      return ok!;
    });

    // add values to list
    for (var value in values) {
      if (value is Map) {
        list.add(value.cast<String, dynamic>());
      }
    }

    // order by clause
    if (!isNullOrEmpty(orderby)) {
      // get ordre by field and descending clause
      orderby = orderby!.trim();
      while (orderby!.contains("  ")) {
        orderby = orderby.replaceAll("  ", " ").trim();
      }
      var s = orderby.trim().split(" ");
      orderby = s.first;
      bool descending = false;
      if ((s.isNotEmpty) && (s[1].toLowerCase() == "desc")) descending = true;

      // sort values
      list.sort((a, b) {
        if ((a.containsKey(orderby)) && (b.containsKey(orderby))) {
          return Comparable.compare(b[orderby], a[orderby]);
        } else {
          return 0;
        }
      });

      // sort descending?
      if (descending) list = list.reversed.toList();
    }
  } catch (e) {
    Log().error('Error Querying Table [$table]');
    Log().exception(e,
        caller:
            'database.dart => Future<List<dynamic>> query($table, where: $where, orderby: $orderby)');
  }
  return list;
}