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

from django.db import migrations


class Migration(migrations.Migration):

    dependencies = [("hordak", "0012_account_full_code")]

    operations = [
        migrations.RunSQL(
            """
            CREATE OR REPLACE FUNCTION update_full_account_codes()
                RETURNS TRIGGER AS
            $$
            BEGIN
                UPDATE
                    hordak_account AS a
                SET
                    full_code = (
                        SELECT string_agg(code, '' order by lft)
                        FROM hordak_account AS a2
                        WHERE a2.lft <= a.lft AND a2.rght >= a.rght AND a.tree_id = a2.tree_id
                    );
                RETURN NULL;
            END;
            $$
            LANGUAGE plpgsql;
            """,
            "DROP FUNCTION update_full_account_codes()",
        ),
        migrations.RunSQL(
            """
            CREATE TRIGGER update_full_account_codes_trigger
            AFTER INSERT OR UPDATE OR DELETE ON hordak_account
            WHEN (pg_trigger_depth() = 0)
            EXECUTE PROCEDURE update_full_account_codes();
            """,
            "DROP TRIGGER IF EXISTS update_full_account_codes_trigger ON hordak_account;",
        ),
    ]
