-- Keep the most recently updated row for any Firebase token before adding
-- the unique index. This prevents a shared device token from staying attached
-- to multiple users after account switching.
DELETE stale
FROM `DeviceToken` stale
JOIN `DeviceToken` fresh
  ON stale.`token` = fresh.`token`
 AND (
   stale.`updatedAt` < fresh.`updatedAt`
   OR (stale.`updatedAt` = fresh.`updatedAt` AND stale.`id` < fresh.`id`)
 );

CREATE UNIQUE INDEX `DeviceToken_token_key` ON `DeviceToken`(`token`);
