Search code examples
androidsqliteandroid-contentprovider

Batch job - violate constraint temporarily


Let's think about a column with a unique constraint and following values:

Col1
1
2
3

Now I want to change those values in a batch job to following:

Col1
2
3
4

The result is, as soon as I change 1 to 2, this violates the unique constraint and the batch job is stopped. Although, after finishing the batch job, the constraint would be fulfilled again.

How do I solve that problem?

Use case

I'm trying to rename a list of files in the media store via contentResolver.applyBatch(MediaStore.AUTHORITY, operations) and this throws an constraint violation exception...


Solution

  • In such case that renaming elements might cause collisions on a unique column, you need to apply the transformation in a safe order.

    Basically instead of asking the content provider to perform the following operations

    rename 1 → 2
    rename 2 → 3
    rename 3 → 4
    

    You should ask

    rename 3 → 4
    rename 2 → 3
    rename 1 → 2
    

    Which always satisfies the unique constraint.

    Also even without the unique constraint, the first method would potentially rename everything to 4