-- Make receipt aliases user-scoped with optional admin-managed global fallback.
ALTER TABLE `ReceiptAlias`
  ADD COLUMN `ownerId` INT NULL,
  ADD COLUMN `isGlobal` BOOLEAN NOT NULL DEFAULT false;

-- Existing aliases become global aliases.
UPDATE `ReceiptAlias`
SET `isGlobal` = true
WHERE `isGlobal` = false;

-- Replace previous global unique key on receiptName.
ALTER TABLE `ReceiptAlias`
  DROP INDEX `ReceiptAlias_receiptName_key`;

-- Add scoped uniqueness and lookup indexes.
ALTER TABLE `ReceiptAlias`
  ADD UNIQUE INDEX `ReceiptAlias_receiptName_ownerId_isGlobal_key`(`receiptName`, `ownerId`, `isGlobal`),
  ADD INDEX `ReceiptAlias_ownerId_idx`(`ownerId`),
  ADD INDEX `ReceiptAlias_isGlobal_idx`(`isGlobal`);

-- Link aliases to owner when user-scoped.
ALTER TABLE `ReceiptAlias`
  ADD CONSTRAINT `ReceiptAlias_ownerId_fkey`
  FOREIGN KEY (`ownerId`) REFERENCES `User`(`id`)
  ON DELETE CASCADE ON UPDATE CASCADE;
