set method

  1. @override
Future<T?> set(
  1. String? correlationId,
  2. T? item
)

Sets a data item. If the data item exists it updates it, otherwise it create a new data item.

  • correlation_id (optional) transaction id to trace execution through call chain.
  • item a item to be set. Return the updated item.

Implementation

@override
Future<T?> set(String? correlationId, T? item) async {
  if (item == null) {
    return null;
  }

  // Assign unique id
  dynamic newItem = item;
  if (newItem.id == null && this.autoGenerateId_) {
    newItem = (newItem as ICloneable).clone();
    newItem.id = IdGenerator.nextLong();
  }

  var row = this.convertFromPublic_(item);
  var columns = this.generateColumns_(row);
  var params = this.generateParameters_(row);
  var setParams = this.generateSetParameters_(row);
  var values = this.generateValues_(row);
  values.addAll(List.from(values));
  // values.add(item.id);

  var query = "INSERT INTO " +
      this.quotedTableName_() +
      " (" +
      columns +
      ") VALUES (" +
      params +
      ")";
  query += " ON DUPLICATE KEY UPDATE " + setParams;

  var res = await client_!.query(query, values);

  query = "SELECT * FROM " + this.quotedTableName_() + " WHERE id=?";
  res = await client_!.query(query, [item.id]);

  var resValues = res.toList().isNotEmpty ? res.toList()[0].fields : null;
  newItem = this.convertToPublic_(resValues);

  logger_.trace(correlationId, "Set in %s with id = %s",
      [this.quotedTableName_(), newItem.id]);

  return newItem;
}