insertReturningOrNull method

Future<D?> insertReturningOrNull(
  1. Insertable<D> entity, {
  2. InsertMode? mode,
  3. UpsertClause<T, D>? onConflict,
})

Inserts a row into the table and returns it.

When no row was inserted and no exception was thrown, for instance because InsertMode.insertOrIgnore was used or because the upsert clause had a where clause that didn't match, null is returned instead.

Implementation

Future<D?> insertReturningOrNull(Insertable<D> entity,
    {InsertMode? mode, UpsertClause<T, D>? onConflict}) async {
  final ctx = createContext(entity, mode ?? InsertMode.insert,
      onConflict: onConflict, returning: true);

  return database.withCurrentExecutor((e) async {
    final result = await e.runSelect(ctx.sql, ctx.boundVariables);
    if (result.isNotEmpty) {
      database.notifyUpdates(
          {TableUpdate.onTable(table, kind: UpdateKind.insert)});
      return table.map(result.single);
    } else {
      return null;
    }
  });
}