Replace

@Insert(onConflict = OnConflictStrategy.REPLACE)
@Update(onConflict = OnConflictStrategy.REPLACE)

What SQLite Does

This strategy maps to INSERT OR REPLACE or UPDATE OR REPLACE statements.

If SQLite encounters a row where a UNIQUE or PRIMARY KEY constraint conflicts with the change requested via the INSERT OR REPLACE or UPDATE OR REPLACE statement, SQLite deletes the existing data and proceeds with the statement. The net effect is that you replace the old data with the new data.

If SQLite encounters a row where a NOT NULL constraint is violated, it will attempt to replace the null value with the default value for that column, if there is one defined in the table schema. If not, this strategy behaves like ABORT.

And for any other constraint violation, this strategy behaves like ABORT.

As a result, this is useful, but only in fairly controlled circumstances, and then mostly for INSERT OR REPLACE. This guarantees that your desired row will wind up in the table, either because it is new or because SQLite gets rid of the previous edition of that row.

Effects in Room

This strategy, like IGNORE, works pretty much as SQLite intends, for the most common use case: a duplicate on a UNIQUE or PRIMARY KEY constraint, resulting in data replacement.

This strategy will have the same problems as ABORT in the cases where it behaves like ABORT — Room will roll back the transaction once it sees the SQLiteConstraintException.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.