<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog
        xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:ext="http://www.liquibase.org/xml/ns/dbchangelog-ext"
        xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.0.xsd
        http://www.liquibase.org/xml/ns/dbchangelog-ext http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-ext.xsd">
    <changeSet id="1" author="bhavinrshah">
        <sql dbms="mysql" endDelimiter=";;" splitStatements="true" stripComments="true">
        <![CDATA[
            USE `art_relations`;;

            DROP TRIGGER IF EXISTS before_update_release;;

            CREATE DEFINER = 'theorchard'@'10.10.%' TRIGGER `before_update_release` BEFORE UPDATE ON `releases` 
            FOR EACH ROW before_update_release_block: BEGIN

                DECLARE vendorId INT DEFAULT NULL;
                DECLARE projectId INT DEFAULT NULL;

                IF (OLD.vendor_catalog_number <=> LEFT(NEW.vendor_catalog_number,20)) THEN
                    LEAVE before_update_release_block;
                END IF;

                -- exit if release is in_content
                IF (OLD.release_status = 'in_content') THEN
                    LEAVE before_update_release_block;
                END IF;

                SET vendorId = (SELECT v.vendor_id FROM vendor v INNER JOIN artist_info ai ON ai.vendor_id = v.vendor_id WHERE ai.artist_id = NEW.artist_id);

                IF (vendorId IS NULL) THEN
                    LEAVE before_update_release_block;
                END IF;

                CALL sp_insert_and_get_project(vendorId, NEW.subaccount_id, NEW.vendor_catalog_number, NEW.upc, NEW.release_name, NEW.artist_id, projectId);

                SET NEW.project_id = projectId;

            END before_update_release_block;
        ]]>
        </sql>
        <rollback>
            <sql dbms="mysql" endDelimiter=";;" splitStatements="true" stripComments="true">
            <![CDATA[
                USE art_relations;;

                DROP TRIGGER IF EXISTS before_update_release;;
            ]]>
            </sql>
        </rollback>
    </changeSet>
</databaseChangeLog>
