# Generated by Django 4.2.17 on 2025-03-07 11:43

from django.db import migrations, router


def create_trigger_function(apps, schema_editor):
    PublishedEventQueue = apps.get_model("services_communication", "PublishedEventQueue")
    if not router.allow_migrate_model(schema_editor.connection.alias, PublishedEventQueue):
        return

    if schema_editor.connection.vendor != 'postgresql':
        return

    schema_editor.execute("""
        CREATE OR REPLACE FUNCTION notify_insert_row() RETURNS TRIGGER AS $$
        BEGIN
            PERFORM pg_notify('new_' || TG_TABLE_SCHEMA::text || '_' || TG_TABLE_NAME::text, null);
            RETURN NEW;
        END;
        $$ LANGUAGE plpgsql;
    """)

    schema_editor.execute(f"""
        CREATE TRIGGER notify_new_published_event_trigger
        AFTER INSERT ON {PublishedEventQueue._meta.db_table}
        FOR EACH ROW EXECUTE FUNCTION notify_insert_row();
    """)



class Migration(migrations.Migration):

    dependencies = [
        ('services_communication', '0003_publishedeventqueue_body_and_more'),
    ]

    operations = [
        migrations.RunPython(create_trigger_function),
    ]
