-- dependson: message_0001
-- model: api.models.message
-- description: ConversationUserStatus and Conversation integrity check
-- author: keyang@wanmeizhensuo.com
-- date: 2015.09.25 15:00:00

BEGIN;

ALTER TABLE `api_conversation` ADD COLUMN `uid_hash` char(32) DEFAULT 'LoveMinamiKotoriLoveMinamiKotori' NOT NULL;

CREATE INDEX `idx_uid_hash` ON `api_conversation` (`uid_hash`);

DELIMITER //
CREATE TRIGGER `cvsr_usr_status_unique` BEFORE INSERT ON `api_conversationuserstatus`
FOR EACH ROW
BEGIN
    DECLARE cnt int;
    SELECT COUNT(*) INTO cnt FROM `api_conversationuserstatus` WHERE user_id=NEW.user_id AND conversation_id=NEW.conversation_id;
    IF cnt > 0 THEN
        SIGNAL SQLSTATE VALUE '99999'
        SET MESSAGE_TEXT = 'duplicate entry.';
    END IF;
END;

CREATE TRIGGER `cvsr_uid_hash_unique` BEFORE INSERT ON `api_conversation`
FOR EACH ROW
BEGIN
    DECLARE cnt int;
    SELECT COUNT(*) INTO cnt FROM `api_conversation` WHERE uid_hash=NEW.uid_hash;
    IF cnt > 0 THEN
        SIGNAL SQLSTATE VALUE '99999'
        SET MESSAGE_TEXT = 'duplicate entry.';
    END IF;
END;

//
DELIMITER ;

COMMIT;

