issue 1615: delete removed relations before adding

This can prevent duplicate key errors. Fixes issue #1615.