         
declare
snapid     	alias for $1;
sessid  	alias for $2;
textstr text;
rec RECORD;
begin
-- Confirm snap ID
PERFORM 1 from edb$snap where edb_id = snapid;
if not found then
     raise exception 'Snapshot identifier % does not exist', snapid::text;
END IF;
textstr := 'ID   '||' '||rpad('USER',10,' ')||rpad('SEQ',5,' ')||' '||rpad('WAIT NAME',24,' ')||' '||
rpad('ELAPSED',12,' ')||' '||rpad('File',6,' ')||' '||rpad('Name',20,' ')||' '||rpad('# of Blk',10,' ')||' '||rpad('Sum of Blks',12,' ');
return next textstr;
textstr := '---------------------------------------------------------------------------------------------------';
return next textstr;
for rec in (
   select b.backend_id, 
          w.usename,
	  b.seq,
          b.wait_name,
          b.elapsed,   		 
          b.p1,     
          c.relname as relname,   
	  b.p2 as p2,     
	  sum(b.p3) as p3          
            from  edb$session_wait_history  as b,
                  edb$session_waits as w,
                  (select relfilenode,relname from pg_class
                  union
                  select 0,'N/A') as c  -- added this to handle file=0 for query plan
                  where b.edb_id              	= snapid
                  and b.backend_id              = sessid
		  and b.backend_id              = w.backend_id
		  and b.dbname                  = w.dbname
		  and b.wait_name               = w.wait_name
		  and b.edb_id                  = w.edb_id
                  and b.p1                      = c.relfilenode
             group by b.backend_id, 
          w.usename,
	  b.seq,
          b.wait_name,
          b.elapsed,
           b.p1 , c.relname, b.p2      
              order by backend_id, seq   
         )  LOOP   
                                 
textstr := rec.backend_id||' '||rpad(rec.usename,10,' ')||' '||rpad(rec.seq::text,5,' ')||' '||rpad(rec.wait_name,24,' ')||
' '||rpad(rec.elapsed::text,12,' ')||' '||rpad(rec.p1::text,6,' ')||' '||rpad(rec.relname,20,' ')||' '||rpad(rec.p2::text,10,' ')||' '||rpad(rec.p3::text,12,' ');
return next textstr;
end loop;
return;
end;
   