How do I back up and restore swiftdata DB files?

I have two questions:

  1. How to backup and restore swiftdata database files.
  2. In the sandbox, there are three database files: default.store, default.store-wal, and default.store-shm. I want to use SQLite database viewing software to observe the data structure more intuitively. How can I export them into . sqlite file?

Hi!

You could setup the ModelContainer manually (to know when the SwiftData stack is being initialised and probably also to have the possibility to decide what the files are named and where they are stored) and backup/copy those files beforehand. By manually setting up the stack I mean something like that:

     let dbRootURL = (URL.documentsDirectory)
      let dbURL = dbRootURL.appendingPathComponent("TheDB.db")

      // open the db
      let fullSchema = Schema(ModelV3.models)
      let dbCfg = ModelConfiguration(schema: fullSchema, url: dbURL)

      return try ModelContainer(for: fullSchema, migrationPlan: DBMigrationPlan.self, configurations: dbCfg)

Those are pretty much the standard files. Other than that "default.store" has usually renaming the "sqlite" extension. Maybe that confuses the tools you are using. Try renaming it to .sqlite and see if it helps.

Cheers, Michael

I'm glad to receive your reply.

After manually changing the DB address of the ModelContainer, it works fine, and I can see the complete data. At that time, I actually faced another problem, and later found the reason, here is the addition:

Problem: When using the default database, after I changed the suffix of default.store to .db, I found that a lot of data was missing, and I couldn’t see all the data as expected. I guess there are a lot of default.store-wal also stored , but I can't view it.

  • default.store: This is CoreData's actual database file, containing your saved data. All actual data will be stored in this file.
  • default.store-wal: This is the Write-Ahead Log file used to support CoreData's high-performance write operations. On database writes, data is first written to the WAL file and then periodically merged into the actual database file. This improves write performance and reduces the risk of data corruption.
  • default.store-shm: This is the Shared Memory file used to coordinate database read and write operations in WAL mode. It enables multiple read operations to proceed concurrently without being blocked by write operations.

After debugging, I closed the APP directly through Xcode. It may be because the APP was not closed normally, resulting in the data in default.store-wal not being synchronized to default.store. So there are a lot of gaps in the data i see.

How do I back up and restore swiftdata DB files?
 
 
Q