update method

Future<T?> update([
  1. dynamic id,
  2. Map<String, dynamic>? data
])

Update existing record using the helper method

Implementation

Future<T?> update([dynamic id, Map<String, dynamic>? data]) async {
  final currentId = this.id ?? id;
  if (currentId == null) {
    throw Exception("Cannot update: $primaryKey is null");
  }

  final updateMap = data ?? toMap();
  final updateData = Map<String, dynamic>.from(updateMap)
    ..remove(primaryKey)
    ..removeWhere((k, v) => k.trim().isEmpty);

  if (updateData.isEmpty) {
    throw Exception("No data provided for update");
  }

  // Use backticks for column names to handle reserved words
  final setClause = updateData.keys.map((k) => '`$k` = :$k').join(', ');

  final sql =
      'UPDATE `${table.name}` SET $setClause WHERE `$primaryKey` = :id';
  final params = {...updateData, 'id': currentId};

  await _executeQuery(sql, namedParams: params);

  return await refresh(currentId);
}