@@ -5,12 +5,15 @@ import 'package:path/path.dart';
55class DatabaseHelper {
66 static final DatabaseHelper instance = DatabaseHelper ._init ();
77 static Database ? _database;
8+ static Future <Database >? _initFuture;
89
910 DatabaseHelper ._init ();
1011
1112 Future <Database > get database async {
1213 if (_database != null ) return _database! ;
13- _database = await _initDB ('pegma.db' );
14+ // Prevent race conditions by reusing the same initialization future
15+ _initFuture ?? = _initDB ('pegma.db' );
16+ _database = await _initFuture;
1417 return _database! ;
1518 }
1619
@@ -20,7 +23,7 @@ class DatabaseHelper {
2023
2124 return await openDatabase (
2225 path,
23- version: 4 ,
26+ version: 5 ,
2427 onCreate: _createDB,
2528 onUpgrade: _upgradeDB,
2629 );
@@ -49,6 +52,16 @@ class DatabaseHelper {
4952 )
5053 ''' );
5154 }
55+
56+ if (oldVersion < 5 ) {
57+ // Delete saved games for levels that were modified (10, 45, 48)
58+ // This fixes incompatibility issues while preserving completed level progress
59+ await db.delete (
60+ 'saved_games' ,
61+ where: 'level_id IN (?, ?, ?)' ,
62+ whereArgs: [10 , 45 , 48 ],
63+ );
64+ }
5265 }
5366
5467 Future <void > _createDB (Database db, int version) async {
@@ -126,11 +139,26 @@ class DatabaseHelper {
126139
127140 if (result.isEmpty) return null ;
128141
129- final row = result.first;
130- return {
131- 'board' : jsonDecode (row['board_state' ] as String ) as List <dynamic >,
132- 'moves_count' : row['moves_count' ] as int ,
133- };
142+ try {
143+ final row = result.first;
144+ final boardData = jsonDecode (row['board_state' ] as String ) as List <dynamic >;
145+
146+ // Validate board structure
147+ if (boardData.isEmpty || boardData.first is ! List ) {
148+ // Invalid board structure, delete corrupted save
149+ await deleteSavedGameState (levelId);
150+ return null ;
151+ }
152+
153+ return {
154+ 'board' : boardData,
155+ 'moves_count' : row['moves_count' ] as int ,
156+ };
157+ } catch (e) {
158+ // If decoding fails, delete corrupted save and return null
159+ await deleteSavedGameState (levelId);
160+ return null ;
161+ }
134162 }
135163
136164 Future <void > deleteSavedGameState (int levelId) async {
@@ -143,6 +171,18 @@ class DatabaseHelper {
143171 await db.delete ('saved_games' );
144172 }
145173
174+ /// Clear saved games for specific levels (useful after level modifications)
175+ Future <void > clearSavedGamesForLevels (List <int > levelIds) async {
176+ if (levelIds.isEmpty) return ;
177+ final db = await database;
178+ final placeholders = List .filled (levelIds.length, '?' ).join (',' );
179+ await db.delete (
180+ 'saved_games' ,
181+ where: 'level_id IN ($placeholders )' ,
182+ whereArgs: levelIds,
183+ );
184+ }
185+
146186 Future <void > close () async {
147187 final db = await database;
148188 await db.close ();
0 commit comments