# Generated by Django 4.2.2 on 2023-06-18 10:58

from django.db import migrations

SQL = """
CREATE TABLE trigger_audit_entries_v2 (
    object_table character varying(128) NOT NULL,
    object_payload JSONB NOT NULL,
    audit_entry_created timestamp with time zone DEFAULT now() NOT NULL,
    audit_txid_current bigint NOT NULL,
    audit_operation character varying(32) NOT NULL,
    audit_version integer NOT NULL
) PARTITION BY RANGE (audit_entry_created);

CREATE INDEX idx_trigger_audit_entries_v2
    ON trigger_audit_entries_v2
    USING GIN (object_payload);

CREATE VIEW trigger_audit_entries_v2_view AS (
    SELECT
        ROW_NUMBER() OVER () as "id",
        object_table,
        object_payload,
        audit_entry_created,
        audit_txid_current,
        audit_operation,
        audit_version
    FROM
        trigger_audit_entries_v2
);

CREATE FUNCTION trigger_audit_entry_creator_func_v2() RETURNS TRIGGER AS $scr$
    DECLARE
        object_payload jsonb;
    BEGIN
        IF (TG_OP = 'INSERT') THEN
            object_payload  = to_jsonb(NEW);
        ELSIF (TG_OP = 'UPDATE') THEN
            object_payload  = to_jsonb(NEW);
        ELSIF (TG_OP = 'DELETE') THEN
            object_payload  = to_jsonb(OLD);
        ELSE
            RAISE EXCEPTION 'Unexpected TG_OP = %', TG_OP;
        END IF;

        INSERT INTO trigger_audit_entries_v2 (
                object_table,
                object_payload,
                audit_entry_created,
                audit_txid_current,
                audit_operation,
                audit_version
            )
            SELECT
                TG_TABLE_NAME,
                object_payload,
                now(),
                txid_current(),
                TG_OP,
                2;
        RETURN NULL;
    END;
$scr$ LANGUAGE plpgsql;
"""


class Migration(migrations.Migration):
    dependencies = [
        ("django_partitioned_audit", "0001_initial"),
    ]

    operations = [migrations.RunSQL(SQL)]
