SIGN IN SIGN UP

Generate copyWithCompanion on data classes (#3022)

The companion class makes an extremely useful way to bundle up a set
of changes to make to a record.  This copyWithCompanion method makes
it possible to apply those changes directly to a record as represented
in Dart, as an instance of the data class.

For example, it can be used by a wrapper that keeps a write-through
cache in Dart for a given database table.  Here's slightly simplified
from a real example we have in Zulip:

    /// Update an account in the store, returning the new version.
    ///
    /// The account with the given account ID will be updated.
    /// It must already exist in the store.
    Future<Account> updateAccount(int accountId, AccountsCompanion data) async {
      assert(!data.id.present);
      await (_db.update(_db.accounts)
        ..where((a) => a.id.equals(accountId))
      ).write(data);
      final result = _accounts.update(accountId,
        (value) => value.copyWithCompanion(data));
      notifyListeners();
      return result;
    }

It's possible to write such a method by hand, of course (in an
extension), or to call copyWith directly.  But it needs a line for
each column of the table, which makes either of those error-prone:
in particular, because copyWith naturally has its parameters all
optional, it would be very easy for someone adding a new column to
overlook the need to add a line to this method, and then updates to
the new column would just silently get dropped.  So this is a case
where there's a large benefit to generating the code.
G
Greg Price committed
51d2e8f77b190cf3eb3bed78fbf653799079707f
Parent: f3487f3
Committed by GitHub <noreply@github.com> on 5/24/2024, 10:45:12 PM