# -*- coding: utf-8 -*-
# Generated by Django 1.11b1 on 2017-03-02 20:56
from __future__ import unicode_literals

from django.db import migrations


class Migration(migrations.Migration):
    """Set child accounts to have the same type as their parent"""

    dependencies = [("hordak", "0015_auto_20170302_2109")]

    operations = [
        migrations.RunSQL(
            """
            CREATE OR REPLACE FUNCTION check_account_type()
                RETURNS TRIGGER AS
            $$
            BEGIN
                IF NEW.parent_id::BOOL THEN
                    NEW.type = (SELECT type FROM hordak_account WHERE id = NEW.parent_id);
                END IF;
                RETURN NEW;
            END;
            $$
            LANGUAGE plpgsql;
            """,
            "DROP FUNCTION check_account_type()",
        ),
        migrations.RunSQL(
            """
            CREATE TRIGGER check_account_type_trigger
            BEFORE INSERT OR UPDATE ON hordak_account
            FOR EACH ROW
            WHEN (pg_trigger_depth() = 0)
            EXECUTE PROCEDURE check_account_type();
            """,
            "DROP TRIGGER IF EXISTS check_account_type_trigger ON hordak_account",
        ),
    ]
