set serveroutput on;

drop table temp_lck;
create table temp_lck
( 
    lck_object_id                 number(9, 0) not null,
    lck_object_type               varchar2(50) not null,
    lck_type                      char not null,
    lck_thread_id                 varchar2(200) not null,
    lck_jvm_id                    varchar2(200) not null,
    lck_tx_id                     varchar2(200),
    primary key (lck_object_id, lck_object_type, lck_jvm_id, lck_thread_id, lck_type)
) organization index tablespace users overflow tablespace indx;

drop index iutl_lck_0;
create index iutl_lck_0 on temp_lck (
        lck_jvm_id,
        lck_thread_id,
        lck_type
) tablespace indx  NOLOGGING;
commit;

--- Avoid orphan LCK records while loading the new LCK table
declare
cursor lck_cur is 
  select * from lck 
  where lck_object_type in ('CATALOG','CATEGORY','CATEGORY_TREE','COLLABORATION_AREA','PATHS_FOR_CATEGORY','WORKFLOW_EVENT') 
  OR (lck_object_type = 'ITEM' and exists (select 1 from itm where lck_object_id = itm_id and itm_next_version_id = 999999999));
i number := 0;
j number := 0;
begin
  for lck_rec in lck_cur
  loop
    i:= i + 1;
    begin
        insert into temp_lck values lck_rec;
      exception
      when others then
        dbms_output.put_line('Insert error for lck_object_id ' || lck_rec.lck_object_id || ' ' || sqlerrm ||'  '|| sqlcode);
        j:= j + 1;
    end;
    if mod(i,100000) = 0 then
      dbms_output.put_line('Work committed at '|| i ||' rows');
      commit work;
    end if;
  end loop;
  dbms_output.put_line(j ||' rows in error');
  dbms_output.put_line(i ||' rows processed');
end;
/

drop table tutl_lck_lock;

rename temp_lck to tutl_lck_lock;

EXEC DBMS_STATS.GATHER_TABLE_STATS(NULL,'TUTL_LCK_LOCK',ESTIMATE_PERCENT => 100, METHOD_OPT => 'FOR ALL COLUMNS SIZE AUTO', DEGREE => 2, CASCADE => TRUE);
