From 030e8dbd75a40ce429856555176bfead94f3f88f Mon Sep 17 00:00:00 2001 From: Richard Fuchs Date: Fri, 7 Mar 2014 10:42:19 -0500 Subject: [PATCH] MT#6013 add unique key to contract_balances --- db_scripts/diff/15045.down | 5 +++++ db_scripts/diff/15045.up | 43 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 db_scripts/diff/15045.down create mode 100644 db_scripts/diff/15045.up diff --git a/db_scripts/diff/15045.down b/db_scripts/diff/15045.down new file mode 100644 index 00000000..6452d259 --- /dev/null +++ b/db_scripts/diff/15045.down @@ -0,0 +1,5 @@ +use billing; + +alter table contract_balances + drop key balance_interval, + add key contractid_idx (contract_id); diff --git a/db_scripts/diff/15045.up b/db_scripts/diff/15045.up new file mode 100644 index 00000000..c9afbce1 --- /dev/null +++ b/db_scripts/diff/15045.up @@ -0,0 +1,43 @@ +use billing; + +delimiter ;; + +create procedure del_dupes() +begin + declare done int default false; + declare cid, c int; + declare s, e datetime; + declare x cursor for select contract_id, start, end, count(*) ct + from contract_balances group by contract_id, start, end having ct > 1; + declare continue handler for sqlstate '02000' set done = true; + + open x; + + rl: loop + fetch x into cid, s, e, c; + if done then + leave rl; + end if; + set c = c - 1; + delete from contract_balances where contract_id = cid and start = s + and end = e and cash_balance = 0 and cash_balance_interval = 0 and + free_time_balance = 0 and free_time_balance_interval = 0 + and invoice_id is null limit c; + end loop; + + close x; +end;; + +delimiter ; +call del_dupes; +drop procedure del_dupes; + + + +-- If this throws an error, then the contracts_balances table contains entries +-- that the above procedure could not delete, which are duplicate entries with +-- non-zero balances. Manual cleanup is required. + +alter table contract_balances + add unique key balance_interval (contract_id, start, end), + drop key contractid_idx;