upsert<_Model extends SqliteModel> method
Future<int?>
upsert<_Model extends SqliteModel>(
- _Model instance, {
- Query? query,
- ModelRepository<
SqliteModel> ? repository,
Insert record into SQLite. Returns the primary key of the record inserted
Implementation
@override
Future<int?> upsert<_Model extends SqliteModel>(instance, {query, repository}) async {
final adapter = modelDictionary.adapterFor[_Model]!;
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(
'`${adapter.tableName}`',
data,
);
}
final primaryKey = existingPrimaryKey ?? instance.primaryKey;
await txn.update(
'`${adapter.tableName}`',
data,
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;
}