firstWhere<T extends Model> static method

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

Implementation

static Future<T?> firstWhere<T extends Model>({required String field, String comp = "==", required dynamic value}) async {
  final constructor = _jsonConstructors[T];
  if (constructor == null) return null;

  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 = "=";
  }

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


    if (record.isNotEmpty) {
      return constructor(record.first.toColumnMap()) as T;
    }

    return null;

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