# Generated by Django 4.0.5 on 2023-03-02 19:55

from django.db import migrations


class Migration(migrations.Migration):
    dependencies = [
        (
            "metering_billing",
            "0220_remove_invoicelineitem_associated_plan_component_and_more",
        ),
    ]

    operations = [
        migrations.RunSQL(
            """
            CREATE OR REPLACE FUNCTION update_billing_record()
            RETURNS TRIGGER AS $$
            BEGIN
                SELECT
                    s.customer_id,
                    s.billing_plan_id
                INTO
                    NEW.customer_id,
                    NEW.billing_plan_id
                FROM
                    metering_billing_subscriptionrecord s
                WHERE
                    s.id = NEW.subscription_id;

                RETURN NEW;
            END;
            $$ LANGUAGE plpgsql;
            """,
            """ 
            DROP FUNCTION IF EXISTS update_billing_record();
            """,
        ),
        migrations.RunSQL(
            """
            CREATE TRIGGER billing_record_trigger
            BEFORE INSERT OR UPDATE ON metering_billing_billingrecord
            FOR EACH ROW EXECUTE FUNCTION update_billing_record();
            """
        ),
    ]
