Wednesday, 31 October 2018

Room: deleting a ForeignKey or setting the ForeignKey to a default value

I have the following entities:

@Entity(indices  = {@Index("address")},
    foreignKeys = @ForeignKey(
    entity = Address.class,
    parentColumns = "address",
    childColumns = "address",
    onUpdate = CASCADE,
    onDelete = SET_DEFAULT))
public class Human {
    @PrimaryKey(autoGenerate = true)
    public long id;

    @NonNull
    public String name;

    @NonNull
    public String address;
}

@Entity
public class Address {

    @PrimaryKey
    @NonNull
    public String address;

    public int someInt;
}

I add "humans" with different addresses which I later try to delete or edit using:

@Insert(onConflict = REPLACE)
void add(Human human);

Options that I see and problems with them:

  1. I have a list of addresses of which one is "default". When I delete an address, I would like the "Humans" residing at the deleted address to "move" to "default". I used:

    @Query("delete from Address where address = :address")
    void deleteAddress(String address);
    
    

so onDelete = SET_DEFAULT does not seem to work as I imagined if I set a default value to address in the Human Entity.

This currently fails with: NOT NULL constraint failed.

  1. An alternative to the deletion would be to edit an address and set it to "default" and thus merging with the existing "default" entry. I tried:

    @Query("update Address SET address = :address WHERE address = :addressToEdit")
    void editAddress(String addressToEdit, String newAddress);
    
    

This currently fails with: UNIQUE constraint failed. because there's already an address with the same name, obviously.

  1. Setting the address to @Nullable in both Entities. In this way, the "default" address is null. This adds extra complexity to my solution(would not prefer it) and it seems that I'm not able to query the Humans with a null address using the following code because it does not return anything.

    @Query("select * from Human where address = :address")
    LiveData<List<Human>> getHumans(String address);
    
    

How can I achieve this setting to default of a deleted address(foreign key)?



from Room: deleting a ForeignKey or setting the ForeignKey to a default value

No comments:

Post a Comment