CBL 2.x: Is database.compact() run automatically

CBL 2.6 Android

Is database.compact()[1] run automatically? I believe I learned it while taking the course or read it somewhere but I cannot find the reference anymore. I know it was highly recommend to compact the database manually periodically.

[1] https://docs.couchbase.com/mobile/2.6.0/couchbase-lite-java/com/couchbase/lite/Database.html#compact–

It is not run automatically.

Hi, I resume this post to better understand how and when run compact database function. There is no documentation on this topic and i want to know what are the best practice.
It’s a good practice run compact function when the app goes in background?

It basically does two things:

  1. Runs the SQLite commands PRAGMA optimize(3); PRAGMA incremental_vacuum; PRAGMA wal_checkpoint(TRUNCATE). This shrinks the database file by shuffling pages around to get rid of unused free space. (You can read the details in the SQLite docs.)
  2. Finds cached [on disk] blobs that are no longer referenced by any documents and deletes their files. You can think of this as a garbage-collector for blobs.

So you’re freeing up storage space, at the expense of potentially a lot of I/O. That’s why we don’t run it automatically: it can take time to run, and the database file is not accessible during step 1 because it’s being modified by those pragmas. So we don’t want to arbitrarily lock you out of your database when it could affect responsiveness.

Running when the app goes into the background is reasonable if you make sure the OS will let you keep running — on iOS you’ll need to register a ‘background task’ so your process continues to get CPU time.

Also note that, the longer it’s been since the last time you called compact, the longer it will take to run. Kind of like ordinary house cleaning… :slight_smile:

1 Like