11

By design, Core Data does not issue a VACUUM SQL command to its SQLite database(s), as detailed here. I'm creating a Core Data application that'll store, and later delete, large binary files (2-10MB in size) in a SQLite db. Over time this will lead to fragmentation and a larger-than-necessary SQLite database. I'd like to periodically issue a VACUUM command, say, during a cleanup operation I run.

  • How can I progmatically issue a VACUUM command to Core Data's SQLite stores?
  • Is it possible to do this through Core Data, or must I mount the SQLite db and connect to it directly to execute the VACUUM SQL?
Dave
  • 12,408
  • 12
  • 64
  • 67

3 Answers3

14

The supported way to do this, on OS X 10.6 / iOS 3.0 and later, is to set the NSSQLiteManualVacuumOption in the options when you are adding the store to the persistent store coordinator.

Pang
  • 9,564
  • 146
  • 81
  • 122
Jim Correia
  • 7,064
  • 1
  • 33
  • 24
1

Yes, vacuum is a recognized SQL statement in SQLite. It can be used as a normal query, or so it says.

Beware, though, as it can lead to excessive file system reads and writes—the bottleneck of practically any system—not to mention server file system fragmentation on Windows servers.

amphetamachine
  • 27,620
  • 12
  • 60
  • 72
1

Here's how you can vacuum your CoreData container

Example:

let container = NSPersistentContainer(name: "someName")

// Enable history tracking and remote notifications
guard let description = container.persistentStoreDescriptions.first else {
    fatalError("###\(#function): Failed to retrieve a persistent store description.")
}

description.setOption(true as NSNumber, forKey: NSSQLiteManualVacuumOption)

//... The rest of your setup

By doing this, the CoreData container will perform the vacuum command and thus resize itself accordingly.

Ivan Cantarino
  • 3,058
  • 4
  • 34
  • 73
  • It seems weird that setting an *option* causes an immediate *action*. Is it just me? I presume that this NSSQLiteManualVacuumOption remains *true* after them vacuum is complete. Does it have any additional effects later? – Jerry Krinock May 12 '22 at 17:33