where<T extends Model> static method

Future<List<T>> where<T extends Model>({
  1. required String field,
  2. String comp = "==",
  3. required dynamic value,
})

Implementation

static Future<List<T>> where<T extends Model>({required String field, String comp = "==", required dynamic value}) async {


  try {
    final constructor = _jsonConstructors[T];
    if (constructor == null) return [];

    const allowedOps = ['=', '==', '!=', '<', '>', '<=', '>=', 'LIKE'];
    if (!allowedOps.contains(comp.toUpperCase()) && comp != "==") {
      // Todo- Look out for quirks / inconsistent results before changing
      // "==" is usually handled as "=" in SQL or logic
      // Adjust logic if "==" is strictly Dart side or SQL side. SQLite uses "=".
      if (comp == "==") {
        comp = "=";
      } else {
        throw ArgumentError("Invalid SQL operator: $comp");
      }
    } else if (comp == "==") {
      comp = "=";
    }

    final tableName = _getTableName<T>();
    final records = await _database.execute(Sql.named('SELECT * FROM "$tableName" WHERE $field = @$field'),
      parameters: { field: value},
    );

    if (records.isNotEmpty) {
      return records.map((record) => constructor(record.toColumnMap()) as T).toList();
    }

    return [];

  } catch (e) {
    print('Postgres where error: $e');
    return [];
  }
}