From 836616a0604e9964867474438cc63c4be2df5cb4 Mon Sep 17 00:00:00 2001
From: Jonathan Druart <jonathan.druart@bugs.koha-community.org>
Date: Tue, 21 Jan 2020 15:01:51 +0100
Subject: [PATCH] Bug 21674: Remove duplicates from library_groups before
 adding the uniq constraint

To avoid to make it fails if duplicates existed prior to this change

Credit for the SQL query goes to Nick, thanks!
---
 installer/data/mysql/atomicupdate/bug_21674.perl | 10 ++++++++++
 1 file changed, 10 insertions(+)

diff --git a/installer/data/mysql/atomicupdate/bug_21674.perl b/installer/data/mysql/atomicupdate/bug_21674.perl
index 3bcf5f9f76..418f3f5d24 100644
--- a/installer/data/mysql/atomicupdate/bug_21674.perl
+++ b/installer/data/mysql/atomicupdate/bug_21674.perl
@@ -2,6 +2,16 @@ $DBversion = 'XXX'; # will be replaced by the RM
 if( CheckVersion( $DBversion ) ) {
     if( !index_exists( 'library_groups', 'library_groups_uniq_2' ) ) {
         $dbh->do(q|
+            DELETE FROM library_groups
+            WHERE id NOT IN (
+                SELECT MIN(id)
+                FROM library_groups
+                WHERE parent_id IS NOT NULL
+                GROUP BY parent_id, branchcode
+            )
+            AND parent_id IS NOT NULL;
+        |);
+        $dbh->do(q|
             ALTER TABLE library_groups
             ADD UNIQUE KEY library_groups_uniq_2 (parent_id, branchcode)
         |);
-- 
2.11.0