upsert<TModel extends SqliteModel> method

  1. @override
Future<int?> upsert<TModel extends SqliteModel>(
  1. TModel instance, {
  2. Query? query,
  3. ModelRepository<SqliteModel>? repository,

Insert record into SQLite. Returns the primary key of the record inserted


Future<int?> upsert<TModel extends SqliteModel>(instance, {query, repository}) async {
  final adapter = modelDictionary.adapterFor[TModel]!;
  final db = await getDb();

  await adapter.beforeSave(instance, provider: this, repository: repository);
  await instance.beforeSave(provider: this, repository: repository);
  final data = await adapter.toSqlite(instance, provider: this, repository: repository);

  final id = await _lock.synchronized(() async {
    return await db.transaction<int?>((txn) async {
      final existingPrimaryKey = await adapter.primaryKeyByUniqueColumns(instance, txn);

      if (instance.isNewRecord && existingPrimaryKey == null) {
        return await txn.insert(

      final primaryKey = existingPrimaryKey ?? instance.primaryKey;
      await txn.update(
        where: '${InsertTable.PRIMARY_KEY_COLUMN} = ?',
        whereArgs: [primaryKey],
      return primaryKey;

  instance.primaryKey = id;
  await adapter.afterSave(instance, provider: this, repository: repository);
  await instance.afterSave(provider: this, repository: repository);
  return id;