<?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="jian">
        <sql dbms="mysql" endDelimiter=";;" splitStatements="true" stripComments="true">
        <![CDATA[
			DROP PROCEDURE IF EXISTS `sp_remove_asset_by_phys_loc`;;

			CREATE DEFINER=`theorchard_dd`@`127.0.0.1` PROCEDURE `sp_remove_asset_by_phys_loc`(IN the_upc BIGINT, IN the_type INT, IN phys_loc_id INT)
			BEGIN
				IF phys_loc_id > 0 THEN
					UPDATE asset_location al
					INNER JOIN asset a ON a.asset_id = al.asset_id
					INNER JOIN asset_type ta ON ta.asset_type_id = a.asset_type_id
					INNER JOIN storage_drive sd ON sd.storage_drive_id = al.storage_drive_id
					INNER JOIN storage s ON s.storage_id = sd.storage_id
					SET al.status = 'N', last_modified = NOW() 
					WHERE a.upc = the_upc 
						AND (a.asset_type_id = the_type OR ta.parent_asset_type_id = the_type)
						AND s.physical_location_id = phys_loc_id;
				ELSE
					UPDATE asset_location al
					INNER JOIN asset a ON a.asset_id = al.asset_id
					INNER JOIN asset_type ta ON ta.asset_type_id = a.asset_type_id
					SET al.status = 'N', last_modified = NOW() 
					WHERE a.upc = the_upc 
						AND (a.asset_type_id = the_type OR ta.parent_asset_type_id = the_type);
				END IF;
			END;;
        ]]>
        </sql>
        <rollback>
            <sql dbms="mysql" endDelimiter=";;" splitStatements="true" stripComments="true">
            <![CDATA[
				DROP PROCEDURE IF EXISTS `sp_remove_asset_by_phys_loc`;;
			]]>
			</sql>
		</rollback>
    </changeSet>
</databaseChangeLog>
