/*
 * See the NOTICE file distributed with this work for additional
 * information regarding copyright ownership.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

package com.xpn.xwiki.store.migration.hibernate;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.jdbc.Work;
import org.xwiki.component.annotation.Component;
import org.xwiki.model.EntityType;
import org.xwiki.model.reference.EntityReference;
import org.xwiki.model.reference.EntityReferenceSerializer;

import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.store.XWikiHibernateBaseStore.HibernateCallback;
import com.xpn.xwiki.store.migration.DataMigrationException;
import com.xpn.xwiki.store.migration.XWikiDBVersion;

/**
 * Migration for XWIKI-12153: Implement nested spaces support at database level.
 * <p>
 * Convert existing values in documents space field from single space name to complete space local reference.
 *
 * @version $Id$
 * @since 7.2M1
 */
@Component
@Named("R72000XWIKI12153")
@Singleton
public class R72000XWIKI12153DataMigration extends AbstractHibernateDataMigration
{
    @Inject
    private EntityReferenceSerializer<String> serializer;

    @Override
    public String getDescription()
    {
        return "Convert document space name into space reference";
    }

    @Override
    public XWikiDBVersion getVersion()
    {
        return new XWikiDBVersion(72000);
    }

    @Override
    public void hibernateMigrate() throws DataMigrationException, XWikiException
    {
        getStore().executeWrite(getXWikiContext(), new HibernateCallback<Object>()
        {
            @Override
            public Object doInHibernate(Session session) throws HibernateException, XWikiException
            {
                session.doWork(new R72000Work());
                return Boolean.TRUE;
            }
        });
    }

    private class R72000Work implements Work
    {
        @Override
        public void execute(Connection connection) throws SQLException
        {
            try (PreparedStatement statement =
                connection.prepareStatement("UPDATE xwikidoc set XWD_WEB = ? WHERE XWD_WEB = ?")) {
                // Search for all document spaces that should be escaped
                try (ResultSet result =
                    statement.executeQuery("select DISTINCT XWD_WEB from xwikidoc"
                        + " where XWD_WEB like '%.%' OR XWD_WEB like '%\\\\%' OR XWD_WEB like '%:%'")) {
                    while (result.next()) {
                        // Get space name
                        String spaceName = result.getString(1);

                        // Convert the space name into a space reference
                        String spaceReference = serializer.serialize(new EntityReference(spaceName, EntityType.SPACE));

                        statement.setString(1, spaceReference);
                        statement.setString(1, spaceName);

                        // Add a conversion to the list
                        statement.addBatch();
                    }

                    // Do all the changes
                    statement.executeBatch();
                }
            }
        }
    }
}

@@ -1057,16 +1057,43 @@
 ception;
+%0Aimport java.sql.Statement;
 %0A%0Aimport
@@ -2991,58 +2991,109 @@
     
-try (PreparedStatement statement =%0A               
+// Search for all document spaces that should be escaped%0A            try (Statement selectStatement =
  con
@@ -3104,14 +3104,13 @@
 ion.
-prepar
+creat
 eSta
@@ -3120,136 +3120,12 @@
 ent(
-%22UPDATE xwikidoc set XWD_WEB = ? WHERE XWD_WEB = ?%22)) %7B%0A                // Search for all document spaces that should be escaped
+)) %7B
 %0A   
@@ -3174,32 +3174,38 @@
                s
+electS
 tatement.execute
@@ -3379,155 +3379,689 @@
     
-while (result.next()) %7B%0A                        // Get space name%0A                        String spaceName = result.getString(1);%0A%0A                
+convert(connection, result);%0A                %7D%0A            %7D%0A        %7D%0A    %7D%0A%0A    private void convert(Connection connection, ResultSet result) throws SQLException%0A    %7B%0A        if (result.next()) %7B%0A            try (PreparedStatement statement =%0A                connection.prepareStatement(%22UPDATE xwikidoc set XWD_WEB = ? WHERE XWD_WEB = ?%22)) %7B%0A                do %7B%0A                    addBatch(statement, result.getString(1));%0A                %7D while (result.next());%0A%0A                // Do all the changes%0A                statement.executeBatch();%0A            %7D%0A        %7D%0A    %7D%0A%0A    private void addBatch(PreparedStatement statement, String spaceName) throws SQLException%0A    %7B%0A
     
@@ -4113,32 +4113,16 @@
 ference%0A
-                
         
@@ -4218,32 +4218,16 @@
 ACE));%0A%0A
-                
         
@@ -4266,32 +4266,16 @@
 rence);%0A
-                
         
@@ -4310,32 +4310,16 @@
 Name);%0A%0A
-                
         
@@ -4350,32 +4350,16 @@
 he list%0A
-                
         
@@ -4384,161 +4384,8 @@
 ();%0A
-                    %7D%0A%0A                    // Do all the changes%0A                    statement.executeBatch();%0A                %7D%0A            %7D%0A        %7D%0A
     

Implement nested spaces support at database level * improve a bit the migration codestyle