{% materialization table_if_rows_exist, adapter='oracle' %}

    {%- set target_relation = this -%}

    -- Count the number of rows in the source table
    {#-- Use the compiled SQL of the model to count rows --#}
    {%- set count_query %}
        select count(*) as row_count from (
            {{ model.compiled_sql }}
        )
    {%- endset %}

    {#-- Execute the count query --#}
    {%- set result = run_query(count_query) -%}
    {%- set num_rows = result.columns[0].values()[0]|int -%}

    {#-- Proceed only if there are rows --#}
    {%- if num_rows > 0 -%}
        {{ log(num_rows ~ ' rows found in source data. Executing model.', info=True) }}

        {#-- collect hooks --#}
        {% set pre_hooks = control_model_start() %}
        {% set post_hooks = control_model_end('TRG') %}
        
        {#-- run pre_hooks --#}
        {% do run_hooks(pre_hooks, inside_transaction=True) %}

        {#-- Define a temporary relation with a unique name --#}
        {%- set tmp_relation = api.Relation.create(
            schema=target_relation.schema,
            identifier=target_relation.identifier + '_tmp'
        ) %}

        {#-- Create a temporary table with the model's SQL --#}
        {% set ctas_sql = 'CREATE TABLE ' ~ tmp_relation ~ ' AS ' ~ model.compiled_sql %}
        {% call statement('main') %}
           {{ ctas_sql }}
        {% endcall %}

        {#-- Drop the existing table if it exists --#}
        {%- if adapter.get_relation(target_relation.database, target_relation.schema, target_relation.identifier) is not none -%}
          {{ log('Dropping target table  ' ~ target_relation.identifier, info=True) }}
          {% do run_query('DROP TABLE ' ~ target_relation.schema ~ '.' ~ target_relation.identifier) %}
        {%- endif -%}

        {#-- Rename the temporary table to the target name --#}
        {{ log('Renaming temporary table to target table', info=True) }}
        {% do run_query('ALTER TABLE ' ~ tmp_relation ~ ' RENAME TO ' ~ target_relation.identifier) %}

        {#-- run post_hooks --#}
        {% do run_hooks(post_hooks, inside_transaction=True) %}
    {%- else -%}
        {#-- Do nothing; leave the target table untouched --#}
        {{ log('No rows in source data. Skipping model execution.', info=True) }}
        {% call statement('main') %}
            SELECT 1 FROM DUAL
        {% endcall %}
    {%- endif -%}

    {#-- Return the target relation to dbt --#}
    {{ return({'relations': [target_relation]}) }}

{% endmaterialization %}
 