{% macro insert_A_TASK_HISTORY_SOURCE(table_name, a_task_history_key, column_name, sq_data_exists) %}

{% if execute %}

    {% set insert_A_TASK_HISTORY_SOURCE %}
        {% if column_name | length %}
            {% if sq_data_exists == 0 %}
                INSERT INTO {{ source('control_tables','A_TASK_HISTORY_SOURCE') }} (A_TASK_HISTORY_SOURCE_KEY, A_TASK_HISTORY_KEY, SOURCE_NAME, ROW_COUNT, SERVICE_NAME)
                SELECT {{ source('control_sequences','A_TASK_HISTORY_SOURCE_SEQ') }}.NEXTVAL, {{ a_task_history_key }}, '{{ table_name }}', 0, '{{ var("input_service_name") }}' FROM dual
            {% else %}
                INSERT INTO {{ source('control_tables','A_TASK_HISTORY_SOURCE') }} (A_TASK_HISTORY_SOURCE_KEY, A_TASK_HISTORY_KEY, A_WORKFLOW_HISTORY_SOURCE_KEY, SOURCE_NAME, ROW_COUNT, SERVICE_NAME)
                SELECT {{ source('control_sequences','A_TASK_HISTORY_SOURCE_SEQ') }}.NEXTVAL, {{ a_task_history_key }}, col_name, '{{ table_name }}', ct, '{{ var("input_service_name") }}'
                FROM (
                    SELECT {{ column_name }} col_name, count(*) ct
                    FROM {{ table_name }}
                    GROUP BY {{ column_name }}
                )
            {% endif %}
        {% else %}
            INSERT INTO {{ source('control_tables','A_TASK_HISTORY_SOURCE') }} (A_TASK_HISTORY_SOURCE_KEY, A_TASK_HISTORY_KEY, SOURCE_NAME, ROW_COUNT, SERVICE_NAME)
            SELECT {{ source('control_sequences','A_TASK_HISTORY_SOURCE_SEQ') }}.NEXTVAL, {{ a_task_history_key }}, '{{ table_name }}', ct, '{{ var("input_service_name") }}'
            FROM (
                SELECT count(*) ct
                FROM {{ table_name }}
            )
        {% endif %}
    {% endset %}

    {% do run_query(insert_A_TASK_HISTORY_SOURCE) %}

{% endif %}

{% endmacro %}
