33 lines
1.8 KiB
SQL
33 lines
1.8 KiB
SQL
-- Bring databases that already recorded an earlier 003_attachments layout
|
|
-- forward without dropping attachment metadata or stored object references.
|
|
ALTER TABLE attachments ADD COLUMN IF NOT EXISTS variants JSONB NOT NULL DEFAULT '[]'::jsonb;
|
|
ALTER TABLE attachments ADD COLUMN IF NOT EXISTS error_code VARCHAR(64);
|
|
ALTER TABLE attachments ADD COLUMN IF NOT EXISTS width INTEGER;
|
|
ALTER TABLE attachments ADD COLUMN IF NOT EXISTS height INTEGER;
|
|
ALTER TABLE attachments ALTER COLUMN width DROP NOT NULL;
|
|
ALTER TABLE attachments ALTER COLUMN height DROP NOT NULL;
|
|
|
|
ALTER TABLE message_attachments ADD COLUMN IF NOT EXISTS chat_id UUID;
|
|
UPDATE message_attachments AS link
|
|
SET chat_id = message.chat_id
|
|
FROM messages AS message
|
|
WHERE message.id = link.message_id
|
|
AND (link.chat_id IS NULL OR link.chat_id <> message.chat_id);
|
|
ALTER TABLE message_attachments ALTER COLUMN chat_id SET NOT NULL;
|
|
|
|
-- Drop referencing foreign keys before replacing their referenced unique keys.
|
|
ALTER TABLE message_attachments DROP CONSTRAINT IF EXISTS message_attachments_message_chat_fk;
|
|
ALTER TABLE message_attachments DROP CONSTRAINT IF EXISTS message_attachments_attachment_chat_fk;
|
|
|
|
ALTER TABLE messages DROP CONSTRAINT IF EXISTS messages_id_chat_id_uq;
|
|
ALTER TABLE messages ADD CONSTRAINT messages_id_chat_id_uq UNIQUE (id, chat_id);
|
|
ALTER TABLE attachments DROP CONSTRAINT IF EXISTS attachments_id_chat_id_uq;
|
|
ALTER TABLE attachments ADD CONSTRAINT attachments_id_chat_id_uq UNIQUE (id, chat_id);
|
|
|
|
ALTER TABLE message_attachments
|
|
ADD CONSTRAINT message_attachments_message_chat_fk
|
|
FOREIGN KEY (message_id, chat_id) REFERENCES messages(id, chat_id) ON DELETE CASCADE;
|
|
ALTER TABLE message_attachments
|
|
ADD CONSTRAINT message_attachments_attachment_chat_fk
|
|
FOREIGN KEY (attachment_id, chat_id) REFERENCES attachments(id, chat_id) ON DELETE CASCADE;
|