<?xml version="1.0" encoding="utf-8"?>
<databaseChangeLog
    xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
    xmlns:ext="http://www.liquibase.org/xml/ns/dbchangelog-ext"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.5.xsd
                        http://www.liquibase.org/xml/ns/dbchangelog-ext http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-ext.xsd">

    <changeSet id="20190506000000-1" author="mhierweck,mhoennig" dbms="postgresql">
        <createTable tableName="history">

            <column name="history_transaction" type="bigint">
                <constraints primaryKey="true" nullable="false"/>
            </column>

            <column name="history_timestamp" type="timestamp">
                <constraints nullable="false" />
            </column>

        </createTable>

    </changeSet>

    <changeSet id="20190506000000-2" author="mhierweck,mhoennig" dbms="postgresql">
        <createProcedure>
            CREATE OR REPLACE FUNCTION historicize()
                RETURNS trigger
            AS $$
                BEGIN
                    IF (TG_OP = 'INSERT') OR (TG_OP = 'UPDATE') THEN
                        EXECUTE 'INSERT INTO history VALUES (txid_current(), now()) ON CONFLICT DO NOTHING';
                        EXECUTE format('INSERT INTO %I_history VALUES (DEFAULT, txid_current(), False, $1.*)', TG_TABLE_NAME) USING NEW;
                        RETURN NEW;
                    ELSE -- assuming TG_OP = 'DELETE'
                        EXECUTE 'INSERT INTO history VALUES (txid_current(), now()) ON CONFLICT DO NOTHING';
                        EXECUTE format('INSERT INTO %I_history VALUES (DEFAULT, txid_current(), True, $1.*)', TG_TABLE_NAME) USING OLD;
                        RETURN OLD;
                    END IF;
                END;
            $$
            LANGUAGE plpgsql;
        </createProcedure>
    </changeSet>


</databaseChangeLog>
