select<T> method

Future select<T>({
  1. @required required SqlBuilder sqlBuilder,
  2. bool print = false,
  3. dynamic model,
})

Executes a 'SELECT' SQL query and returns the results.

The sqlBuilder parameter is required. It should be an instance of SqlBuilder that represents the 'SELECT' query. The print parameter is optional and defaults to false. If print is true, the final SQL query string will be logged. The model parameter is optional. If provided, it should be an empty instance of the model class that the results should be converted to.

This method first gets a reference to the database by calling getDatabase(). Then it executes the 'SELECT' query by calling rawQuery() on the database reference. The SQL query string is obtained by calling build(print: print) on the sqlBuilder instance.

If the result set is empty, a warning is logged and the method returns an empty list.

If T is not a basic type (String, int, double, bool, DateTime, or Null) and model is null, the method returns the result set as a List<Map<String, dynamic>>.

If model is not null, the method uses reflection to convert each map in the result set to an instance of T. The fromJson method of the model class is used for this conversion. The method returns a list of these instances.

If T is a basic type and model is null, the method tries to convert each map in the result set to T and returns a list of these values. If this conversion fails, a warning is logged and the method returns null.

Usage:

var builder = SqlBuilder();
// Add statements to the builder...
var result = await select<int>(sqlBuilder: builder, print: true);
// or
var result = await select<MyModel>(sqlBuilder: builder, model: MyModel());

Note: If you want to return a model, you must specify an empty instance of that model in order to make the reflection.

Implementation

Future<dynamic> select<T>(
    {@required required SqlBuilder sqlBuilder,
    bool print = false,
    dynamic model}) async {
  var db = await getDatabase();
  var result = await db!.rawQuery(sqlBuilder.build(print: print));
  if (result.isEmpty) {
    PrintHandler.warningLogger
        .t('⚠️sqflite_simple_dao_backend⚠️: No data found.');
  }
  if ((T != String ||
          T != int ||
          T != double ||
          T != bool ||
          T != DateTime ||
          T == Null) &&
      model == null) {
    return result;
  } else if (model != null) {
    ClassMirror instance = reflector.reflect(model).type;
    List<dynamic> list = [];
    for (var x in result) {
      list.add(instance.newInstance('fromJson', [x]));
    }
    return list;
  } else {
    try {
      return result.map((e) => e.values.first as T).toList();
    } catch (e) {
      PrintHandler.warningLogger.f(
          '⛔sqflite_simple_dao_backend⛔: Error selecting data: $e. "null" returned.');
      return null;
    }
  }
}