ROOM database framework migration refers to north

ROOM database migration refers to the operation of modifying the database when the class, structure, or index of an Entity Entity needs to be changed due to the change of the service logic. Each operation needs to add 1 to the version number of the database. For the non-important database, the version number can be directly upgraded to perform destructive update. Destructive updates wipe out the database. Think twice before using destructive updates.

Migration steps
  1. Add or modify an Entity class, ensure that the class is marked with @Entity annotation, and add primary key and index information based on business requirements.
  2. inRoomDatabaseRegister the entity class on the implementation class of, and add the version number +1.
  3. Write the corresponding versionMigrationClass and passaddMigrationsMethod registered toRoom.databaseBuilder()In the call chain.
  • Note: The following Chinese characters need to be replaced with the corresponding English names.[]The inside parameter is optional
Add a new table

CREATE TABLE IF NOT EXISTS (' field 1 'type [NOT NULL] [DEFAULT DEFAULT value]...) PRIMARY KEY(' field name '...)

Add nullable fields

ALTER TABLE 'ALTER TABLE name' ADD COLUMN 'new COLUMN name' type

Add non-empty fields

Because adding a non-null field will cause the old data to fail to correctly retrieve the new field value, we have to rename the old table, create a new table, and copy the old data to it. ALTER TABLE ‘TABLE name’ RENAME TO ‘temp’ CREATE TABLE IF NOT EXISTS ‘TABLE name’ ALTER TABLE ‘TABLE name’ RENAME TO ‘temp’ CREATE TABLE IF NOT EXISTS ‘TABLE name’ ALTER TABLE ‘TABLE name’ RENAME TO ‘temp’ CREATE TABLE IF NOT EXISTS ‘TABLE name’ New field name type [NOT NULL] [DEFAULT DEFAULT]…) PRIMARY KEY(‘ field name ‘…) INSERT INTO ‘table name’ (‘ field 1 ‘, ‘new field name’…) SELECT (‘ field 1 ‘, default…) FROM `Temp` DROP TABLE `temp`

Adding indexes

CREATE INDEX IF NOT EXISTS 'index_ table name _ field name' ON 'table name' (' field name ')