房间删除​​数据后重置增量密钥

Room reset incremental key after deleting data

删除房间数据库 Table 中的所有数据后,如何将 id(即我的 @PrimaryKey(autogenerate = true))设置回 0?目前我的删除有效,但新插入的数据增加了最后一个 ID 所在的位置。

@Dao
interface MyDao {

 @RawQuery
 fun vacuumDb(supportSQLiteQuery: SupportSQLiteQuery): Int
}

当内容全部删除后,执行这条语句,

MyDao.vacuumDb(SimpleSQLiteQuery("VACUUM"))

VACUUM 命令不会更改数据库的内容,但会更改 rowids。这将重置 rowids.

VACUUM 是如何工作的?

The VACUUM command works by copying the contents of the database into a temporary database file and then overwriting the original with the contents of the temporary file. When overwriting the original, a rollback journal or write-ahead log WAL file is used just as it would be for any other database transaction. This means that when VACUUMing a database, as much as twice the size of the original database file is required in free disk space.

The VACUUM INTO command works the same way except that it uses the file named on the INTO clause in place of the temporary database and omits the step of copying the vacuumed database back over top of the original database.

The VACUUM command may change the ROWIDs of entries in any tables that do not have an explicit INTEGER PRIMARY KEY.

A VACUUM will fail if there is an open transaction on the database connection that is attempting to run the VACUUM. Unfinalized SQL statements typically hold a read transaction open, so the VACUUM might fail if there are unfinalized SQL statements on the same connection. VACUUM (but not VACUUM INTO) is a write operation and so if another database connection is holding a lock that prevents writes, then the VACUUM will fail.

An alternative to using the VACUUM command to reclaim space after data has been deleted is auto-vacuum mode, enabled using the auto_vacuum pragma. When auto_vacuum is enabled for a database free pages may be reclaimed after deleting data, causing the file to shrink, without rebuilding the entire database using VACUUM. However, using auto_vacuum can lead to extra database file fragmentation. And auto_vacuum does not compact partially filled pages of the database as VACUUM does.

更多信息:SQLite VACUUM