# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-12-09 01:11
from __future__ import unicode_literals

from django.db import migrations


class Migration(migrations.Migration):

    dependencies = [
        ('hordak', '0006_auto_20161209_0108'),
    ]

    operations = [
        migrations.RunSQL(
            """
                CREATE OR REPLACE FUNCTION check_leg_and_account_currency_match()
                    RETURNS trigger AS
                $$
                DECLARE

                BEGIN

                    IF (TG_OP = 'DELETE') THEN
                        RETURN OLD;
                    END IF;

                    PERFORM * FROM hordak_account WHERE id = NEW.account_id AND NEW.amount_currency = ANY(currencies);

                    IF NOT FOUND THEN
                        RAISE EXCEPTION 'Destination account does not support currency %', NEW.amount_currency;
                    END IF;

                    RETURN NEW;
                END;
                $$
                LANGUAGE plpgsql
            """
            ,
            'DROP FUNCTION check_leg_and_account_currency_match()'
        ),

        migrations.RunSQL(
            """
                CREATE CONSTRAINT TRIGGER check_leg_and_account_currency_match_trigger
                AFTER INSERT OR UPDATE OR DELETE ON hordak_leg
                DEFERRABLE INITIALLY DEFERRED
                FOR EACH ROW EXECUTE PROCEDURE check_leg_and_account_currency_match()
            """
            ,
            'DROP TRIGGER IF EXISTS check_leg_and_account_currency_match_trigger ON hordak_leg'
        ),
    ]
