Skip to content

Commit b77a42b

Browse files
committed
fix: Handle race condition in demo data migration
- Try update, create, then update - Handles concurrent creation
1 parent ddd3cac commit b77a42b

File tree

1 file changed

+52
-10
lines changed

1 file changed

+52
-10
lines changed

lib/shared/services/demo_data_migration_service.dart

Lines changed: 52 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -43,11 +43,32 @@ class DemoDataMigrationService {
4343
userId: oldUserId,
4444
);
4545
final newSettings = oldSettings.copyWith(id: newUserId);
46-
await _userAppSettingsRepository.update(
47-
id: newUserId,
48-
item: newSettings,
49-
userId: newUserId,
50-
);
46+
47+
try {
48+
// Attempt to update first (if a default entry already exists)
49+
await _userAppSettingsRepository.update(
50+
id: newUserId,
51+
item: newSettings,
52+
userId: newUserId,
53+
);
54+
} on NotFoundException {
55+
// If update fails because item not found, try to create
56+
try {
57+
await _userAppSettingsRepository.create(
58+
item: newSettings,
59+
userId: newUserId,
60+
);
61+
} on ConflictException {
62+
// If create fails due to conflict (item was created concurrently),
63+
// re-attempt update. This handles a race condition.
64+
await _userAppSettingsRepository.update(
65+
id: newUserId,
66+
item: newSettings,
67+
userId: newUserId,
68+
);
69+
}
70+
}
71+
5172
await _userAppSettingsRepository.delete(
5273
id: oldUserId,
5374
userId: oldUserId,
@@ -75,11 +96,32 @@ class DemoDataMigrationService {
7596
userId: oldUserId,
7697
);
7798
final newPreferences = oldPreferences.copyWith(id: newUserId);
78-
await _userContentPreferencesRepository.update(
79-
id: newUserId,
80-
item: newPreferences,
81-
userId: newUserId,
82-
);
99+
100+
try {
101+
// Attempt to update first (if a default entry already exists)
102+
await _userContentPreferencesRepository.update(
103+
id: newUserId,
104+
item: newPreferences,
105+
userId: newUserId,
106+
);
107+
} on NotFoundException {
108+
// If update fails because item not found, try to create
109+
try {
110+
await _userContentPreferencesRepository.create(
111+
item: newPreferences,
112+
userId: newUserId,
113+
);
114+
} on ConflictException {
115+
// If create fails due to conflict (item was created concurrently),
116+
// re-attempt update. This handles a race condition.
117+
await _userContentPreferencesRepository.update(
118+
id: newUserId,
119+
item: newPreferences,
120+
userId: newUserId,
121+
);
122+
}
123+
}
124+
83125
await _userContentPreferencesRepository.delete(
84126
id: oldUserId,
85127
userId: oldUserId,

0 commit comments

Comments
 (0)