@@ -186,12 +186,15 @@ async function reconstructDatabase() {
186186 } ) ;
187187 await newDb . initialize ( ) ;
188188
189- log . info ( `Reconstructing database at ${ newDbPath } ...` ) ;
190- const workspace = await initWorkspace ( newDb ) ;
191-
192- await migrateNotesAndEmbeds ( oldDb , workspace , newDb ) ;
193- oldDb . close ( ) ;
194- newDb . destroy ( ) ;
189+ try {
190+ log . info ( `Reconstructing database at ${ newDbPath } ...` ) ;
191+ const workspace = await initWorkspace ( newDb ) ;
192+ await migrateNotesAndEmbeds ( oldDb , workspace , newDb ) ;
193+ } finally {
194+ // Ensure locks are disposed
195+ oldDb . close ( ) ;
196+ newDb . destroy ( ) ;
197+ }
195198}
196199
197200async function migrateNotesAndEmbeds (
@@ -359,16 +362,24 @@ async function initWorkspace(newDb: DataSource) {
359362
360363async function swap ( ) {
361364 const backupPath = path . join ( Paths . DATA_ROOT , "darkwrite-data-alpha/" ) ;
365+ let fallbackCreated = false ;
362366 try {
363367 log . info ( "Moving existing data to a fallback location..." ) ;
364368 await fse . move ( Paths . DATA_DIR , backupPath , { overwrite : true } ) ;
369+ fallbackCreated = true ;
365370 await fse . move ( Paths . MIGRATION_CACHE_DIR , Paths . DATA_DIR ) ;
366371 } catch ( err ) {
367372 log . error (
368373 "Failed to move new data directory into place - attempting rollback." ,
369374 err ,
370375 ) ;
371376 try {
377+ if ( ! fallbackCreated ) {
378+ log . error (
379+ "We could not create the fallback directory either. We don't need to rollback." ,
380+ ) ;
381+ throw err ;
382+ }
372383 await fse . move ( backupPath , Paths . DATA_DIR ) ;
373384
374385 throw new Error (
0 commit comments