fix(mobile): dedupe stale remote_asset rows on sync

queue a pre-delete on the matching partial-index tuple before each
upsert in updateAssetsV1/V2 so the second insert does not crash on
SqliteException(2067) when the server re-issues a new id for the
same (ownerId, checksum). closes #22522 #27186.
This commit is contained in:
Santo Shakil
2026-05-15 23:31:38 +06:00
parent 21d6755f39
commit 1dd68e5950
2 changed files with 163 additions and 1 deletions
@@ -197,6 +197,16 @@ class SyncStreamRepository extends DriftDatabaseRepository {
try {
await _db.batch((batch) {
for (final asset in data) {
// Avoid SqliteException(2067) when server re-issues a new id for
// the same (ownerId, checksum). #22522 #27186
_enqueueRemoteAssetDedupe(
batch,
id: asset.id,
ownerId: asset.ownerId,
checksum: asset.checksum,
libraryId: asset.libraryId,
);
final companion = RemoteAssetEntityCompanion(
name: Value(asset.originalFileName),
type: Value(asset.type.toAssetType()),
@@ -236,6 +246,15 @@ class SyncStreamRepository extends DriftDatabaseRepository {
try {
await _db.batch((batch) {
for (final asset in data) {
// See updateAssetsV1 for why this dedupe is required. #22522 #27186
_enqueueRemoteAssetDedupe(
batch,
id: asset.id,
ownerId: asset.ownerId,
checksum: asset.checksum,
libraryId: asset.libraryId,
);
final companion = RemoteAssetEntityCompanion(
name: Value(asset.originalFileName),
type: Value(asset.type.toAssetType()),
@@ -271,6 +290,39 @@ class SyncStreamRepository extends DriftDatabaseRepository {
}
}
/// Queues a DELETE that prunes any stale remote_asset row matching the
/// partial UNIQUE index for the incoming asset:
/// - libraryId IS NULL -> (owner_id, checksum)
/// - libraryId NOT NULL -> (owner_id, library_id, checksum)
/// The current id is excluded so a same-id update does not delete itself.
void _enqueueRemoteAssetDedupe(
Batch batch, {
required String id,
required String ownerId,
required String checksum,
required String? libraryId,
}) {
if (libraryId == null) {
batch.deleteWhere(
_db.remoteAssetEntity,
(row) =>
row.ownerId.equals(ownerId) &
row.checksum.equals(checksum) &
row.libraryId.isNull() &
row.id.equals(id).not(),
);
} else {
batch.deleteWhere(
_db.remoteAssetEntity,
(row) =>
row.ownerId.equals(ownerId) &
row.checksum.equals(checksum) &
row.libraryId.equals(libraryId) &
row.id.equals(id).not(),
);
}
}
Future<void> updateAssetsExifV1(Iterable<SyncAssetExifV1> data, {String debugLabel = 'user'}) async {
try {
await _db.batch((batch) {