CREATE OR REPLACE PROCEDURE "BACKUP_SEQUENCE" (p#batch_id IN NUMBER DEFAULT NULL) ----spu 19.03.2014 central log
IS
  /*
    popis: zalohuje sequence nekolikrat denne s productu i z publicu, pokud nastane
    chyba posila se mail 
  */
  l#batch_id NUMBER;
  l#cnt NUMBER;
BEGIN

  IF p#batch_id IS NULL THEN  --spu 19.03.2014 central log
    -- nikdo ten process neridi, nema rodice, takze ho loguji jako novy
    l#batch_id := neomag.log.begin_batch('neomag.backup_sequence');
  ELSE
    -- uz se vi, ze mam bezet, takze dam vedet, ze zacinam
    l#batch_id := p#batch_id;
    neomag.log.begin_childbatch(p#batch_id);
  END IF;

  DELETE FROM neomag.a_backup_sequence WHERE data_dt < SYSDATE - 30;

  BEGIN
    INSERT INTO neomag.a_backup_sequence (
      data_dt, server, sequence_owner, sequence_name, min_value, max_value, 
      increment_by, cycle_flag, order_flag, cache_size, last_number, stmt
    )
    SELECT 
      SYSDATE AS data_dt, 'PRODUCT' AS server, sequence_owner, sequence_name, min_value, max_value, 
      increment_by, cycle_flag, order_flag, cache_size, last_number,
      ' create sequence neomag.' || sequence_name ||
      ' minvalue ' || min_value ||
      ' maxvalue ' || max_value ||
      ' start with ' || to_char(last_number + increment_by) ||
      ' increment by ' || increment_by ||
      ' cache ' || cache_size || DECODE(cycle_flag, 'Y', ' cycle') || ';' AS stmt
    FROM all_sequences a 
    WHERE sequence_owner = 'NEOMAG';
    
    l#cnt := SQL%ROWCOUNT;
  EXCEPTION
    WHEN OTHERS THEN
      neomag.mail.sendMessage('neomag@product.cekia.cz', 'pukl@cekia.cz;danda@cekia.cz', '!!! nesly stahnout sequence neomagu z PRODUCTU', SQLERRM);
  END;

  BEGIN
    INSERT INTO neomag.a_backup_sequence (
      data_dt, server, sequence_owner, sequence_name, min_value, max_value, 
      increment_by, cycle_flag, order_flag, cache_size, last_number, stmt
    )
    SELECT 
      SYSDATE AS data_dt, 'PRODUCT' AS server, sequence_owner, sequence_name, min_value, max_value, 
      increment_by, cycle_flag, order_flag, cache_size, last_number,
      ' create sequence neomag.' || sequence_name ||
      ' minvalue ' || min_value ||
      ' maxvalue ' || max_value ||
      ' start with ' || to_char(last_number + increment_by) ||
      ' increment by ' || increment_by ||
      ' cache ' || cache_size || DECODE(cycle_flag, 'Y', ' cycle') || ';' AS stmt
    FROM all_sequences@NEOMAG.PUBLIC_LINK.BISNODE.CZ a 
    WHERE sequence_owner = 'NEOMAG';

    l#cnt := l#cnt + SQL%ROWCOUNT;
  EXCEPTION
    WHEN OTHERS THEN
      neomag.mail.sendMessage('neomag@product.cekia.cz', 'pukl@cekia.cz;danda@cekia.cz', '!!! nesly stahnout sequence neomagu z PUBLICU', SQLERRM);
  END;

  COMMIT;
  neomag.log.end_batch(l#batch_id, neomag.log.c#ok, l#cnt);

EXCEPTION 
  WHEN OTHERS THEN
    neomag.log.end_batch(l#batch_id, neomag.log.c#error, NULL, 'EXCEPTION:' || DBMS_UTILITY.FORMAT_ERROR_STACK);

END backup_sequence;
