upsert method

Future<DtoChatItem> upsert(
  1. DtoChatItem item, {
  2. bool toView = false,
})

Creates or updates the provided item in the database.

If toView is true, then also adds a view to the ChatItemViews.

Implementation

Future<DtoChatItem> upsert(DtoChatItem item, {bool toView = false}) async {
  Log.debug('upsert($item) toView($toView)', '$runtimeType');

  _cache[item.value.id] = item;

  final result = await safe((db) async {
    final ChatItemRow row = item.toDb();
    final DtoChatItem stored = _ChatItemDb.fromDb(
      await db
          .into(db.chatItems)
          .insertReturning(row, onConflict: DoUpdate((_) => row)),
    );

    if (toView) {
      final ChatItemViewRow row = item.toView();
      await db
          .into(db.chatItemViews)
          .insertReturning(row, onConflict: DoUpdate((_) => row));
    }

    return stored;
  }, tag: 'chat_item.upsert(item, toView: $toView)');

  return result ?? item;
}