 language plpgsql AS $$
 declare
   tables record;
-  audits record;
+  from_data record;
+  to_data record;
 
   where_clause text;
   table_name text;

  loop  
    table_name = current_schema || '.' || format('%I', tables.table_name);

    from_sql := 
      format(
'select a.*
from %s a
%s
',
       tables.table_name,
       where_clause
    );

    for audits in execute from_sql
    loop 
      raise notice '%', from_sql;
      execute from_sql;

      to_sql := 
        format(
'select a.*
from %s a
where audit_date < ''%s''::timestamp
order by audit_date desc
limit 1',
         tables.table_name,
         audits.audit_date
      );   

      raise notice '%', to_sql;
      execute to_sql;
    end loop;
  end loop;
end;
$$;



-- Range test
select

  columns_list text;
  columns_type text;
  columns_insert text;

  reserved_columns varchar[];
begin
  reserved_columns := array['audit_action', 'audit_date', 'audit_request', 'audit_txid', 'audit_user'];

  where_clause := 'WHERE 1=1';
  if (audit_txid is not null) then
    where_clause := where_clause || ' AND audit_txid = ' || audit_txid;
