What are the differences between put and add in Sembast?

534

Per sembast documentation

  /// Create the record if it does not exist.
  ///
  /// Returns the key if inserted, null otherwise.
  Future<K> add(DatabaseClient databaseClient, V value) async
  /// Save a record, create if needed.
  ///
  /// if [merge] is true and the field exists, data is merged
  ///
  /// Returns the updated value.
  Future<V> put(DatabaseClient databaseClient, V value, {bool merge}) async

So basically add won't overwrite the record whereas put will

Edit:

  1. Yes, exactly.
    if (merge == true) {
      record = txnGetRecordSync(txn, key);
      //if (record != null) {
      // Always merge to get rid of FieldValue.delete if any
      value = mergeValue(record?.value, value, allowDotsInKeys: true);
      //}
    } else {
      // Simple clone the calue
      value = cloneValue(value);
    }

and

/// Merge an existing value with a new value, Map only!
dynamic mergeValue(dynamic existingValue, dynamic newValue,

So merge works only for maps, if it works as you said, if not it will create a copy of an object, so the fields that don't exists in it will disappear.

Share:
534
Zenko
Author by

Zenko

Updated on December 21, 2022

Comments

  • Zenko
    Zenko over 1 year

    Using Flutter package called Sembast.

    What are the difference behaviors between these two commands?

    store.record(key).put(db, dataMap)

    and

    store.record(key).add(db, dataMap)

    Specifically about their behavior when there is an existing data.
    Will they overwrite it?
    How does the 'merge' parameter works in the put method?

    And also for any other differences if you have other pointers.

    Thank you.

  • Zenko
    Zenko almost 4 years
    1. Does it mean that if the record exist, add won't do anything while put will overwrite it? 2. How does merge work? Is it like this: If merge = true: it overwrite the existing fields and create non-existing field. Thus after this process, the old and new fields are all existing at the same time. If merge = false: it deletes all the fields then replace with the new fields. Thus, no old fields exist anymore afterwards.
  • Kamil Poniewierski
    Kamil Poniewierski almost 4 years
    I ran out of characters here, see the answer above