为什么我的 sqlite3 数据库大小没有减小?

Why does my sqlite3 database not decrease in size?

我正在为 Rails 应用程序测试一些销毁命令,我想确保 Paperclip 确实删除了与我的模型关联的文件。

我 运行 销毁命令成功,我从 Rails 和 Paperclip 收到成功的销毁消息,所以我知道它已经消失了。

令我困惑的是,尽管删除了 704 Kb 的图像,但为什么我的数据库的大小似乎没有减少。

根据 ls -lh,我的 development.sqlite3 文件在销毁前为 17K,销毁后为 17K。

为什么我的数据库文件大小没有减小?

VACUUM 命令通过将其内容复制到临时数据库文件并从副本重新加载原始数据库文件来清理主数据库。这会消除空闲页面,将 table 数据对齐为连续的,否则会清理数据库文件结构。

当一个对象从数据库中删除时,它会留下空的 space。这个空的 space 将在下次将新信息添加到数据库时重新使用。但与此同时,数据库文件可能比绝对需要的要大。

Source

这在 SQLite FAQ:

(12) I deleted a lot of data but the database file did not get any smaller. Is this a bug?

No. When you delete information from an SQLite database, the unused disk space is added to an internal "free-list" and is reused the next time you insert data. The disk space is not lost. But neither is it returned to the operating system.

If you delete a lot of data and want to shrink the database file, run the VACUUM command. VACUUM will reconstruct the database from scratch. This will leave the database with an empty free-list and a file that is minimal in size. Note, however, that the VACUUM can take some time to run and it can use up to twice as much temporary disk space as the original file while it is running.

An alternative to using the VACUUM command is auto-vacuum mode, enabled using the auto_vacuum pragma.