<?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="bshah">
        <sql dbms="mysql" endDelimiter=";;" splitStatements="true" stripComments="true">
        <![CDATA[
            CREATE TABLE IF NOT EXISTS `ROLLBACK-releases_missing_sales_date` (
                `release_id` INT(11) UNSIGNED NOT NULL,
                    `sale_start_date` DATE DEFAULT NULL,
                        PRIMARY KEY (`release_id`)
                    ) ENGINE=INNODB DEFAULT CHARSET=utf8;;

            INSERT INTO `ROLLBACK-releases_missing_sales_date`
                SELECT release_id, sale_start_date FROM releases
                    WHERE release_date IS NOT NULL AND release_date <> '0000-00-00'
                        AND (sale_start_date IS NULL OR sale_start_date = '0000-00-00')
                            AND release_status IN ('in_content');;

            UPDATE releases
                SET sale_start_date = release_date
                    WHERE release_date IS NOT NULL AND release_date <> '0000-00-00'
                        AND (sale_start_date IS NULL OR sale_start_date = '0000-00-00')
                            AND release_status IN ('in_content');;
        ]]>
        </sql>
        <rollback>
            <![CDATA[
            UPDATE releases AS r
                INNER JOIN `ROLLBACK-releases_missing_sales_date` AS rmsd ON rmsd.release_id = r.release_id
                    SET r.sale_start_date = rmsd.sale_start_date;;
            ]]>
        </rollback>
    </changeSet>
</databaseChangeLog>